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/src/main/java/net/floodlightcontroller/topology/TopologyManager.java b/src/main/java/net/floodlightcontroller/topology/TopologyManager.java index 0a73fc1f..961d6259 100644 --- a/src/main/java/net/floodlightcontroller/topology/TopologyManager.java +++ b/src/main/java/net/floodlightcontroller/topology/TopologyManager.java @@ -1,1530 +1,1530 @@ /** * Copyright 2013, Big Switch Networks, 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 net.floodlightcontroller.topology; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import net.floodlightcontroller.core.FloodlightContext; import net.floodlightcontroller.core.HAListenerTypeMarker; import net.floodlightcontroller.core.IFloodlightProviderService; import net.floodlightcontroller.core.IFloodlightProviderService.Role; import net.floodlightcontroller.core.IHAListener; import net.floodlightcontroller.core.IOFMessageListener; import net.floodlightcontroller.core.IOFSwitch; import net.floodlightcontroller.core.annotations.LogMessageCategory; import net.floodlightcontroller.core.annotations.LogMessageDoc; import net.floodlightcontroller.core.module.FloodlightModuleContext; import net.floodlightcontroller.core.module.FloodlightModuleException; import net.floodlightcontroller.core.module.IFloodlightModule; import net.floodlightcontroller.core.module.IFloodlightService; import net.floodlightcontroller.core.util.SingletonTask; import net.floodlightcontroller.counter.ICounterStoreService; import net.floodlightcontroller.debugcounter.IDebugCounter; import net.floodlightcontroller.debugcounter.IDebugCounterService; import net.floodlightcontroller.debugcounter.IDebugCounterService.CounterException; import net.floodlightcontroller.debugcounter.IDebugCounterService.CounterType; import net.floodlightcontroller.debugcounter.NullDebugCounter; import net.floodlightcontroller.debugevent.IDebugEventService; import net.floodlightcontroller.debugevent.IEventUpdater; import net.floodlightcontroller.debugevent.NullDebugEvent; import net.floodlightcontroller.debugevent.IDebugEventService.EventColumn; import net.floodlightcontroller.debugevent.IDebugEventService.EventFieldType; import net.floodlightcontroller.debugevent.IDebugEventService.EventType; import net.floodlightcontroller.debugevent.IDebugEventService.MaxEventsRegistered; import net.floodlightcontroller.linkdiscovery.ILinkDiscoveryListener; import net.floodlightcontroller.linkdiscovery.ILinkDiscoveryService; import net.floodlightcontroller.packet.BSN; import net.floodlightcontroller.packet.Ethernet; import net.floodlightcontroller.packet.LLDP; import net.floodlightcontroller.restserver.IRestApiService; import net.floodlightcontroller.routing.IRoutingService; import net.floodlightcontroller.routing.Link; import net.floodlightcontroller.routing.Route; import net.floodlightcontroller.threadpool.IThreadPoolService; import net.floodlightcontroller.topology.web.TopologyWebRoutable; import org.openflow.protocol.OFMessage; import org.openflow.protocol.OFPacketIn; import org.openflow.protocol.OFPacketOut; import org.openflow.protocol.OFPort; import org.openflow.protocol.OFType; import org.openflow.protocol.action.OFAction; import org.openflow.protocol.action.OFActionOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Topology manager is responsible for maintaining the controller's notion * of the network graph, as well as implementing tools for finding routes * through the topology. */ @LogMessageCategory("Network Topology") public class TopologyManager implements IFloodlightModule, ITopologyService, IRoutingService, ILinkDiscoveryListener, IOFMessageListener { protected static Logger log = LoggerFactory.getLogger(TopologyManager.class); public static final String MODULE_NAME = "topology"; public static final String CONTEXT_TUNNEL_ENABLED = "com.bigswitch.floodlight.topologymanager.tunnelEnabled"; /** * Role of the controller. */ private Role role; /** * Set of ports for each switch */ protected Map<Long, Set<Short>> switchPorts; /** * Set of links organized by node port tuple */ protected Map<NodePortTuple, Set<Link>> switchPortLinks; /** * Set of direct links */ protected Map<NodePortTuple, Set<Link>> directLinks; /** * set of links that are broadcast domain links. */ protected Map<NodePortTuple, Set<Link>> portBroadcastDomainLinks; /** * set of tunnel links */ protected Set<NodePortTuple> tunnelPorts; protected ILinkDiscoveryService linkDiscovery; protected IThreadPoolService threadPool; protected IFloodlightProviderService floodlightProvider; protected IRestApiService restApi; protected IDebugCounterService debugCounters; // Modules that listen to our updates protected ArrayList<ITopologyListener> topologyAware; protected BlockingQueue<LDUpdate> ldUpdates; // These must be accessed using getCurrentInstance(), not directly protected TopologyInstance currentInstance; protected TopologyInstance currentInstanceWithoutTunnels; protected SingletonTask newInstanceTask; private Date lastUpdateTime; /** * Flag that indicates if links (direct/tunnel/multihop links) were * updated as part of LDUpdate. */ protected boolean linksUpdated; /** * Flag that indicates if direct or tunnel links were updated as * part of LDUpdate. */ protected boolean dtLinksUpdated; /** Flag that indicates if tunnel ports were updated or not */ protected boolean tunnelPortsUpdated; protected int TOPOLOGY_COMPUTE_INTERVAL_MS = 500; private IHAListener haListener; /** * Debug Counters */ protected static final String PACKAGE = TopologyManager.class.getPackage().getName(); protected IDebugCounter ctrIncoming; /** * Debug Events */ protected IDebugEventService debugEvents; /* * Topology Event Updater */ protected IEventUpdater<TopologyEvent> evTopology; /** * Topology Information exposed for a Topology related event - used inside * the BigTopologyEvent class */ protected class TopologyEventInfo { private final int numOpenflowClusters; private final int numExternalClusters; private final int numExternalPorts; private final int numTunnelPorts; public TopologyEventInfo(int numOpenflowClusters, int numExternalClusters, int numExternalPorts, int numTunnelPorts) { super(); this.numOpenflowClusters = numOpenflowClusters; this.numExternalClusters = numExternalClusters; this.numExternalPorts = numExternalPorts; this.numTunnelPorts = numTunnelPorts; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("# Openflow Clusters: "); builder.append(numOpenflowClusters); builder.append(", # External Clusters: "); builder.append(numExternalClusters); builder.append(", # External Ports: "); builder.append(numExternalPorts); builder.append(", # Tunnel Ports: "); builder.append(numTunnelPorts); return builder.toString(); } } /** * Topology Event class to track topology related events */ protected class TopologyEvent { @EventColumn(name = "Reason", description = EventFieldType.STRING) private final String reason; @EventColumn(name = "Topology Summary") private final TopologyEventInfo topologyInfo; public TopologyEvent(String reason, TopologyEventInfo topologyInfo) { super(); this.reason = reason; this.topologyInfo = topologyInfo; } } // Getter/Setter methods /** * Get the time interval for the period topology updates, if any. * The time returned is in milliseconds. * @return */ public int getTopologyComputeInterval() { return TOPOLOGY_COMPUTE_INTERVAL_MS; } /** * Set the time interval for the period topology updates, if any. * The time is in milliseconds. * @return */ public void setTopologyComputeInterval(int time_ms) { TOPOLOGY_COMPUTE_INTERVAL_MS = time_ms; } /** * Thread for recomputing topology. The thread is always running, * however the function applyUpdates() has a blocking call. */ @LogMessageDoc(level="ERROR", message="Error in topology instance task thread", explanation="An unknown error occured in the topology " + "discovery module.", recommendation=LogMessageDoc.CHECK_CONTROLLER) protected class UpdateTopologyWorker implements Runnable { @Override public void run() { try { if (ldUpdates.peek() != null) updateTopology(); handleMiscellaneousPeriodicEvents(); } catch (Exception e) { log.error("Error in topology instance task thread", e); } finally { if (floodlightProvider.getRole() != Role.SLAVE) newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS, TimeUnit.MILLISECONDS); } } } // To be used for adding any periodic events that's required by topology. protected void handleMiscellaneousPeriodicEvents() { return; } public boolean updateTopology() { boolean newInstanceFlag; linksUpdated = false; dtLinksUpdated = false; tunnelPortsUpdated = false; List<LDUpdate> appliedUpdates = applyUpdates(); newInstanceFlag = createNewInstance("link-discovery-updates"); lastUpdateTime = new Date(); informListeners(appliedUpdates); return newInstanceFlag; } // ********************** // ILinkDiscoveryListener // ********************** @Override public void linkDiscoveryUpdate(List<LDUpdate> updateList) { if (log.isTraceEnabled()) { log.trace("Queuing update: {}", updateList); } ldUpdates.addAll(updateList); } @Override public void linkDiscoveryUpdate(LDUpdate update) { if (log.isTraceEnabled()) { log.trace("Queuing update: {}", update); } ldUpdates.add(update); } // **************** // ITopologyService // **************** // // ITopologyService interface methods // @Override public Date getLastUpdateTime() { return lastUpdateTime; } @Override public void addListener(ITopologyListener listener) { topologyAware.add(listener); } @Override public boolean isAttachmentPointPort(long switchid, short port) { return isAttachmentPointPort(switchid, port, true); } @Override public boolean isAttachmentPointPort(long switchid, short port, boolean tunnelEnabled) { // If the switch port is 'tun-bsn' port, it is not // an attachment point port, irrespective of whether // a link is found through it or not. if (linkDiscovery.isTunnelPort(switchid, port)) return false; TopologyInstance ti = getCurrentInstance(tunnelEnabled); // if the port is not attachment point port according to // topology instance, then return false if (ti.isAttachmentPointPort(switchid, port) == false) return false; // Check whether the port is a physical port. We should not learn // attachment points on "special" ports. if ((port & 0xff00) == 0xff00 && port != (short)0xfffe) return false; // Make sure that the port is enabled. IOFSwitch sw = floodlightProvider.getSwitch(switchid); if (sw == null) return false; return (sw.portEnabled(port)); } @Override public long getOpenflowDomainId(long switchId) { return getOpenflowDomainId(switchId, true); } @Override public long getOpenflowDomainId(long switchId, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getOpenflowDomainId(switchId); } @Override public long getL2DomainId(long switchId) { return getL2DomainId(switchId, true); } @Override public long getL2DomainId(long switchId, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getL2DomainId(switchId); } @Override public boolean inSameOpenflowDomain(long switch1, long switch2) { return inSameOpenflowDomain(switch1, switch2, true); } @Override public boolean inSameOpenflowDomain(long switch1, long switch2, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.inSameOpenflowDomain(switch1, switch2); } @Override public boolean isAllowed(long sw, short portId) { return isAllowed(sw, portId, true); } @Override public boolean isAllowed(long sw, short portId, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.isAllowed(sw, portId); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// @Override public boolean isIncomingBroadcastAllowed(long sw, short portId) { return isIncomingBroadcastAllowed(sw, portId, true); } @Override public boolean isIncomingBroadcastAllowed(long sw, short portId, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.isIncomingBroadcastAllowedOnSwitchPort(sw, portId); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /** Get all the ports connected to the switch */ @Override public Set<Short> getPortsWithLinks(long sw) { return getPortsWithLinks(sw, true); } /** Get all the ports connected to the switch */ @Override public Set<Short> getPortsWithLinks(long sw, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getPortsWithLinks(sw); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /** Get all the ports on the target switch (targetSw) on which a * broadcast packet must be sent from a host whose attachment point * is on switch port (src, srcPort). */ @Override public Set<Short> getBroadcastPorts(long targetSw, long src, short srcPort) { return getBroadcastPorts(targetSw, src, srcPort, true); } /** Get all the ports on the target switch (targetSw) on which a * broadcast packet must be sent from a host whose attachment point * is on switch port (src, srcPort). */ @Override public Set<Short> getBroadcastPorts(long targetSw, long src, short srcPort, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getBroadcastPorts(targetSw, src, srcPort); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// @Override public NodePortTuple getOutgoingSwitchPort(long src, short srcPort, long dst, short dstPort) { // Use this function to redirect traffic if needed. return getOutgoingSwitchPort(src, srcPort, dst, dstPort, true); } @Override public NodePortTuple getOutgoingSwitchPort(long src, short srcPort, long dst, short dstPort, boolean tunnelEnabled) { // Use this function to redirect traffic if needed. TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getOutgoingSwitchPort(src, srcPort, dst, dstPort); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// @Override public NodePortTuple getIncomingSwitchPort(long src, short srcPort, long dst, short dstPort) { return getIncomingSwitchPort(src, srcPort, dst, dstPort, true); } @Override public NodePortTuple getIncomingSwitchPort(long src, short srcPort, long dst, short dstPort, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getIncomingSwitchPort(src, srcPort, dst, dstPort); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /** * Checks if the two switchports belong to the same broadcast domain. */ @Override public boolean isInSameBroadcastDomain(long s1, short p1, long s2, short p2) { return isInSameBroadcastDomain(s1, p1, s2, p2, true); } @Override public boolean isInSameBroadcastDomain(long s1, short p1, long s2, short p2, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.inSameBroadcastDomain(s1, p1, s2, p2); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /** * Checks if the switchport is a broadcast domain port or not. */ @Override public boolean isBroadcastDomainPort(long sw, short port) { return isBroadcastDomainPort(sw, port, true); } @Override public boolean isBroadcastDomainPort(long sw, short port, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.isBroadcastDomainPort(new NodePortTuple(sw, port)); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /** * Checks if the new attachment point port is consistent with the * old attachment point port. */ @Override public boolean isConsistent(long oldSw, short oldPort, long newSw, short newPort) { return isConsistent(oldSw, oldPort, newSw, newPort, true); } @Override public boolean isConsistent(long oldSw, short oldPort, long newSw, short newPort, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.isConsistent(oldSw, oldPort, newSw, newPort); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /** * Checks if the two switches are in the same Layer 2 domain. */ @Override public boolean inSameL2Domain(long switch1, long switch2) { return inSameL2Domain(switch1, switch2, true); } @Override public boolean inSameL2Domain(long switch1, long switch2, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.inSameL2Domain(switch1, switch2); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// @Override public NodePortTuple getAllowedOutgoingBroadcastPort(long src, short srcPort, long dst, short dstPort) { return getAllowedOutgoingBroadcastPort(src, srcPort, dst, dstPort, true); } @Override public NodePortTuple getAllowedOutgoingBroadcastPort(long src, short srcPort, long dst, short dstPort, boolean tunnelEnabled){ TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getAllowedOutgoingBroadcastPort(src, srcPort, dst, dstPort); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// @Override public NodePortTuple getAllowedIncomingBroadcastPort(long src, short srcPort) { return getAllowedIncomingBroadcastPort(src,srcPort, true); } @Override public NodePortTuple getAllowedIncomingBroadcastPort(long src, short srcPort, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getAllowedIncomingBroadcastPort(src,srcPort); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// @Override public Set<Long> getSwitchesInOpenflowDomain(long switchDPID) { return getSwitchesInOpenflowDomain(switchDPID, true); } @Override public Set<Long> getSwitchesInOpenflowDomain(long switchDPID, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getSwitchesInOpenflowDomain(switchDPID); } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// @Override public Set<NodePortTuple> getBroadcastDomainPorts() { return portBroadcastDomainLinks.keySet(); } @Override public Set<NodePortTuple> getTunnelPorts() { return tunnelPorts; } @Override public Set<NodePortTuple> getBlockedPorts() { Set<NodePortTuple> bp; Set<NodePortTuple> blockedPorts = new HashSet<NodePortTuple>(); // As we might have two topologies, simply get the union of // both of them and send it. bp = getCurrentInstance(true).getBlockedPorts(); if (bp != null) blockedPorts.addAll(bp); bp = getCurrentInstance(false).getBlockedPorts(); if (bp != null) blockedPorts.addAll(bp); return blockedPorts; } //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // *************** // IRoutingService // *************** @Override public Route getRoute(long src, long dst, long cookie) { return getRoute(src, dst, cookie, true); } @Override public Route getRoute(long src, long dst, long cookie, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getRoute(src, dst, cookie); } @Override public Route getRoute(long src, short srcPort, long dst, short dstPort, long cookie) { return getRoute(src, srcPort, dst, dstPort, cookie, true); } @Override public Route getRoute(long src, short srcPort, long dst, short dstPort, long cookie, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.getRoute(null, src, srcPort, dst, dstPort, cookie); } @Override public boolean routeExists(long src, long dst) { return routeExists(src, dst, true); } @Override public boolean routeExists(long src, long dst, boolean tunnelEnabled) { TopologyInstance ti = getCurrentInstance(tunnelEnabled); return ti.routeExists(src, dst); } @Override public ArrayList<Route> getRoutes(long srcDpid, long dstDpid, boolean tunnelEnabled) { // Floodlight supports single path routing now // return single path now ArrayList<Route> result=new ArrayList<Route>(); result.add(getRoute(srcDpid, dstDpid, 0, tunnelEnabled)); return result; } // ****************** // IOFMessageListener // ****************** @Override public String getName() { return MODULE_NAME; } @Override public boolean isCallbackOrderingPrereq(OFType type, String name) { return "linkdiscovery".equals(name); } @Override public boolean isCallbackOrderingPostreq(OFType type, String name) { return false; } @Override public Command receive(IOFSwitch sw, OFMessage msg, FloodlightContext cntx) { switch (msg.getType()) { case PACKET_IN: ctrIncoming.updateCounterNoFlush(); return this.processPacketInMessage(sw, (OFPacketIn) msg, cntx); default: break; } return Command.CONTINUE; } // *************** // IHAListener // *************** private class HAListenerDelegate implements IHAListener { @Override public void transitionToMaster() { role = Role.MASTER; log.debug("Re-computing topology due " + "to HA change from SLAVE->MASTER"); newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS, TimeUnit.MILLISECONDS); } @Override public void controllerNodeIPsChanged( Map<String, String> curControllerNodeIPs, Map<String, String> addedControllerNodeIPs, Map<String, String> removedControllerNodeIPs) { // no-op } @Override public String getName() { return TopologyManager.this.getName(); } @Override public boolean isCallbackOrderingPrereq(HAListenerTypeMarker type, String name) { return "linkdiscovery".equals(name) || "tunnelmanager".equals(name); } @Override public boolean isCallbackOrderingPostreq(HAListenerTypeMarker type, String name) { // TODO Auto-generated method stub return false; } } // ***************** // IFloodlightModule // ***************** @Override public Collection<Class<? extends IFloodlightService>> getModuleServices() { Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(ITopologyService.class); l.add(IRoutingService.class); return l; } @Override public Map<Class<? extends IFloodlightService>, IFloodlightService> getServiceImpls() { Map<Class<? extends IFloodlightService>, IFloodlightService> m = new HashMap<Class<? extends IFloodlightService>, IFloodlightService>(); // We are the class that implements the service m.put(ITopologyService.class, this); m.put(IRoutingService.class, this); return m; } @Override public Collection<Class<? extends IFloodlightService>> getModuleDependencies() { Collection<Class<? extends IFloodlightService>> l = new ArrayList<Class<? extends IFloodlightService>>(); l.add(ILinkDiscoveryService.class); l.add(IThreadPoolService.class); l.add(IFloodlightProviderService.class); l.add(ICounterStoreService.class); l.add(IRestApiService.class); return l; } @Override public void init(FloodlightModuleContext context) throws FloodlightModuleException { linkDiscovery = context.getServiceImpl(ILinkDiscoveryService.class); threadPool = context.getServiceImpl(IThreadPoolService.class); floodlightProvider = context.getServiceImpl(IFloodlightProviderService.class); restApi = context.getServiceImpl(IRestApiService.class); debugCounters = context.getServiceImpl(IDebugCounterService.class); debugEvents = context.getServiceImpl(IDebugEventService.class); switchPorts = new HashMap<Long,Set<Short>>(); switchPortLinks = new HashMap<NodePortTuple, Set<Link>>(); directLinks = new HashMap<NodePortTuple, Set<Link>>(); portBroadcastDomainLinks = new HashMap<NodePortTuple, Set<Link>>(); tunnelPorts = new HashSet<NodePortTuple>(); topologyAware = new ArrayList<ITopologyListener>(); ldUpdates = new LinkedBlockingQueue<LDUpdate>(); haListener = new HAListenerDelegate(); registerTopologyDebugCounters(); registerTopologyDebugEvents(); } protected void registerTopologyDebugEvents() throws FloodlightModuleException { if (debugEvents == null) { debugEvents = new NullDebugEvent(); } try { evTopology = debugEvents.registerEvent(PACKAGE, "topologyevent", "Topology Computation", EventType.ALWAYS_LOG, TopologyEvent.class, 100); } catch (MaxEventsRegistered e) { throw new FloodlightModuleException("Max events registered", e); } } @Override public void startUp(FloodlightModuleContext context) { clearCurrentTopology(); // Initialize role to floodlight provider role. this.role = floodlightProvider.getRole(); ScheduledExecutorService ses = threadPool.getScheduledExecutor(); newInstanceTask = new SingletonTask(ses, new UpdateTopologyWorker()); if (role != Role.SLAVE) newInstanceTask.reschedule(TOPOLOGY_COMPUTE_INTERVAL_MS, TimeUnit.MILLISECONDS); linkDiscovery.addListener(this); floodlightProvider.addOFMessageListener(OFType.PACKET_IN, this); floodlightProvider.addHAListener(this.haListener); addRestletRoutable(); } private void registerTopologyDebugCounters() throws FloodlightModuleException { if (debugCounters == null) { log.error("Debug Counter Service not found."); debugCounters = new NullDebugCounter(); } try { ctrIncoming = debugCounters.registerCounter(PACKAGE, "incoming", "All incoming packets seen by this module", CounterType.ALWAYS_COUNT); } catch (CounterException e) { throw new FloodlightModuleException(e.getMessage()); } } protected void addRestletRoutable() { restApi.addRestletRoutable(new TopologyWebRoutable()); } // **************** // Internal methods // **************** /** * If the packet-in switch port is disabled for all data traffic, then * the packet will be dropped. Otherwise, the packet will follow the * normal processing chain. * @param sw * @param pi * @param cntx * @return */ protected Command dropFilter(long sw, OFPacketIn pi, FloodlightContext cntx) { Command result = Command.CONTINUE; short port = pi.getInPort(); // If the input port is not allowed for data traffic, drop everything. // BDDP packets will not reach this stage. if (isAllowed(sw, port) == false) { if (log.isTraceEnabled()) { log.trace("Ignoring packet because of topology " + "restriction on switch={}, port={}", sw, port); result = Command.STOP; } } return result; } /** * TODO This method must be moved to a layer below forwarding * so that anyone can use it. * @param packetData * @param sw * @param ports * @param cntx */ @LogMessageDoc(level="ERROR", message="Failed to clear all flows on switch {switch}", explanation="An I/O error occured while trying send " + "topology discovery packet", recommendation=LogMessageDoc.CHECK_SWITCH) public void doMultiActionPacketOut(byte[] packetData, IOFSwitch sw, Set<Short> ports, FloodlightContext cntx) { if (ports == null) return; if (packetData == null || packetData.length <= 0) return; OFPacketOut po = (OFPacketOut) floodlightProvider.getOFMessageFactory(). getMessage(OFType.PACKET_OUT); List<OFAction> actions = new ArrayList<OFAction>(); for(short p: ports) { actions.add(new OFActionOutput(p, (short) 0)); } // set actions po.setActions(actions); // set action length po.setActionsLength((short) (OFActionOutput.MINIMUM_LENGTH * ports.size())); // set buffer-id to BUFFER_ID_NONE po.setBufferId(OFPacketOut.BUFFER_ID_NONE); // set in-port to OFPP_NONE po.setInPort(OFPort.OFPP_NONE.getValue()); // set packet data po.setPacketData(packetData); // compute and set packet length. short poLength = (short)(OFPacketOut.MINIMUM_LENGTH + po.getActionsLength() + packetData.length); po.setLength(poLength); try { //counterStore.updatePktOutFMCounterStore(sw, po); if (log.isTraceEnabled()) { log.trace("write broadcast packet on switch-id={} " + "interaces={} packet-data={} packet-out={}", new Object[] {sw.getId(), ports, packetData, po}); } sw.write(po, cntx); } catch (IOException e) { log.error("Failure writing packet out", e); } } /** * Get the set of ports to eliminate for sending out BDDP. The method * returns all the ports that are suppressed for link discovery on the * switch. * packets. * @param sid * @return */ protected Set<Short> getPortsToEliminateForBDDP(long sid) { Set<NodePortTuple> suppressedNptList = linkDiscovery.getSuppressLLDPsInfo(); if (suppressedNptList == null) return null; Set<Short> resultPorts = new HashSet<Short>(); for(NodePortTuple npt: suppressedNptList) { if (npt.getNodeId() == sid) { resultPorts.add(npt.getPortId()); } } return resultPorts; } /** * The BDDP packets are forwarded out of all the ports out of an * openflowdomain. Get all the switches in the same openflow * domain as the sw (disabling tunnels). Then get all the * external switch ports and send these packets out. * @param sw * @param pi * @param cntx */ protected void doFloodBDDP(long pinSwitch, OFPacketIn pi, FloodlightContext cntx) { TopologyInstance ti = getCurrentInstance(false); Set<Long> switches = ti.getSwitchesInOpenflowDomain(pinSwitch); if (switches == null) { // indicates no links are connected to the switches switches = new HashSet<Long>(); switches.add(pinSwitch); } for(long sid: switches) { IOFSwitch sw = floodlightProvider.getSwitch(sid); if (sw == null) continue; Collection<Short> enabledPorts = sw.getEnabledPortNumbers(); if (enabledPorts == null) continue; Set<Short> ports = new HashSet<Short>(); ports.addAll(enabledPorts); // all the ports known to topology // without tunnels. // out of these, we need to choose only those that are // broadcast port, otherwise, we should eliminate. Set<Short> portsKnownToTopo = ti.getPortsWithLinks(sid); if (portsKnownToTopo != null) { for(short p: portsKnownToTopo) { NodePortTuple npt = new NodePortTuple(sid, p); if (ti.isBroadcastDomainPort(npt) == false) { ports.remove(p); } } } Set<Short> portsToEliminate = getPortsToEliminateForBDDP(sid); if (portsToEliminate != null) { ports.removeAll(portsToEliminate); } // remove the incoming switch port if (pinSwitch == sid) { ports.remove(pi.getInPort()); } // we have all the switch ports to which we need to broadcast. doMultiActionPacketOut(pi.getPacketData(), sw, ports, cntx); } } protected Command processPacketInMessage(IOFSwitch sw, OFPacketIn pi, FloodlightContext cntx) { // get the packet-in switch. Ethernet eth = IFloodlightProviderService.bcStore. get(cntx,IFloodlightProviderService.CONTEXT_PI_PAYLOAD); if (eth.getPayload() instanceof BSN) { BSN bsn = (BSN) eth.getPayload(); if (bsn == null) return Command.STOP; if (bsn.getPayload() == null) return Command.STOP; // It could be a packet other than BSN LLDP, therefore // continue with the regular processing. if (bsn.getPayload() instanceof LLDP == false) return Command.CONTINUE; doFloodBDDP(sw.getId(), pi, cntx); return Command.STOP; } else { return dropFilter(sw.getId(), pi, cntx); } } /** * Updates concerning switch disconnect and port down are not processed. * LinkDiscoveryManager is expected to process those messages and send * multiple link removed messages. However, all the updates from * LinkDiscoveryManager would be propagated to the listeners of topology. */ @LogMessageDoc(level="ERROR", message="Error reading link discovery update.", explanation="Unable to process link discovery update", recommendation=LogMessageDoc.REPORT_CONTROLLER_BUG) public List<LDUpdate> applyUpdates() { List<LDUpdate> appliedUpdates = new ArrayList<LDUpdate>(); LDUpdate update = null; while (ldUpdates.peek() != null) { try { update = ldUpdates.take(); } catch (Exception e) { log.error("Error reading link discovery update.", e); } if (log.isTraceEnabled()) { log.trace("Applying update: {}", update); } switch (update.getOperation()) { case LINK_UPDATED: addOrUpdateLink(update.getSrc(), update.getSrcPort(), update.getDst(), update.getDstPort(), update.getType()); break; case LINK_REMOVED: removeLink(update.getSrc(), update.getSrcPort(), update.getDst(), update.getDstPort()); break; case SWITCH_UPDATED: addOrUpdateSwitch(update.getSrc()); break; case SWITCH_REMOVED: removeSwitch(update.getSrc()); break; case TUNNEL_PORT_ADDED: addTunnelPort(update.getSrc(), update.getSrcPort()); break; case TUNNEL_PORT_REMOVED: removeTunnelPort(update.getSrc(), update.getSrcPort()); break; case PORT_UP: case PORT_DOWN: break; } // Add to the list of applied updates. appliedUpdates.add(update); } return (Collections.unmodifiableList(appliedUpdates)); } protected void addOrUpdateSwitch(long sw) { // nothing to do here for the time being. return; } public void addTunnelPort(long sw, short port) { NodePortTuple npt = new NodePortTuple(sw, port); tunnelPorts.add(npt); tunnelPortsUpdated = true; } public void removeTunnelPort(long sw, short port) { NodePortTuple npt = new NodePortTuple(sw, port); tunnelPorts.remove(npt); tunnelPortsUpdated = true; } public boolean createNewInstance() { return createNewInstance("internal"); } /** * This function computes a new topology instance. * It ignores links connected to all broadcast domain ports * and tunnel ports. The method returns if a new instance of * topology was created or not. */ protected boolean createNewInstance(String reason) { Set<NodePortTuple> blockedPorts = new HashSet<NodePortTuple>(); if (!linksUpdated) return false; Map<NodePortTuple, Set<Link>> openflowLinks; openflowLinks = new HashMap<NodePortTuple, Set<Link>>(); Set<NodePortTuple> nptList = switchPortLinks.keySet(); if (nptList != null) { for(NodePortTuple npt: nptList) { Set<Link> linkSet = switchPortLinks.get(npt); if (linkSet == null) continue; openflowLinks.put(npt, new HashSet<Link>(linkSet)); } } // Identify all broadcast domain ports. // Mark any port that has inconsistent set of links // as broadcast domain ports as well. Set<NodePortTuple> broadcastDomainPorts = identifyBroadcastDomainPorts(); // Remove all links incident on broadcast domain ports. for(NodePortTuple npt: broadcastDomainPorts) { if (switchPortLinks.get(npt) == null) continue; for(Link link: switchPortLinks.get(npt)) { removeLinkFromStructure(openflowLinks, link); } } // Remove all tunnel links. for(NodePortTuple npt: tunnelPorts) { if (switchPortLinks.get(npt) == null) continue; for(Link link: switchPortLinks.get(npt)) { removeLinkFromStructure(openflowLinks, link); } } TopologyInstance nt = new TopologyInstance(switchPorts, blockedPorts, openflowLinks, broadcastDomainPorts, tunnelPorts); nt.compute(); // We set the instances with and without tunnels to be identical. // If needed, we may compute them differently. currentInstance = nt; currentInstanceWithoutTunnels = nt; TopologyEventInfo topologyInfo = new TopologyEventInfo(nt.getClusters().size(), 0, 0, 0); - evTopology.updateEventWithFlush(new TopologyEvent(reason, - topologyInfo)); + evTopology.updateEventWithFlush(new TopologyEvent(reason, + topologyInfo)); return true; } /** * We expect every switch port to have at most two links. Both these * links must be unidirectional links connecting to the same switch port. * If not, we will mark this as a broadcast domain port. */ protected Set<NodePortTuple> identifyBroadcastDomainPorts() { Set<NodePortTuple> broadcastDomainPorts = new HashSet<NodePortTuple>(); broadcastDomainPorts.addAll(this.portBroadcastDomainLinks.keySet()); Set<NodePortTuple> additionalNpt = new HashSet<NodePortTuple>(); // Copy switchPortLinks Map<NodePortTuple, Set<Link>> spLinks = new HashMap<NodePortTuple, Set<Link>>(); for(NodePortTuple npt: switchPortLinks.keySet()) { spLinks.put(npt, new HashSet<Link>(switchPortLinks.get(npt))); } for(NodePortTuple npt: spLinks.keySet()) { Set<Link> links = spLinks.get(npt); boolean bdPort = false; ArrayList<Link> linkArray = new ArrayList<Link>(); if (links.size() > 2) { bdPort = true; } else if (links.size() == 2) { for(Link l: links) { linkArray.add(l); } // now, there should be two links in [0] and [1]. Link l1 = linkArray.get(0); Link l2 = linkArray.get(1); // check if these two are symmetric. if (l1.getSrc() != l2.getDst() || l1.getSrcPort() != l2.getDstPort() || l1.getDst() != l2.getSrc() || l1.getDstPort() != l2.getSrcPort()) { bdPort = true; } } if (bdPort && (broadcastDomainPorts.contains(npt) == false)) { additionalNpt.add(npt); } } if (additionalNpt.size() > 0) { log.warn("The following switch ports have multiple " + "links incident on them, so these ports will be treated " + " as braodcast domain ports. {}", additionalNpt); broadcastDomainPorts.addAll(additionalNpt); } return broadcastDomainPorts; } public void informListeners(List<LDUpdate> linkUpdates) { if (role != null && role != Role.MASTER) return; for(int i=0; i<topologyAware.size(); ++i) { ITopologyListener listener = topologyAware.get(i); listener.topologyChanged(linkUpdates); } } public void addSwitch(long sid) { if (switchPorts.containsKey(sid) == false) { switchPorts.put(sid, new HashSet<Short>()); } } private void addPortToSwitch(long s, short p) { addSwitch(s); switchPorts.get(s).add(p); } public void removeSwitch(long sid) { // Delete all the links in the switch, switch and all // associated data should be deleted. if (switchPorts.containsKey(sid) == false) return; // Check if any tunnel ports need to be removed. for(NodePortTuple npt: tunnelPorts) { if (npt.getNodeId() == sid) { removeTunnelPort(npt.getNodeId(), npt.getPortId()); } } Set<Link> linksToRemove = new HashSet<Link>(); for(Short p: switchPorts.get(sid)) { NodePortTuple n1 = new NodePortTuple(sid, p); linksToRemove.addAll(switchPortLinks.get(n1)); } if (linksToRemove.isEmpty()) return; for(Link link: linksToRemove) { removeLink(link); } } /** * Add the given link to the data structure. Returns true if a link was * added. * @param s * @param l * @return */ private boolean addLinkToStructure(Map<NodePortTuple, Set<Link>> s, Link l) { boolean result1 = false, result2 = false; NodePortTuple n1 = new NodePortTuple(l.getSrc(), l.getSrcPort()); NodePortTuple n2 = new NodePortTuple(l.getDst(), l.getDstPort()); if (s.get(n1) == null) { s.put(n1, new HashSet<Link>()); } if (s.get(n2) == null) { s.put(n2, new HashSet<Link>()); } result1 = s.get(n1).add(l); result2 = s.get(n2).add(l); return (result1 || result2); } /** * Delete the given link from the data strucure. Returns true if the * link was deleted. * @param s * @param l * @return */ private boolean removeLinkFromStructure(Map<NodePortTuple, Set<Link>> s, Link l) { boolean result1 = false, result2 = false; NodePortTuple n1 = new NodePortTuple(l.getSrc(), l.getSrcPort()); NodePortTuple n2 = new NodePortTuple(l.getDst(), l.getDstPort()); if (s.get(n1) != null) { result1 = s.get(n1).remove(l); if (s.get(n1).isEmpty()) s.remove(n1); } if (s.get(n2) != null) { result2 = s.get(n2).remove(l); if (s.get(n2).isEmpty()) s.remove(n2); } return result1 || result2; } protected void addOrUpdateTunnelLink(long srcId, short srcPort, long dstId, short dstPort) { // If you need to handle tunnel links, this is a placeholder. } public void addOrUpdateLink(long srcId, short srcPort, long dstId, short dstPort, LinkType type) { Link link = new Link(srcId, srcPort, dstId, dstPort); if (type.equals(LinkType.MULTIHOP_LINK)) { addPortToSwitch(srcId, srcPort); addPortToSwitch(dstId, dstPort); addLinkToStructure(switchPortLinks, link); addLinkToStructure(portBroadcastDomainLinks, link); dtLinksUpdated = removeLinkFromStructure(directLinks, link); linksUpdated = true; } else if (type.equals(LinkType.DIRECT_LINK)) { addPortToSwitch(srcId, srcPort); addPortToSwitch(dstId, dstPort); addLinkToStructure(switchPortLinks, link); addLinkToStructure(directLinks, link); removeLinkFromStructure(portBroadcastDomainLinks, link); dtLinksUpdated = true; linksUpdated = true; } else if (type.equals(LinkType.TUNNEL)) { addOrUpdateTunnelLink(srcId, srcPort, dstId, dstPort); } } public void removeLink(Link link) { linksUpdated = true; dtLinksUpdated = removeLinkFromStructure(directLinks, link); removeLinkFromStructure(portBroadcastDomainLinks, link); removeLinkFromStructure(switchPortLinks, link); NodePortTuple srcNpt = new NodePortTuple(link.getSrc(), link.getSrcPort()); NodePortTuple dstNpt = new NodePortTuple(link.getDst(), link.getDstPort()); // Remove switch ports if there are no links through those switch ports if (switchPortLinks.get(srcNpt) == null) { if (switchPorts.get(srcNpt.getNodeId()) != null) switchPorts.get(srcNpt.getNodeId()).remove(srcNpt.getPortId()); } if (switchPortLinks.get(dstNpt) == null) { if (switchPorts.get(dstNpt.getNodeId()) != null) switchPorts.get(dstNpt.getNodeId()).remove(dstNpt.getPortId()); } // Remove the node if no ports are present if (switchPorts.get(srcNpt.getNodeId())!=null && switchPorts.get(srcNpt.getNodeId()).isEmpty()) { switchPorts.remove(srcNpt.getNodeId()); } if (switchPorts.get(dstNpt.getNodeId())!=null && switchPorts.get(dstNpt.getNodeId()).isEmpty()) { switchPorts.remove(dstNpt.getNodeId()); } } public void removeLink(long srcId, short srcPort, long dstId, short dstPort) { Link link = new Link(srcId, srcPort, dstId, dstPort); removeLink(link); } public void clear() { switchPorts.clear(); tunnelPorts.clear(); switchPortLinks.clear(); portBroadcastDomainLinks.clear(); directLinks.clear(); } /** * Clears the current topology. Note that this does NOT * send out updates. */ public void clearCurrentTopology() { this.clear(); linksUpdated = true; dtLinksUpdated = true; tunnelPortsUpdated = true; createNewInstance("startup"); lastUpdateTime = new Date(); } /** * Getters. No Setters. */ public Map<Long, Set<Short>> getSwitchPorts() { return switchPorts; } public Map<NodePortTuple, Set<Link>> getSwitchPortLinks() { return switchPortLinks; } public Map<NodePortTuple, Set<Link>> getPortBroadcastDomainLinks() { return portBroadcastDomainLinks; } public TopologyInstance getCurrentInstance(boolean tunnelEnabled) { if (tunnelEnabled) return currentInstance; else return this.currentInstanceWithoutTunnels; } public TopologyInstance getCurrentInstance() { return this.getCurrentInstance(true); } /** * Switch methods */ @Override public Set<Short> getPorts(long sw) { IOFSwitch iofSwitch = floodlightProvider.getSwitch(sw); if (iofSwitch == null) return Collections.emptySet(); Collection<Short> ofpList = iofSwitch.getEnabledPortNumbers(); if (ofpList == null) return Collections.emptySet(); Set<Short> ports = new HashSet<Short>(ofpList); Set<Short> qPorts = linkDiscovery.getQuarantinedPorts(sw); if (qPorts != null) ports.removeAll(qPorts); return ports; } }
true
true
protected boolean createNewInstance(String reason) { Set<NodePortTuple> blockedPorts = new HashSet<NodePortTuple>(); if (!linksUpdated) return false; Map<NodePortTuple, Set<Link>> openflowLinks; openflowLinks = new HashMap<NodePortTuple, Set<Link>>(); Set<NodePortTuple> nptList = switchPortLinks.keySet(); if (nptList != null) { for(NodePortTuple npt: nptList) { Set<Link> linkSet = switchPortLinks.get(npt); if (linkSet == null) continue; openflowLinks.put(npt, new HashSet<Link>(linkSet)); } } // Identify all broadcast domain ports. // Mark any port that has inconsistent set of links // as broadcast domain ports as well. Set<NodePortTuple> broadcastDomainPorts = identifyBroadcastDomainPorts(); // Remove all links incident on broadcast domain ports. for(NodePortTuple npt: broadcastDomainPorts) { if (switchPortLinks.get(npt) == null) continue; for(Link link: switchPortLinks.get(npt)) { removeLinkFromStructure(openflowLinks, link); } } // Remove all tunnel links. for(NodePortTuple npt: tunnelPorts) { if (switchPortLinks.get(npt) == null) continue; for(Link link: switchPortLinks.get(npt)) { removeLinkFromStructure(openflowLinks, link); } } TopologyInstance nt = new TopologyInstance(switchPorts, blockedPorts, openflowLinks, broadcastDomainPorts, tunnelPorts); nt.compute(); // We set the instances with and without tunnels to be identical. // If needed, we may compute them differently. currentInstance = nt; currentInstanceWithoutTunnels = nt; TopologyEventInfo topologyInfo = new TopologyEventInfo(nt.getClusters().size(), 0, 0, 0); evTopology.updateEventWithFlush(new TopologyEvent(reason, topologyInfo)); return true; }
protected boolean createNewInstance(String reason) { Set<NodePortTuple> blockedPorts = new HashSet<NodePortTuple>(); if (!linksUpdated) return false; Map<NodePortTuple, Set<Link>> openflowLinks; openflowLinks = new HashMap<NodePortTuple, Set<Link>>(); Set<NodePortTuple> nptList = switchPortLinks.keySet(); if (nptList != null) { for(NodePortTuple npt: nptList) { Set<Link> linkSet = switchPortLinks.get(npt); if (linkSet == null) continue; openflowLinks.put(npt, new HashSet<Link>(linkSet)); } } // Identify all broadcast domain ports. // Mark any port that has inconsistent set of links // as broadcast domain ports as well. Set<NodePortTuple> broadcastDomainPorts = identifyBroadcastDomainPorts(); // Remove all links incident on broadcast domain ports. for(NodePortTuple npt: broadcastDomainPorts) { if (switchPortLinks.get(npt) == null) continue; for(Link link: switchPortLinks.get(npt)) { removeLinkFromStructure(openflowLinks, link); } } // Remove all tunnel links. for(NodePortTuple npt: tunnelPorts) { if (switchPortLinks.get(npt) == null) continue; for(Link link: switchPortLinks.get(npt)) { removeLinkFromStructure(openflowLinks, link); } } TopologyInstance nt = new TopologyInstance(switchPorts, blockedPorts, openflowLinks, broadcastDomainPorts, tunnelPorts); nt.compute(); // We set the instances with and without tunnels to be identical. // If needed, we may compute them differently. currentInstance = nt; currentInstanceWithoutTunnels = nt; TopologyEventInfo topologyInfo = new TopologyEventInfo(nt.getClusters().size(), 0, 0, 0); evTopology.updateEventWithFlush(new TopologyEvent(reason, topologyInfo)); return true; }
diff --git a/src/com/fourisland/frigidearth/MapViewGameState.java b/src/com/fourisland/frigidearth/MapViewGameState.java index 07df1d6..bd3471f 100644 --- a/src/com/fourisland/frigidearth/MapViewGameState.java +++ b/src/com/fourisland/frigidearth/MapViewGameState.java @@ -1,1403 +1,1403 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.fourisland.frigidearth; import com.fourisland.frigidearth.mobs.Mouse; import com.fourisland.frigidearth.mobs.Rat; import com.fourisland.frigidearth.mobs.Spider; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * * @author hatkirby */ public class MapViewGameState implements GameState { private final int TILE_WIDTH = 12; private final int TILE_HEIGHT = 12; private final int MESSAGE_HEIGHT = 6; private final int VIEWPORT_WIDTH = Main.CANVAS_WIDTH / TILE_WIDTH; private final int VIEWPORT_HEIGHT = Main.CANVAS_HEIGHT / TILE_HEIGHT - MESSAGE_HEIGHT; private final int MAX_ROOM_WIDTH = 13; private final int MIN_ROOM_WIDTH = 7; private final int MAX_ROOM_HEIGHT = 13; private final int MIN_ROOM_HEIGHT = 7; private final int MAX_CORRIDOR_LENGTH = 6; private final int MIN_CORRIDOR_LENGTH = 2; private final int[][] OCTET_MULTIPLIERS = new int[][] {new int[] {1,0,0,-1,-1,0,0,1}, new int[] {0,1,-1,0,0,-1,1,0}, new int[] {0,1,1,0,0,-1,-1,0}, new int[] {1,0,0,1,-1,0,0,-1}}; private int mapWidth = 60; private int mapHeight = 60; private Tile[][] grid; private boolean[][] gridLighting; private String[] messages = new String[MESSAGE_HEIGHT]; private List<Room> rooms = new ArrayList<Room>(); private List<Mob> mobs = new ArrayList<Mob>(); private List<ItemInstance> items = new ArrayList<ItemInstance>(); private int playerx = 4; private int playery = 4; private int viewportx = 0; private int viewporty = 0; private boolean snowGrow = false; private int heartbeat = 0; private int floor; private int spawnTimer = 0; public MapViewGameState(int floor) { this.floor = floor; mapWidth += (50 * (floor-1)); mapHeight += (50 * (floor-1)); grid = new Tile[mapWidth][mapHeight]; gridLighting = new boolean[mapWidth][mapHeight]; for (int x=0; x<mapWidth; x++) { for (int y=0; y<mapHeight; y++) { if ((x == 0) || (x == mapWidth-1) || (y == 0) || (y == mapHeight-1)) { grid[x][y] = Tile.StoneWall; } else { grid[x][y] = Tile.Unused; } } } Direction keyRoomDirection = Direction.getRandomDirection(); Rectangle legalBounds = null; switch (keyRoomDirection) { case North: legalBounds = new Rectangle(0, 14, mapWidth, mapHeight-14); break; case East: legalBounds = new Rectangle(0, 0, mapWidth-14, mapHeight); break; case South: legalBounds = new Rectangle(0, 0, mapWidth, mapHeight-14); break; case West: legalBounds = new Rectangle(14, 0, mapWidth-14, mapHeight); break; } makeRoom(mapWidth/2, mapHeight/2, Direction.getRandomDirection(), legalBounds); int currentFeatures = 1; int objects = 300; for (int countingTries = 0; countingTries < 1000; countingTries++) { if (currentFeatures == objects) { break; } int newx = 0; int xmod = 0; int newy = 0; int ymod = 0; Direction validTile = null; for (int testing = 0; testing < 1000; testing++) { newx = Functions.random(1, mapWidth-1); newy = Functions.random(1, mapHeight-1); validTile = null; if ((grid[newx][newy] == Tile.DirtWall) || (grid[newx][newy] == Tile.Corridor)) { if ((grid[newx][newy+1] == Tile.DirtFloor) || (grid[newx][newy+1] == Tile.Corridor)) { validTile = Direction.North; xmod = 0; ymod = -1; } else if ((grid[newx-1][newy] == Tile.DirtFloor) || (grid[newx-1][newy] == Tile.Corridor)) { validTile = Direction.East; xmod = 1; ymod = 0; } else if ((grid[newx][newy-1] == Tile.DirtFloor) || (grid[newx][newy-1] == Tile.Corridor)) { validTile = Direction.South; xmod = 0; ymod = 1; } else if ((grid[newx+1][newy] == Tile.DirtFloor) || (grid[newx+1][newy] == Tile.Corridor)) { validTile = Direction.West; xmod = -1; ymod = 0; } if (validTile != null) { if (grid[newx][newy+1] == Tile.Door) { validTile = null; } else if (grid[newx-1][newy] == Tile.Door) { validTile = null; } else if (grid[newx][newy-1] == Tile.Door) { validTile = null; } else if (grid[newx+1][newy] == Tile.Door) { validTile = null; } } if (validTile != null) { break; } } } if (validTile != null) { if (Functions.random(0, 100) <= 75) { if (makeRoom(newx+xmod, newy+ymod, validTile, legalBounds)) { currentFeatures++; grid[newx][newy] = Tile.Door; grid[newx+xmod][newy+ymod] = Tile.DirtFloor; } } else { if (makeCorridor(newx+xmod, newy+ymod, validTile)) { currentFeatures++; grid[newx][newy] = Tile.Door; } } } } int newx = 0; int newy = 0; int ways = 0; int state = 0; while (state != 10) { for (int testing = 0; testing < 1000; testing++) { - newx = Functions.random(1, mapWidth-1); + newx = Functions.random(1, mapWidth-2); newy = Functions.random(1, mapHeight-2); ways = 4; for (Direction dir : Direction.values()) { Point to = dir.to(new Point(newx, newy)); if ((isValidPosition(to.x, to.y)) && (grid[to.x][to.y] == Tile.DirtFloor) || (grid[to.x][to.y] == Tile.Corridor)) { ways--; } } if (state == 0) { if (ways == 0) { grid[newx][newy] = Tile.UpStairs; state = 1; break; } } else if (state == 1) { if (ways == 0) { grid[newx][newy] = Tile.DownStairs; playerx=newx; playery=newy; state = 10; break; } } } } // Create key room Room oRoom = null; for (Room r : rooms) { if (oRoom == null) { oRoom = r; } else if ((keyRoomDirection == Direction.North) && (r.getY() < oRoom.getY())) { oRoom = r; } else if ((keyRoomDirection == Direction.East) && (r.getX() > oRoom.getX())) { oRoom = r; } else if ((keyRoomDirection == Direction.South) && (r.getY() > oRoom.getY())) { oRoom = r; } else if ((keyRoomDirection == Direction.West) && (r.getX() < oRoom.getX())) { oRoom = r; } } Room room = null; switch (keyRoomDirection) { case North: room = new Room(oRoom.getX()+oRoom.getWidth()/2-3, oRoom.getY()-13, 7, 13, false); break; case East: room = new Room(oRoom.getX()+oRoom.getWidth(), oRoom.getY()+oRoom.getHeight()/2-3, 13, 7, false); break; case South: room = new Room(oRoom.getX()+oRoom.getWidth()/2-3, oRoom.getY()+oRoom.getHeight(), 7, 13, false); break; case West: room = new Room(oRoom.getX()-13, oRoom.getY()+oRoom.getHeight()/2-3, 13, 7, false); break; } for (int ytemp=room.getY(); ytemp < room.getY()+room.getHeight(); ytemp++) { for (int xtemp=room.getX(); xtemp < room.getX()+room.getWidth(); xtemp++) { if (xtemp == room.getX()) { if (((keyRoomDirection == Direction.North) || (keyRoomDirection == Direction.South)) && (ytemp % 2 == 0) && (ytemp != room.getY())) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else if (xtemp == room.getX()+room.getWidth()-1) { if (((keyRoomDirection == Direction.North) || (keyRoomDirection == Direction.South)) && (ytemp % 2 == 0) && (ytemp != (room.getY()+room.getHeight()))) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else if (ytemp == room.getY()) { if (((keyRoomDirection == Direction.West) || (keyRoomDirection == Direction.East)) && (xtemp % 2 == 0) && (xtemp != room.getX())) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else if (ytemp == room.getY()+room.getHeight()-1) { if (((keyRoomDirection == Direction.West) || (keyRoomDirection == Direction.East)) && (xtemp % 2 == 0) && (xtemp != (room.getX()+room.getWidth()))) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else { grid[xtemp][ytemp] = Tile.DirtFloor; } } } ItemInstance key = new ItemInstance(); key.item = Item.Key; switch (keyRoomDirection) { case North: grid[room.getX()+room.getWidth()/2][room.getY()+room.getHeight()] = Tile.Door; grid[room.getX()+room.getWidth()/2][room.getY()+room.getHeight()-1] = Tile.DirtFloor; key.x = room.getX()+3; key.y = room.getY()+3; break; case East: grid[room.getX()-1][room.getY()+room.getHeight()/2] = Tile.Door; grid[room.getX()][room.getY()+room.getHeight()/2] = Tile.DirtFloor; key.x = room.getX()+10; key.y = room.getY()+3; break; case South: grid[room.getX()+room.getWidth()/2][room.getY()-1] = Tile.Door; grid[room.getX()+room.getWidth()/2][room.getY()] = Tile.DirtFloor; key.x = room.getX()+3; key.y = room.getY()+10; break; case West: grid[room.getX()+room.getWidth()][room.getY()+room.getHeight()/2] = Tile.Door; grid[room.getX()+room.getWidth()-1][room.getY()+room.getHeight()/2] = Tile.DirtFloor; key.x = room.getX()+3; key.y = room.getY()+3; break; } items.add(key); rooms.add(room); adjustViewport(); calculateFieldOfView(); } private boolean makeRoom(int x, int y, Direction direction, Rectangle legalBounds) { int width = Functions.random(MIN_ROOM_WIDTH, MAX_ROOM_WIDTH); int height = Functions.random(MIN_ROOM_HEIGHT, MAX_ROOM_HEIGHT); Room room = null; Rectangle bounds = null; if (legalBounds == null) { bounds = new Rectangle(0, 0, mapWidth, mapHeight); } else { bounds = legalBounds; } switch (direction) { case North: room = new Room(x-width/2, y-height, width+1, height+1, true); break; case East: room = new Room(x, y-height/2, width+1, height+1, true); break; case South: room = new Room(x-width/2, y, width+1, height+1, true); break; case West: room = new Room(x-width, y-height/2, width+1, height+1, true); break; } for (int ytemp=room.getY(); ytemp < room.getY()+room.getHeight(); ytemp++) { if ((ytemp < bounds.y) || (ytemp > bounds.y+bounds.height )) { return false; } for (int xtemp=room.getX(); xtemp < room.getX()+room.getWidth(); xtemp++) { if ((xtemp < bounds.x) || (xtemp > bounds.x+bounds.width)) { return false; } if (grid[xtemp][ytemp] != Tile.Unused) { return false; } } } for (int ytemp=room.getY(); ytemp < room.getY()+room.getHeight(); ytemp++) { for (int xtemp=room.getX(); xtemp < room.getX()+room.getWidth(); xtemp++) { if (xtemp == room.getX()) { grid[xtemp][ytemp] = Tile.DirtWall; } else if (xtemp == room.getX()+room.getWidth()-1) { grid[xtemp][ytemp] = Tile.DirtWall; } else if (ytemp == room.getY()) { grid[xtemp][ytemp] = Tile.DirtWall; } else if (ytemp == room.getY()+room.getHeight()-1) { grid[xtemp][ytemp] = Tile.DirtWall; } else { grid[xtemp][ytemp] = Tile.DirtFloor; } } } rooms.add(room); // Spawn some random monsters int perf = 60; for (;;) { if (Functions.random(0, 100) < perf) { perf /= 2; mobs.add(createInDepthMonster(room)); } else { break; } } // and some random items perf = 30; for (;;) { if (Functions.random(0, 100) < perf) { perf /= 2; ItemInstance ii = new ItemInstance(); ii.item = Item.getWeightedRandomItem(); ii.x = Functions.random(room.getX()+1, room.getX()+room.getWidth()-2); ii.y = Functions.random(room.getY()+1, room.getY()+room.getHeight()-2); items.add(ii); } else { break; } } return true; } private boolean makeCorridor(int x, int y, Direction direction) { int length = Functions.random(MIN_CORRIDOR_LENGTH, MAX_CORRIDOR_LENGTH); int xtemp = 0; int ytemp = 0; switch (direction) { case North: if ((x < 0) || (x > mapWidth)) { return false; } else { xtemp = x; } for (ytemp = y; ytemp > (y-length); ytemp--) { if ((ytemp < 0) || (ytemp > mapHeight)) { return false; } if (grid[xtemp][ytemp] != Tile.Unused) { return false; } } for (ytemp = y; ytemp > (y-length); ytemp--) { grid[xtemp][ytemp] = Tile.Corridor; } break; case East: if ((y < 0) || (y > mapHeight)) { return false; } else { ytemp = y; } for (xtemp = x; xtemp < (x+length); xtemp++) { if ((xtemp < 0) || (xtemp > mapWidth)) { return false; } if (grid[xtemp][ytemp] != Tile.Unused) { return false; } } for (xtemp = x; xtemp < (x+length); xtemp++) { grid[xtemp][ytemp] = Tile.Corridor; } break; case South: if ((x < 0) || (x > mapWidth)) { return false; } else { xtemp = x; } for (ytemp = y; ytemp < (y+length); ytemp++) { if ((ytemp < 0) || (ytemp > mapHeight)) { return false; } if (grid[xtemp][ytemp] != Tile.Unused) { return false; } } for (ytemp = y; ytemp < (y+length); ytemp++) { grid[xtemp][ytemp] = Tile.Corridor; } break; case West: if ((y < 0) || (y > mapHeight)) { return false; } else { ytemp = y; } for (xtemp = x; xtemp > (x-length); xtemp--) { if ((xtemp < 0) || (xtemp > mapWidth)) { return false; } if (grid[xtemp][ytemp] != Tile.Unused) { return false; } } for (xtemp = x; xtemp > (x-length); xtemp--) { grid[xtemp][ytemp] = Tile.Corridor; } break; } return true; } private void calculateFieldOfView() { for (int x=0; x<mapWidth; x++) { for (int y=0; y<mapHeight; y++) { gridLighting[x][y] = false; } } for (int i=0; i<8; i++) { castLight(playerx, playery, 1, 1.0, 0.0, Math.max(VIEWPORT_WIDTH/2, VIEWPORT_HEIGHT/2), OCTET_MULTIPLIERS[0][i], OCTET_MULTIPLIERS[1][i], OCTET_MULTIPLIERS[2][i], OCTET_MULTIPLIERS[3][i], 0); } } private void castLight(int cx, int cy, int row, double start, double end, int radius, int xx, int xy, int yx, int yy, int id) { if (start < end) { return; } int r2 = radius * radius; for (int j=row; j<radius+1; j++) { int dx = -j-1; int dy = -j; boolean blocked = false; double newStart = 0.0; while (dx <= 0) { dx++; int x = cx + dx*xx + dy*xy; int y = cy + dx*yx + dy*yy; double l_slope = ((double)dx-0.5)/((double)dy+0.5); double r_slope = ((double)dx+0.5)/((double)dy-0.5); if (start < r_slope) { continue; } else if (end > l_slope) { break; } else { if ((dx*dx + dy*dy) < r2) { gridLighting[x][y] = true; } if (blocked) { if (grid[x][y].isBlocked()) { newStart = r_slope; continue; } else { blocked = false; start = newStart; } } else { if ((grid[x][y].isBlocked()) && (j < radius)) { blocked = true; castLight(cx, cy, j+1, start, l_slope, radius, xx, xy, yx, yy, id+1); newStart = r_slope; } } } } if (blocked) { break; } } } public void render(Graphics2D g) { // Render tiles for (int x=viewportx; x<viewportx+VIEWPORT_WIDTH; x++) { for (int y=viewporty; y<viewporty+VIEWPORT_HEIGHT; y++) { if (gridLighting[x][y]) { char displayChar = grid[x][y].getDisplayCharacter(); Color displayColor = grid[x][y].getBackgroundColor(); if (!displayColor.equals(Color.BLACK)) { g.setColor(displayColor); g.fillRect((x-viewportx)*TILE_WIDTH, (y-viewporty)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT); } if (displayChar != ' ') { g.drawImage(SystemFont.getCharacter(grid[x][y].getDisplayCharacter(), Color.WHITE), (x-viewportx)*TILE_WIDTH, (y-viewporty)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT, null); } } } } // Render mobs for (Mob mob : mobs) { if ((gridLighting[mob.x][mob.y]) && (isInViewport(mob.x, mob.y))) { g.drawImage(SystemFont.getCharacter(mob.getDisplayCharacter(), mob.getDisplayColor()), (mob.x-viewportx)*TILE_WIDTH, (mob.y-viewporty)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT, null); } } // Render items for (ItemInstance ii : items) { if (gridLighting[ii.x][ii.y]) { g.drawImage(SystemFont.getCharacter(ii.item.getDisplayCharacter(), ii.item.getDisplayColor()), (ii.x-viewportx)*TILE_WIDTH, (ii.y-viewporty)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT, null); } } // Render player g.drawImage(SystemFont.getCharacter('@', Color.WHITE), (playerx-viewportx)*TILE_WIDTH, (playery-viewporty)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT, null); // Render messages g.setColor(new Color(53, 63, 62)); g.fillRect(0, VIEWPORT_HEIGHT*TILE_HEIGHT, Main.CANVAS_WIDTH, TILE_HEIGHT*MESSAGE_HEIGHT); for (int i=0; i<MESSAGE_HEIGHT; i++) { if (messages[i] != null) { for (int j=0; j<messages[i].length(); j++) { g.drawImage(SystemFont.getCharacter(messages[i].charAt(j), Color.WHITE), j*TILE_WIDTH, (VIEWPORT_HEIGHT+i)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT, null); } } } // Render status bar g.drawImage(SystemFont.getCharacter((char) 3, Color.RED), TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); String healthText = Integer.toString(Main.currentGame.health); double healthPercentage = ((double) Main.currentGame.health) / ((double) Main.currentGame.maxHealth); Color healthColor = Color.WHITE; if (healthPercentage < 0.2) { healthColor = Color.RED; } else if (healthPercentage < 0.55) { healthColor = Color.YELLOW; } else if (healthPercentage < 1) { healthColor = Color.GREEN; } for (int i=0; i<healthText.length(); i++) { g.drawImage(SystemFont.getCharacter(healthText.charAt(i), healthColor), (i+2)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); } g.drawImage(SystemFont.getCharacter((char) 5, Color.GRAY), (healthText.length()+3)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); int b = healthText.length()+4; String defenseText = Integer.toString(Main.currentGame.getDefense()); for (int i=0; i<defenseText.length(); i++) { g.drawImage(SystemFont.getCharacter(defenseText.charAt(i), Color.WHITE), (i+b)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); } b+=defenseText.length()+1; g.drawImage(SystemFont.getCharacter('E', Color.WHITE), (b)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); g.drawImage(SystemFont.getCharacter('X', Color.WHITE), (b+1)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); g.drawImage(SystemFont.getCharacter('P', Color.WHITE), (b+2)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); b+=3; String expText = Functions.padLeft(Integer.toString(Main.currentGame.experience), 3, '0'); for (int i=0; i<expText.length(); i++) { g.drawImage(SystemFont.getCharacter(expText.charAt(i), Color.WHITE), (i+b)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); } b+=expText.length(); g.drawImage(SystemFont.getCharacter(':', Color.WHITE), (b)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); b++; String levelText = Integer.toString(Main.currentGame.level); for (int i=0; i<levelText.length(); i++) { g.drawImage(SystemFont.getCharacter(levelText.charAt(i), Color.WHITE), (i+b)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null); } } public void processInput(KeyEvent e) { // Handle input switch (e.getKeyCode()) { case KeyEvent.VK_LEFT: case KeyEvent.VK_RIGHT: case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: Direction dir = Direction.fromKeyEvent(e); Point to = dir.to(new Point(playerx, playery)); if ((isValidPosition(to.x,to.y)) && (!grid[to.x][to.y].isBlocked())) { // Check for mobs boolean foundMob = false; for (Mob mob : mobs) { if (mob.getPosition().equals(to)) { printMessage("You hit the " + mob.getName().toLowerCase()); mob.health -= Main.currentGame.getAttackPower(); if (mob.health <= 0) { printMessage("You killed the " + mob.getName().toLowerCase() + "!"); mobs.remove(mob); Main.currentGame.experience += (mob.getBaseExperience()/(Main.currentGame.level*Main.currentGame.level)); if (Main.currentGame.experience >= 1000) { Main.currentGame.level++; Main.currentGame.experience -= 1000; int hpGain = Functions.rollDice(6, 2) + 3; Main.currentGame.health += hpGain; Main.currentGame.maxHealth += hpGain; printMessage("You grow to level " + Main.currentGame.level + "!"); } if (Functions.random(0, 1000) < (mob.getBaseExperience() / (floor*floor))) { ItemInstance ii = new ItemInstance(); ii.item = Item.getWeightedRandomItem(); ii.x = mob.x; ii.y = mob.y; items.add(ii); } } foundMob = true; break; } } if (!foundMob) { playerx = to.x; playery = to.y; } } else { printMessage("Blocked: " + dir.name()); return; } break; case KeyEvent.VK_G: for (ItemInstance ii : items) { if ((ii.x == playerx) && (ii.y == playery)) { printMessage("You get a " + ii.item.getItemName().toLowerCase()); Main.currentGame.inventory.add(ii.item); items.remove(ii); if (ii.item == Item.Key) { printMessage("All the windows in the room shatter!"); for (int x=0; x<mapWidth; x++) { for (int y=0; y<mapHeight; y++) { if (grid[x][y] == Tile.Window) { grid[x][y] = Tile.ShatteredWindow; } } } } break; } } break; case KeyEvent.VK_W: // Wait a turn break; case KeyEvent.VK_PERIOD: if (e.isShiftDown()) { if (grid[playerx][playery] == Tile.UpStairs) { if (Main.currentGame.inventory.contains(Item.Key)) { Main.currentGame.inventory.remove(Item.Key); Main.setGameState(new MapViewGameState(floor+1)); return; } else { printMessage("The stairs are locked! You need a key."); } } break; } case KeyEvent.VK_I: if (Main.currentGame.inventory.isEmpty()) { printMessage("You have no items"); } else { InventoryOverlay io = new InventoryOverlay(); Main.addRenderable(io); Main.addInputable(io); return; } default: return; } tick(); } public void tick() { // Move mobs for (Mob mob : mobs) { // If the mob is hostile, it should move toward the player IF IT CAN SEE the player // Also, if it is adjacent to the player, it should attack if ((mob.hostile) && (canSeePlayer(mob.x, mob.y))) { if (arePointsAdjacent(playerx, playery, mob.x, mob.y, false)) { // Attack! Main.currentGame.health -= Math.max(mob.getAttackPower() - Functions.random(0,Main.currentGame.getDefense()), 0); printMessage(mob.getBattleMessage()); } else { List<Direction> path = findPath(mob.getPosition(), new Point(playerx, playery)); if (path != null) { Point to = path.get(0).to(mob.getPosition()); boolean found = false; for (Mob m : mobs) { if (m.getPosition().equals(to)) { found = true; break; } } if (!found) { mob.moveInDirection(path.get(0)); } } } } else { // If the mob isn't hostile, it should just move around randomly Direction toDir = null; for (int i=0; i<10; i++) { toDir = Direction.getRandomDirection(); Point to = toDir.to(mob.getPosition()); if ((isValidPosition(to.x,to.y)) && (!grid[to.x][to.y].isBlocked()) && (!to.equals(new Point(playerx, playery)))) { boolean found = false; for (Mob m : mobs) { if (m.getPosition().equals(to)) { found = true; break; } } if (!found) { mob.moveInDirection(toDir); break; } } } } // Snow weakens (but doesn't kill) mobs too! if ((grid[mob.x][mob.y] == Tile.Snow) && (heartbeat % 2 == 0)) { mob.health--; } } // Move snow if (snowGrow) { for (int x=0; x<mapWidth; x++) { for (int y=0; y<mapHeight; y++) { if (grid[x][y] == Tile.Snow) { for (Direction d : Direction.values()) { Point to = d.to(new Point(x, y)); if ((!grid[to.x][to.y].isBlocked()) && (grid[to.x][to.y] != Tile.Snow) && (grid[to.x][to.y] != Tile.UpStairs)) { grid[to.x][to.y] = Tile.SnowTemp; } } } } } for (int x=0; x<mapWidth; x++) { for (int y=0; y<mapHeight; y++) { if (grid[x][y] == Tile.ShatteredWindow) { for (Direction d : Direction.values()) { Point to = d.to(new Point(x, y)); if ((!grid[to.x][to.y].isBlocked()) && (grid[to.x][to.y] != Tile.Snow)) { grid[to.x][to.y] = Tile.Snow; } } } else if (grid[x][y] == Tile.SnowTemp) { grid[x][y] = Tile.Snow; } } } } snowGrow = !snowGrow; // Heartbeat if (heartbeat % 2 == 0) { if (grid[playerx][playery] == Tile.Snow) { Main.currentGame.health--; } } if ((grid[playerx][playery] != Tile.Snow) && ((heartbeat == Functions.random(0, 7)) || (heartbeat == 8))) { if (Main.currentGame.health < Main.currentGame.maxHealth) { Main.currentGame.health++; } } heartbeat++; if (heartbeat == 8) heartbeat = 0; // Spawn mobs if (spawnTimer == 10) { spawnTimer = 0; if (mobs.size() < (rooms.size()*2)) { Room r = rooms.get(Functions.random(0, rooms.size()-1)); if (r.canGenerateMonsters()) { Mob m = createInDepthMonster(r); if (!gridLighting[m.x][m.y]) { mobs.add(m); } } } } else { spawnTimer++; } // Do viewport stuff adjustViewport(); calculateFieldOfView(); // Handle death if (Main.currentGame.health <= 0) { printMessage("You have died! Press [ENTER] to quit."); Main.addInputable(new Inputable() { @Override public void processInput(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { System.exit(0); } } }); } } private void adjustViewport() { if (playerx > (VIEWPORT_WIDTH/2)) { if (playerx < (mapWidth - (VIEWPORT_WIDTH/2-1))) { viewportx = playerx - (VIEWPORT_WIDTH/2); } else { viewportx = mapWidth - VIEWPORT_WIDTH; } } else { viewportx = 0; } if (playery > (VIEWPORT_HEIGHT/2)) { if (playery < (mapHeight - (VIEWPORT_HEIGHT/2-1))) { viewporty = playery - (VIEWPORT_HEIGHT/2); } else { viewporty = mapHeight - VIEWPORT_HEIGHT; } } else { viewporty = 0; } } private boolean isValidPosition(int x, int y) { if (x < 0) return false; if (x > mapWidth) return false; if (y < 0) return false; if (y > mapHeight) return false; return true; } private boolean isInViewport(int x, int y) { if (x < viewportx) return false; if (x > viewportx+VIEWPORT_WIDTH) return false; if (y < viewporty) return false; if (y > viewporty+VIEWPORT_HEIGHT) return false; return true; } public void printMessage(String message) { String temp = message; while (temp.length() > VIEWPORT_WIDTH) { String shortm = temp.substring(0, VIEWPORT_WIDTH); if ((temp.charAt(VIEWPORT_WIDTH) == ' ') || (shortm.endsWith(" "))) { pushUpMessages(shortm); temp = temp.substring(VIEWPORT_WIDTH); } else { int lastSpace = shortm.lastIndexOf(" "); pushUpMessages(shortm.substring(0, lastSpace)); temp = temp.substring(lastSpace); } } pushUpMessages(temp); } private void pushUpMessages(String message) { for (int i=1; i<MESSAGE_HEIGHT; i++) { messages[i-1] = messages[i]; } messages[MESSAGE_HEIGHT-1] = message; } private boolean canSeePlayer(int mx, int my) { int dx = playerx - mx; int dy = playery - my; int ax = Math.abs(dx) << 1; int ay = Math.abs(dy) << 1; int sx = (int) Math.signum(dx); int sy = (int) Math.signum(dy); int x = mx; int y = my; if (ax > ay) { int t = ay - (ax >> 1); do { if (t >= 0) { y += sy; t -= ax; } x += sx; t += ay; if ((x == playerx) && (y == playery)) { return true; } } while (!grid[x][y].isBlocked()); return false; } else { int t = ax - (ay >> 1); do { if (t >= 0) { x += sx; t -= ay; } y += sy; t += ax; if ((x == playerx) && (y == playery)) { return true; } } while (!grid[x][y].isBlocked()); return false; } } private boolean arePointsAdjacent(int px, int py, int mx, int my, boolean includeDiagonals) { if (mx == (px-1)) { if ((my == (py-1)) && (includeDiagonals)) return true; if (my == py) return true; if ((my == (py+1)) && (includeDiagonals)) return true; } else if (mx == px) { if (my == (py-1)) return true; if (my == (py+1)) return true; } else if (mx == (px+1)) { if ((my == (py-1)) && (includeDiagonals)) return true; if (my == py) return true; if ((my == (py+1)) && (includeDiagonals)) return true; } return false; } private List<Direction> findPath(Point from, Point to) { return findPath(from, to, new ArrayList<Point>()); } private List<Direction> findPath(Point from, Point to, List<Point> attempts) { /* Iterate over all of the directions and check if moving in that * direction would result in the destination position. If so, the * correct path has been acquired and thus we can return. */ for (Direction d : Direction.values()) { Point loc = d.to(from); if (to.equals(loc)) { List<Direction> moves = new ArrayList<Direction>(); moves.add(d); return moves; } } /* Calculate the directions to attempt and the order in which to do so * based on proximity to the destination */ List<Direction> ds = new ArrayList<Direction>(); for (Direction d : Direction.values()) { Point loc = d.to(from); if ((isValidPosition(loc.x, loc.y)) && (!grid[loc.x][loc.y].isBlocked())) { ds.add(d); } } List<Direction> tempd = new ArrayList<Direction>(); if (to.x < from.x) { tempd.add(Direction.West); } else if (to.x > from.x) { tempd.add(Direction.East); } else { if (!ds.contains(Direction.North) || !ds.contains(Direction.South)) { tempd.add(Direction.West); tempd.add(Direction.East); } } if (to.y < from.y) { tempd.add(Direction.North); } else if (to.y > from.y) { tempd.add(Direction.South); } else { if (!ds.contains(Direction.West) || !ds.contains(Direction.East)) { tempd.add(Direction.North); tempd.add(Direction.South); } } // Remove calculated directions that aren't legal movements tempd.retainAll(ds); // Randomize directions so movement is more fluid Collections.shuffle(tempd); // Iterate over the suggested directions for (Direction d : tempd) { /* If the position in the suggested direction has not already been * covered, recursively search from the new position */ Point loc = d.to(from); if (!attempts.contains(loc)) { attempts.add(loc); List<Direction> moves = findPath(loc, to, attempts); if (moves != null) { moves.add(0, d); return moves; } } } return null; } private Mob createInDepthMonster(Room r) { int x = Functions.random(r.getX()+1, r.getX()+r.getWidth()-2); int y = Functions.random(r.getY()+1, r.getY()+r.getHeight()-2); List<Class> mobTypes = new ArrayList<Class>(); switch (floor) { case 10: case 9: case 8: case 7: case 6: case 5: case 4: case 3: case 2: case 1: mobTypes.add(Mouse.class); mobTypes.add(Rat.class); mobTypes.add(Spider.class); } try { return (Mob) mobTypes.get(Functions.random(0, mobTypes.size()-1)).getConstructor(int.class, int.class).newInstance(x, y); } catch (Exception ex) { return null; } } public void dropItemAtPlayer(Item item) { ItemInstance ii = new ItemInstance(); ii.item = item; ii.x = playerx; ii.y = playery; items.add(ii); } }
true
true
public MapViewGameState(int floor) { this.floor = floor; mapWidth += (50 * (floor-1)); mapHeight += (50 * (floor-1)); grid = new Tile[mapWidth][mapHeight]; gridLighting = new boolean[mapWidth][mapHeight]; for (int x=0; x<mapWidth; x++) { for (int y=0; y<mapHeight; y++) { if ((x == 0) || (x == mapWidth-1) || (y == 0) || (y == mapHeight-1)) { grid[x][y] = Tile.StoneWall; } else { grid[x][y] = Tile.Unused; } } } Direction keyRoomDirection = Direction.getRandomDirection(); Rectangle legalBounds = null; switch (keyRoomDirection) { case North: legalBounds = new Rectangle(0, 14, mapWidth, mapHeight-14); break; case East: legalBounds = new Rectangle(0, 0, mapWidth-14, mapHeight); break; case South: legalBounds = new Rectangle(0, 0, mapWidth, mapHeight-14); break; case West: legalBounds = new Rectangle(14, 0, mapWidth-14, mapHeight); break; } makeRoom(mapWidth/2, mapHeight/2, Direction.getRandomDirection(), legalBounds); int currentFeatures = 1; int objects = 300; for (int countingTries = 0; countingTries < 1000; countingTries++) { if (currentFeatures == objects) { break; } int newx = 0; int xmod = 0; int newy = 0; int ymod = 0; Direction validTile = null; for (int testing = 0; testing < 1000; testing++) { newx = Functions.random(1, mapWidth-1); newy = Functions.random(1, mapHeight-1); validTile = null; if ((grid[newx][newy] == Tile.DirtWall) || (grid[newx][newy] == Tile.Corridor)) { if ((grid[newx][newy+1] == Tile.DirtFloor) || (grid[newx][newy+1] == Tile.Corridor)) { validTile = Direction.North; xmod = 0; ymod = -1; } else if ((grid[newx-1][newy] == Tile.DirtFloor) || (grid[newx-1][newy] == Tile.Corridor)) { validTile = Direction.East; xmod = 1; ymod = 0; } else if ((grid[newx][newy-1] == Tile.DirtFloor) || (grid[newx][newy-1] == Tile.Corridor)) { validTile = Direction.South; xmod = 0; ymod = 1; } else if ((grid[newx+1][newy] == Tile.DirtFloor) || (grid[newx+1][newy] == Tile.Corridor)) { validTile = Direction.West; xmod = -1; ymod = 0; } if (validTile != null) { if (grid[newx][newy+1] == Tile.Door) { validTile = null; } else if (grid[newx-1][newy] == Tile.Door) { validTile = null; } else if (grid[newx][newy-1] == Tile.Door) { validTile = null; } else if (grid[newx+1][newy] == Tile.Door) { validTile = null; } } if (validTile != null) { break; } } } if (validTile != null) { if (Functions.random(0, 100) <= 75) { if (makeRoom(newx+xmod, newy+ymod, validTile, legalBounds)) { currentFeatures++; grid[newx][newy] = Tile.Door; grid[newx+xmod][newy+ymod] = Tile.DirtFloor; } } else { if (makeCorridor(newx+xmod, newy+ymod, validTile)) { currentFeatures++; grid[newx][newy] = Tile.Door; } } } } int newx = 0; int newy = 0; int ways = 0; int state = 0; while (state != 10) { for (int testing = 0; testing < 1000; testing++) { newx = Functions.random(1, mapWidth-1); newy = Functions.random(1, mapHeight-2); ways = 4; for (Direction dir : Direction.values()) { Point to = dir.to(new Point(newx, newy)); if ((isValidPosition(to.x, to.y)) && (grid[to.x][to.y] == Tile.DirtFloor) || (grid[to.x][to.y] == Tile.Corridor)) { ways--; } } if (state == 0) { if (ways == 0) { grid[newx][newy] = Tile.UpStairs; state = 1; break; } } else if (state == 1) { if (ways == 0) { grid[newx][newy] = Tile.DownStairs; playerx=newx; playery=newy; state = 10; break; } } } } // Create key room Room oRoom = null; for (Room r : rooms) { if (oRoom == null) { oRoom = r; } else if ((keyRoomDirection == Direction.North) && (r.getY() < oRoom.getY())) { oRoom = r; } else if ((keyRoomDirection == Direction.East) && (r.getX() > oRoom.getX())) { oRoom = r; } else if ((keyRoomDirection == Direction.South) && (r.getY() > oRoom.getY())) { oRoom = r; } else if ((keyRoomDirection == Direction.West) && (r.getX() < oRoom.getX())) { oRoom = r; } } Room room = null; switch (keyRoomDirection) { case North: room = new Room(oRoom.getX()+oRoom.getWidth()/2-3, oRoom.getY()-13, 7, 13, false); break; case East: room = new Room(oRoom.getX()+oRoom.getWidth(), oRoom.getY()+oRoom.getHeight()/2-3, 13, 7, false); break; case South: room = new Room(oRoom.getX()+oRoom.getWidth()/2-3, oRoom.getY()+oRoom.getHeight(), 7, 13, false); break; case West: room = new Room(oRoom.getX()-13, oRoom.getY()+oRoom.getHeight()/2-3, 13, 7, false); break; } for (int ytemp=room.getY(); ytemp < room.getY()+room.getHeight(); ytemp++) { for (int xtemp=room.getX(); xtemp < room.getX()+room.getWidth(); xtemp++) { if (xtemp == room.getX()) { if (((keyRoomDirection == Direction.North) || (keyRoomDirection == Direction.South)) && (ytemp % 2 == 0) && (ytemp != room.getY())) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else if (xtemp == room.getX()+room.getWidth()-1) { if (((keyRoomDirection == Direction.North) || (keyRoomDirection == Direction.South)) && (ytemp % 2 == 0) && (ytemp != (room.getY()+room.getHeight()))) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else if (ytemp == room.getY()) { if (((keyRoomDirection == Direction.West) || (keyRoomDirection == Direction.East)) && (xtemp % 2 == 0) && (xtemp != room.getX())) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else if (ytemp == room.getY()+room.getHeight()-1) { if (((keyRoomDirection == Direction.West) || (keyRoomDirection == Direction.East)) && (xtemp % 2 == 0) && (xtemp != (room.getX()+room.getWidth()))) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else { grid[xtemp][ytemp] = Tile.DirtFloor; } } } ItemInstance key = new ItemInstance(); key.item = Item.Key; switch (keyRoomDirection) { case North: grid[room.getX()+room.getWidth()/2][room.getY()+room.getHeight()] = Tile.Door; grid[room.getX()+room.getWidth()/2][room.getY()+room.getHeight()-1] = Tile.DirtFloor; key.x = room.getX()+3; key.y = room.getY()+3; break; case East: grid[room.getX()-1][room.getY()+room.getHeight()/2] = Tile.Door; grid[room.getX()][room.getY()+room.getHeight()/2] = Tile.DirtFloor; key.x = room.getX()+10; key.y = room.getY()+3; break; case South: grid[room.getX()+room.getWidth()/2][room.getY()-1] = Tile.Door; grid[room.getX()+room.getWidth()/2][room.getY()] = Tile.DirtFloor; key.x = room.getX()+3; key.y = room.getY()+10; break; case West: grid[room.getX()+room.getWidth()][room.getY()+room.getHeight()/2] = Tile.Door; grid[room.getX()+room.getWidth()-1][room.getY()+room.getHeight()/2] = Tile.DirtFloor; key.x = room.getX()+3; key.y = room.getY()+3; break; } items.add(key); rooms.add(room); adjustViewport(); calculateFieldOfView(); }
public MapViewGameState(int floor) { this.floor = floor; mapWidth += (50 * (floor-1)); mapHeight += (50 * (floor-1)); grid = new Tile[mapWidth][mapHeight]; gridLighting = new boolean[mapWidth][mapHeight]; for (int x=0; x<mapWidth; x++) { for (int y=0; y<mapHeight; y++) { if ((x == 0) || (x == mapWidth-1) || (y == 0) || (y == mapHeight-1)) { grid[x][y] = Tile.StoneWall; } else { grid[x][y] = Tile.Unused; } } } Direction keyRoomDirection = Direction.getRandomDirection(); Rectangle legalBounds = null; switch (keyRoomDirection) { case North: legalBounds = new Rectangle(0, 14, mapWidth, mapHeight-14); break; case East: legalBounds = new Rectangle(0, 0, mapWidth-14, mapHeight); break; case South: legalBounds = new Rectangle(0, 0, mapWidth, mapHeight-14); break; case West: legalBounds = new Rectangle(14, 0, mapWidth-14, mapHeight); break; } makeRoom(mapWidth/2, mapHeight/2, Direction.getRandomDirection(), legalBounds); int currentFeatures = 1; int objects = 300; for (int countingTries = 0; countingTries < 1000; countingTries++) { if (currentFeatures == objects) { break; } int newx = 0; int xmod = 0; int newy = 0; int ymod = 0; Direction validTile = null; for (int testing = 0; testing < 1000; testing++) { newx = Functions.random(1, mapWidth-1); newy = Functions.random(1, mapHeight-1); validTile = null; if ((grid[newx][newy] == Tile.DirtWall) || (grid[newx][newy] == Tile.Corridor)) { if ((grid[newx][newy+1] == Tile.DirtFloor) || (grid[newx][newy+1] == Tile.Corridor)) { validTile = Direction.North; xmod = 0; ymod = -1; } else if ((grid[newx-1][newy] == Tile.DirtFloor) || (grid[newx-1][newy] == Tile.Corridor)) { validTile = Direction.East; xmod = 1; ymod = 0; } else if ((grid[newx][newy-1] == Tile.DirtFloor) || (grid[newx][newy-1] == Tile.Corridor)) { validTile = Direction.South; xmod = 0; ymod = 1; } else if ((grid[newx+1][newy] == Tile.DirtFloor) || (grid[newx+1][newy] == Tile.Corridor)) { validTile = Direction.West; xmod = -1; ymod = 0; } if (validTile != null) { if (grid[newx][newy+1] == Tile.Door) { validTile = null; } else if (grid[newx-1][newy] == Tile.Door) { validTile = null; } else if (grid[newx][newy-1] == Tile.Door) { validTile = null; } else if (grid[newx+1][newy] == Tile.Door) { validTile = null; } } if (validTile != null) { break; } } } if (validTile != null) { if (Functions.random(0, 100) <= 75) { if (makeRoom(newx+xmod, newy+ymod, validTile, legalBounds)) { currentFeatures++; grid[newx][newy] = Tile.Door; grid[newx+xmod][newy+ymod] = Tile.DirtFloor; } } else { if (makeCorridor(newx+xmod, newy+ymod, validTile)) { currentFeatures++; grid[newx][newy] = Tile.Door; } } } } int newx = 0; int newy = 0; int ways = 0; int state = 0; while (state != 10) { for (int testing = 0; testing < 1000; testing++) { newx = Functions.random(1, mapWidth-2); newy = Functions.random(1, mapHeight-2); ways = 4; for (Direction dir : Direction.values()) { Point to = dir.to(new Point(newx, newy)); if ((isValidPosition(to.x, to.y)) && (grid[to.x][to.y] == Tile.DirtFloor) || (grid[to.x][to.y] == Tile.Corridor)) { ways--; } } if (state == 0) { if (ways == 0) { grid[newx][newy] = Tile.UpStairs; state = 1; break; } } else if (state == 1) { if (ways == 0) { grid[newx][newy] = Tile.DownStairs; playerx=newx; playery=newy; state = 10; break; } } } } // Create key room Room oRoom = null; for (Room r : rooms) { if (oRoom == null) { oRoom = r; } else if ((keyRoomDirection == Direction.North) && (r.getY() < oRoom.getY())) { oRoom = r; } else if ((keyRoomDirection == Direction.East) && (r.getX() > oRoom.getX())) { oRoom = r; } else if ((keyRoomDirection == Direction.South) && (r.getY() > oRoom.getY())) { oRoom = r; } else if ((keyRoomDirection == Direction.West) && (r.getX() < oRoom.getX())) { oRoom = r; } } Room room = null; switch (keyRoomDirection) { case North: room = new Room(oRoom.getX()+oRoom.getWidth()/2-3, oRoom.getY()-13, 7, 13, false); break; case East: room = new Room(oRoom.getX()+oRoom.getWidth(), oRoom.getY()+oRoom.getHeight()/2-3, 13, 7, false); break; case South: room = new Room(oRoom.getX()+oRoom.getWidth()/2-3, oRoom.getY()+oRoom.getHeight(), 7, 13, false); break; case West: room = new Room(oRoom.getX()-13, oRoom.getY()+oRoom.getHeight()/2-3, 13, 7, false); break; } for (int ytemp=room.getY(); ytemp < room.getY()+room.getHeight(); ytemp++) { for (int xtemp=room.getX(); xtemp < room.getX()+room.getWidth(); xtemp++) { if (xtemp == room.getX()) { if (((keyRoomDirection == Direction.North) || (keyRoomDirection == Direction.South)) && (ytemp % 2 == 0) && (ytemp != room.getY())) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else if (xtemp == room.getX()+room.getWidth()-1) { if (((keyRoomDirection == Direction.North) || (keyRoomDirection == Direction.South)) && (ytemp % 2 == 0) && (ytemp != (room.getY()+room.getHeight()))) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else if (ytemp == room.getY()) { if (((keyRoomDirection == Direction.West) || (keyRoomDirection == Direction.East)) && (xtemp % 2 == 0) && (xtemp != room.getX())) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else if (ytemp == room.getY()+room.getHeight()-1) { if (((keyRoomDirection == Direction.West) || (keyRoomDirection == Direction.East)) && (xtemp % 2 == 0) && (xtemp != (room.getX()+room.getWidth()))) { grid[xtemp][ytemp] = Tile.Window; } else { grid[xtemp][ytemp] = Tile.DirtWall; } } else { grid[xtemp][ytemp] = Tile.DirtFloor; } } } ItemInstance key = new ItemInstance(); key.item = Item.Key; switch (keyRoomDirection) { case North: grid[room.getX()+room.getWidth()/2][room.getY()+room.getHeight()] = Tile.Door; grid[room.getX()+room.getWidth()/2][room.getY()+room.getHeight()-1] = Tile.DirtFloor; key.x = room.getX()+3; key.y = room.getY()+3; break; case East: grid[room.getX()-1][room.getY()+room.getHeight()/2] = Tile.Door; grid[room.getX()][room.getY()+room.getHeight()/2] = Tile.DirtFloor; key.x = room.getX()+10; key.y = room.getY()+3; break; case South: grid[room.getX()+room.getWidth()/2][room.getY()-1] = Tile.Door; grid[room.getX()+room.getWidth()/2][room.getY()] = Tile.DirtFloor; key.x = room.getX()+3; key.y = room.getY()+10; break; case West: grid[room.getX()+room.getWidth()][room.getY()+room.getHeight()/2] = Tile.Door; grid[room.getX()+room.getWidth()-1][room.getY()+room.getHeight()/2] = Tile.DirtFloor; key.x = room.getX()+3; key.y = room.getY()+3; break; } items.add(key); rooms.add(room); adjustViewport(); calculateFieldOfView(); }
diff --git a/src/cx/fbn/nevernote/sql/REnSearch.java b/src/cx/fbn/nevernote/sql/REnSearch.java index abb6c85..3fbbaa8 100644 --- a/src/cx/fbn/nevernote/sql/REnSearch.java +++ b/src/cx/fbn/nevernote/sql/REnSearch.java @@ -1,948 +1,948 @@ /* * This file is part of NixNote * Copyright 2009 Randy Baumgarte * * This file may be licensed under the terms of of the * GNU General Public License Version 2 (the ``GPL''). * * Software distributed under the License is distributed * on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either * express or implied. See the GPL for the specific language * governing rights and limitations. * * You should have received a copy of the GPL along with this * program. If not, go to http://www.gnu.org/licenses/gpl.html * or write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ package cx.fbn.nevernote.sql; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.regex.Pattern; import org.apache.commons.lang3.StringEscapeUtils; import com.evernote.edam.type.Note; import com.evernote.edam.type.Notebook; import com.evernote.edam.type.Tag; import cx.fbn.nevernote.sql.driver.NSqlQuery; import cx.fbn.nevernote.utilities.ApplicationLogger; public class REnSearch { private final List<String> searchWords; private final List<String> searchPhrases; private final List<String> notebooks; private final List<String> tags; private final List<String> intitle; private final List<String> created; private final List<String> updated; private final List<String> resource; private final List<String> subjectDate; private final List<String> longitude; private final List<String> latitude; private final List<String> altitude; private final List<String> author; private final List<String> source; private final List<String> sourceApplication; private final List<String> recoType; private final List<String> todo; private final List<String> stack; private final List<Tag> tagIndex; private final ApplicationLogger logger; // private final DatabaseConnection db; private boolean any; private int minimumRecognitionWeight = 80; private final DatabaseConnection conn; public REnSearch(DatabaseConnection c, ApplicationLogger l, String s, List<Tag> t, int r) { logger = l; conn = c; tagIndex = t; minimumRecognitionWeight = r; searchWords = new ArrayList<String>(); searchPhrases = new ArrayList<String>(); notebooks = new ArrayList<String>(); tags = new ArrayList<String>(); intitle = new ArrayList<String>(); created = new ArrayList<String>(); updated = new ArrayList<String>(); resource = new ArrayList<String>(); subjectDate = new ArrayList<String>(); longitude = new ArrayList<String>(); latitude = new ArrayList<String>(); altitude = new ArrayList<String>(); author = new ArrayList<String>(); source = new ArrayList<String>(); sourceApplication = new ArrayList<String>(); recoType = new ArrayList<String>(); todo = new ArrayList<String>(); any = false; stack = new ArrayList<String>(); if (s == null) return; if (s.trim().equals("")) return; resolveSearch(s); } public List<String> getWords() { return searchWords; } public List<String> getNotebooks() { return notebooks; } public List<String> getIntitle() { return intitle; } public List<String> getTags() { return tags; } public List<String> getResource() { return resource; } public List<String> getAuthor() { return author; } public List<String> getSource() { return source; } public List<String> getSourceApplication() { return sourceApplication; } public List<String> getRecoType() { return recoType; } public List<String> getToDo() { return todo; } public List<String> getLongitude() { return longitude; } public List<String> getLatitude() { return latitude; } public List<String> getAltitude() { return altitude; } public List<String> getCreated() { return created; } public List<String> getUpdated() { return updated; } public List<String> getSubjectDate() { return subjectDate; } public List<String> getStack() { return stack; } // match tag names private boolean matchTagsAll(List<String> tagNames, List<String> list) { for (int j=0; j<list.size(); j++) { boolean negative = false; negative = false; if (list.get(j).startsWith("-")) negative = true; int pos = list.get(j).indexOf(":"); String filterName = cleanupWord(list.get(j).substring(pos+1)); filterName = filterName.replace("*", ".*"); // setup for regular expression pattern match if (tagNames.size() == 0 && !negative) return false; if (tagNames.size() == 0 && negative) return true; boolean good = false; for (int i=0; i<tagNames.size() && !good; i++) { boolean matches = Pattern.matches(filterName.toLowerCase(),tagNames.get(i).toLowerCase()); if (matches && !negative) good = true; if (!matches && negative) good = true; } if (!good) return false; } return true; } // match tag names private boolean matchTagsAny(List<String> tagNames, List<String> list) { if (list.size() == 0) return true; boolean negative = false; boolean found = false; for (int j=0; j<list.size(); j++) { negative = false; if (list.get(j).startsWith("-")) negative = true; int pos = list.get(j).indexOf(":"); String filterName = cleanupWord(list.get(j).substring(pos+1)); filterName = filterName.replace("*", ".*"); // setup for regular expression pattern match if (tagNames.size() == 0) found = false; for (int i=0; i<tagNames.size(); i++) { boolean matches = Pattern.matches(filterName.toLowerCase(),tagNames.get(i).toLowerCase()); if (matches) found = true; } } if (negative) return !found; else return found; } // Match notebooks in search terms against notes private boolean matchNotebook(String guid) { if (getNotebooks().size() == 0) return true; NotebookTable bookTable = new NotebookTable(logger, conn); List<Notebook> books = bookTable.getAll(); String name = new String(""); for (int i=0; i<books.size(); i++) { if (guid.equalsIgnoreCase(books.get(i).getGuid())) { name = books.get(i).getName(); i=books.size(); } } if (any) return matchListAny(getNotebooks(), name); else return matchListAll(getNotebooks(), name); } // Match notebooks in search terms against notes private boolean matchNotebookStack(String guid) { if (getStack().size() == 0) return true; NotebookTable bookTable = new NotebookTable(logger, conn); List<Notebook> books = bookTable.getAll(); String name = new String(""); for (int i=0; i<books.size(); i++) { if (guid.equalsIgnoreCase(books.get(i).getGuid())) { name = books.get(i).getStack(); i=books.size(); } } if (name == null) name = ""; if (any) return matchListAny(getStack(), name); else return matchListAll(getStack(), name); } // Match notebooks in search terms against notes private boolean matchListAny(List<String> list, String title) { if (list.size() == 0) return true; boolean negative = false; boolean found = false; for (int i=0; i<list.size(); i++) { int pos = list.get(i).indexOf(":"); negative = false; if (list.get(i).startsWith("-")) negative = true; String filterName = cleanupWord(list.get(i).substring(pos+1)); filterName = filterName.replace("*", ".*"); // setup for regular expression pattern match boolean matches = Pattern.matches(filterName.toLowerCase(),title.toLowerCase()); if (matches) found = true; } if (negative) return !found; else return found; } // Match notebooks in search terms against notes private boolean matchContentAny(Note n) { if (todo.size() == 0 && resource.size() == 0 && searchPhrases.size() == 0) return true; // pull back the record n = conn.getNoteTable().getNote(n.getGuid(), true, true, false, false, false); // Check for search phrases String text = StringEscapeUtils.unescapeHtml4(n.getContent().replaceAll("\\<.*?\\>", "")).toLowerCase(); boolean negative = false; for (int i=0; i<searchPhrases.size(); i++) { String phrase = searchPhrases.get(i); if (phrase.startsWith("-")) { negative = true; phrase = phrase.substring(1); } else negative = false; phrase = phrase.substring(1); phrase = phrase.substring(0,phrase.length()-1); if (text.indexOf(phrase)>=0) { if (negative) return false; else return true; } if (text.indexOf(phrase)<0 && negative) return true; } for (int i=0; i<todo.size(); i++) { String value = todo.get(i); value = value.replace("\"", ""); boolean desiredState; if (!value.endsWith(":false") && !value.endsWith(":true") && !value.endsWith(":*") && !value.endsWith("*")) return false; if (value.endsWith(":false")) desiredState = false; else desiredState = true; if (value.startsWith("-")) desiredState = !desiredState; int pos = n.getContent().indexOf("<en-todo"); if (pos == -1 && value.startsWith("-") && (value.endsWith("*") || value.endsWith(":"))) return true; if (value.endsWith("*")) return true; while (pos > -1) { int endPos = n.getContent().indexOf("/>", pos); String segment = n.getContent().substring(pos, endPos); boolean currentState; if (segment.toLowerCase().indexOf("checked=\"true\"") == -1) currentState = false; else currentState = true; if (desiredState == currentState) return true; pos = n.getContent().indexOf("<en-todo", pos+1); } } // Check resources for (int i=0; i<resource.size(); i++) { String resourceString = resource.get(i); resourceString = resourceString.replace("\"", ""); if (resourceString.startsWith("-")) negative = true; resourceString = resourceString.substring(resourceString.indexOf(":")+1); for (int j=0; j<n.getResourcesSize(); j++) { boolean match = stringMatch(n.getResources().get(j).getMime(), resourceString, negative); if (match) return true; } } return false; } // Take the initial search & split it apart private void resolveSearch(String search) { List<String> words = new ArrayList<String>(); StringBuffer b = new StringBuffer(search); int len = search.length(); char nextChar = ' '; boolean quote = false; for (int i=0, j=0; i<len; i++, j++) { if (search.charAt(i)==nextChar && !quote) { b.setCharAt(j,'\0'); nextChar = ' '; } else { if (search.charAt(i)=='\"') { if (!quote) { quote=true; } else { quote=false; j++; b.insert(j, "\0"); } } } if (((i+2)<len) && search.charAt(i) == '\\') { i=i+2; } } search = b.toString(); int pos = 0; for (int i=0; i<search.length(); i++) { if (search.charAt(i) == '\0') { search = search.substring(1); i=0; } else { pos = search.indexOf('\0'); if (pos > 0) { words.add(search.substring(0,pos).toLowerCase()); search = search.substring(pos); i=0; } } } if (search.charAt(0)=='\0') words.add(search.substring(1).toLowerCase()); else words.add(search.toLowerCase()); parseTerms(words); } // Parse out individual words into separate lists // Supported options // Tags // Notebooks // Intitle // author // source // source application // created // updated // subject date private void parseTerms(List<String> words) { for (int i=0; i<words.size(); i++) { String word = words.get(i); int pos = word.indexOf(":"); if (word.startsWith("any:")) { any = true; word = word.substring(4).trim(); pos = word.indexOf(":"); } boolean searchPhrase = false; if (pos < 0 && word.indexOf(" ") > 0) { searchPhrase=true; searchPhrases.add(word.toLowerCase()); } if (!searchPhrase && pos < 0) if (word != null && word.length() > 0) getWords().add(word); // getWords().add("*"+word+"*"); //// WILDCARD if (word.startsWith("intitle:")) intitle.add("*"+word+"*"); if (word.startsWith("-intitle:")) intitle.add("*"+word+"*"); if (word.startsWith("notebook:")) notebooks.add(word); if (word.startsWith("-notebook:")) notebooks.add(word); if (word.startsWith("tag:")) tags.add(word); if (word.startsWith("-tag:")) tags.add(word); if (word.startsWith("resource:")) resource.add(word); if (word.startsWith("-resource:")) resource.add(word); if (word.startsWith("author:")) author.add(word); if (word.startsWith("-author:")) author.add(word); if (word.startsWith("source:")) source.add(word); if (word.startsWith("-source:")) source.add(word); if (word.startsWith("sourceapplication:")) sourceApplication.add(word); if (word.startsWith("-sourceapplication:")) sourceApplication.add(word); if (word.startsWith("recotype:")) recoType.add(word); if (word.startsWith("-recotype:")) recoType.add(word); if (word.startsWith("todo:")) todo.add(word); if (word.startsWith("-todo:")) todo.add(word); if (word.startsWith("stack:")) stack.add(word); if (word.startsWith("-stack:")) stack.add(word); if (word.startsWith("latitude:")) latitude.add(word); if (word.startsWith("-latitude:")) latitude.add(word); if (word.startsWith("longitude:")) longitude.add(word); if (word.startsWith("-longitude:")) longitude.add(word); if (word.startsWith("altitude:")) altitude.add(word); if (word.startsWith("-altitude:")) altitude.add(word); if (word.startsWith("created:")) created.add(word); if (word.startsWith("-created:")) created.add(word); if (word.startsWith("updated:")) updated.add(word); if (word.startsWith("-updated:")) updated.add(word); if (word.startsWith("subjectdate:")) created.add(word); if (word.startsWith("-subjectdate:")) created.add(word); } } // Match notebooks in search terms against notes private boolean matchListAll(List<String> list, String title) { if (list.size() == 0) return true; boolean negative = false; for (int i=0; i<list.size(); i++) { int pos = list.get(i).indexOf(":"); negative = false; if (list.get(i).startsWith("-")) negative = true; String filterName = cleanupWord(list.get(i).substring(pos+1)); filterName = filterName.replace("*", ".*"); // setup for regular expression pattern match boolean matches = Pattern.matches(filterName.toLowerCase(),title.toLowerCase()); if (matches && negative) return false; if (matches && !negative) return true; } if (negative) return true; else return false; } // Match notebooks in search terms against notes private boolean matchContentAll(Note n) { if (todo.size() == 0 && resource.size() == 0 && searchPhrases.size() == 0) return true; boolean returnTodo = false; boolean returnResource = false; boolean returnPhrase = false; if (todo.size() == 0) returnTodo = true; if (resource.size() == 0) returnResource = true; if (searchPhrases.size() == 0) returnPhrase = true; n = conn.getNoteTable().getNote(n.getGuid(), true, true, false, false, false); // Check for search phrases String text = StringEscapeUtils.unescapeHtml4(n.getContent().replaceAll("\\<.*?\\>", "")).toLowerCase(); boolean negative = false; for (int i=0; i<searchPhrases.size(); i++) { String phrase = searchPhrases.get(i); if (phrase.startsWith("-")) { negative = true; phrase = phrase.substring(1); } else negative = false; phrase = phrase.substring(1); phrase = phrase.substring(0,phrase.length()-1); if (text.indexOf(phrase)>=0) { if (!negative) returnPhrase = true; } if (text.indexOf(phrase)<0 && negative) returnPhrase = true; } for (int i=0; i<todo.size(); i++) { String value = todo.get(i); value = value.replace("\"", ""); boolean desiredState; if (!value.endsWith(":false") && !value.endsWith(":true") && !value.endsWith(":*") && !value.endsWith("*")) return false; if (value.endsWith(":false")) desiredState = false; else desiredState = true; if (value.startsWith("-")) desiredState = !desiredState; int pos = n.getContent().indexOf("<en-todo"); if (pos == -1 && value.startsWith("-") && (value.endsWith("*") || value.endsWith(":"))) return true; if (pos > -1 && value.startsWith("-") && (value.endsWith("*") || value.endsWith(":"))) return false; if (pos == -1) return false; if (value.endsWith("*")) returnTodo = true; while (pos > -1) { int endPos = n.getContent().indexOf("/>", pos); String segment = n.getContent().substring(pos, endPos); boolean currentState; if (segment.toLowerCase().indexOf("checked=\"true\"") == -1) currentState = false; else currentState = true; if (desiredState == currentState) returnTodo = true; pos = n.getContent().indexOf("<en-todo", pos+1); } } // Check resources for (int i=0; i<resource.size(); i++) { String resourceString = resource.get(i); resourceString = resourceString.replace("\"", ""); negative = false; if (resourceString.startsWith("-")) negative = true; resourceString = resourceString.substring(resourceString.indexOf(":")+1); if (resourceString.equals("")) return false; for (int j=0; j<n.getResourcesSize(); j++) { boolean match = stringMatch(n.getResources().get(j).getMime(), resourceString, negative); if (!match) return false; returnResource = true; } } return returnResource && returnTodo && returnPhrase; } private boolean stringMatch(String content, String text, boolean negative) { String regex; if (content == null && !negative) return false; if (content == null && negative) return true; if (text.endsWith("*")) { text = text.substring(0,text.length()-1); regex = text; } else { regex = text; } content = content.toLowerCase(); regex = regex.toLowerCase(); boolean matches = content.startsWith(regex); if (negative) return !matches; return matches; } // Remove odd strings from search terms private String cleanupWord(String word) { if (word.startsWith("\"")) word = word.substring(1); if (word.endsWith("\"")) word = word.substring(0,word.length()-1); word = word.replace("\\\"","\""); word = word.replace("\\\\","\\"); return word; } // Match dates private boolean matchDatesAll(List<String> dates, long noteDate) { if (dates.size()== 0) return true; boolean negative = false; for (int i=0; i<dates.size(); i++) { String requiredDate = dates.get(i); if (requiredDate.startsWith("-")) negative = true; int response = 0; requiredDate = requiredDate.substring(requiredDate.indexOf(":")+1); try { response = dateCheck(requiredDate, noteDate); } catch (java.lang.NumberFormatException e) {return false;} { if (negative && response < 0) return false; if (!negative && response > 0) return false; } } return true; } private boolean matchDatesAny(List<String> dates, long noteDate) { if (dates.size()== 0) return true; boolean negative = false; for (int i=0; i<dates.size(); i++) { String requiredDate = dates.get(i); if (requiredDate.startsWith("-")) negative = true; int response = 0; requiredDate = requiredDate.substring(requiredDate.indexOf(":")+1); try { response = dateCheck(requiredDate, noteDate); } catch (java.lang.NumberFormatException e) {return false;} { if (negative && response > 0) return true; if (!negative && response < 0) return true; } } return false; } @SuppressWarnings("unused") private void printCalendar(Calendar calendar) { // define output format and print SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy hh:mm:ss aaa"); String date = sdf.format(calendar.getTime()); System.err.print(date); calendar = new GregorianCalendar(); } //**************************************** //**************************************** // Match search terms against notes //**************************************** //**************************************** public List<Note> matchWords() { logger.log(logger.EXTREME, "Inside EnSearch.matchWords()"); boolean subSelect = false; NoteTable noteTable = new NoteTable(logger, conn); List<String> validGuids = new ArrayList<String>(); if (searchWords.size() > 0) subSelect = true; NSqlQuery query = new NSqlQuery(conn.getConnection()); // Build a temp table for GUID results if (!conn.dbTableExists("SEARCH_RESULTS")) { query.exec("create temporary table SEARCH_RESULTS (guid varchar)"); query.exec("create temporary table SEARCH_RESULTS_MERGE (guid varchar)"); } else { query. exec("Delete from SEARCH_RESULTS"); query. exec("Delete from SEARCH_RESULTS_MERGE"); } NSqlQuery insertQuery = new NSqlQuery(conn.getConnection()); NSqlQuery indexQuery = new NSqlQuery(conn.getIndexConnection()); NSqlQuery mergeQuery = new NSqlQuery(conn.getConnection()); NSqlQuery deleteQuery = new NSqlQuery(conn.getConnection()); insertQuery.prepare("Insert into SEARCH_RESULTS (guid) values (:guid)"); mergeQuery.prepare("Insert into SEARCH_RESULTS_MERGE (guid) values (:guid)"); if (subSelect) { for (int i=0; i<getWords().size(); i++) { - if (getWords().get(i).indexOf("*") == 0) { + if (getWords().get(i).indexOf("*") == -1) { indexQuery.prepare("Select distinct guid from words where weight >= " +minimumRecognitionWeight + " and word=:word"); indexQuery.bindValue(":word", getWords().get(i)); } else { indexQuery.prepare("Select distinct guid from words where weight >= " +minimumRecognitionWeight + " and word like :word"); indexQuery.bindValue(":word", getWords().get(i).replace("*", "%")); } indexQuery.exec(); String guid = null; while(indexQuery.next()) { guid = indexQuery.valueString(0); if (i==0 || any) { insertQuery.bindValue(":guid", guid); insertQuery.exec(); } else { mergeQuery.bindValue(":guid", guid); mergeQuery.exec(); } } if (i>0 && !any) { deleteQuery.exec("Delete from SEARCH_RESULTS where guid not in (select guid from SEARCH_RESULTS_MERGE)"); deleteQuery.exec("Delete from SEARCH_RESULTS_MERGE"); } } query.prepare("Select distinct guid from Note where guid in (Select guid from SEARCH_RESULTS)"); if (!query.exec()) logger.log(logger.LOW, "Error merging search results:" + query.lastError()); while (query.next()) { validGuids.add(query.valueString(0)); } } List<Note> noteIndex = noteTable.getAllNotes(); List<Note> guids = new ArrayList<Note>(); for (int i=0; i<noteIndex.size(); i++) { Note n = noteIndex.get(i); boolean good = true; if (!validGuids.contains(n.getGuid()) && subSelect) good = false; // Start matching special stuff, like tags & notebooks if (any) { if (good && !matchTagsAny(n.getTagNames(), getTags())) good = false; if (good && !matchNotebook(n.getNotebookGuid())) good = false; if (good && !matchNotebookStack(n.getNotebookGuid())) good = false; if (good && !matchListAny(getIntitle(), n.getTitle())) good = false; if (good && !matchListAny(getAuthor(), n.getAttributes().getAuthor())) good = false; if (good && !matchListAny(getSource(), n.getAttributes().getSource())) good = false; if (good && !matchListAny(getSourceApplication(), n.getAttributes().getSourceApplication())) good = false; if (good && !matchContentAny(n)) good = false; if (good && !matchDatesAny(getCreated(), n.getCreated())) good = false; if (good && !matchDatesAny(getUpdated(), n.getUpdated())) good = false; if (good && n.getAttributes() != null && !matchDatesAny(getSubjectDate(), n.getAttributes().getSubjectDate())) good = false; } else { if (good && !matchTagsAll(n.getTagNames(), getTags())) good = false; if (good && !matchNotebook(n.getNotebookGuid())) good = false; if (good && !matchNotebookStack(n.getNotebookGuid())) good = false; if (good && !matchListAll(getIntitle(), n.getTitle())) good = false; if (good && !matchListAll(getAuthor(), n.getAttributes().getAuthor())) good = false; if (good && !matchListAll(getSource(), n.getAttributes().getSource())) good = false; if (good && !matchListAll(getSourceApplication(), n.getAttributes().getSourceApplication())) good = false; if (good && !matchContentAll(n)) good = false; if (good && !matchDatesAll(getCreated(), n.getCreated())) good = false; if (good && !matchDatesAll(getUpdated(), n.getUpdated())) good = false; if (good && n.getAttributes() != null && !matchDatesAll(getSubjectDate(), n.getAttributes().getSubjectDate())) good = false; } if (good) { guids.add(n); } } // For performance reasons, we didn't get the tags for every note individually. We now need to // get them List<NoteTagsRecord> noteTags = noteTable.noteTagsTable.getAllNoteTags(); for (int i=0; i<guids.size(); i++) { List<String> tags = new ArrayList<String>(); List<String> names = new ArrayList<String>(); for (int j=0; j<noteTags.size(); j++) { if (guids.get(i).getGuid().equals(noteTags.get(j).noteGuid)) { tags.add(noteTags.get(j).tagGuid); names.add(getTagNameByGuid(noteTags.get(j).tagGuid)); } } guids.get(i).setTagGuids(tags); guids.get(i).setTagNames(names); }; logger.log(logger.EXTREME, "Leaving EnSearch.matchWords()"); return guids; } private String getTagNameByGuid(String guid) { for (int i=0; i<tagIndex.size(); i++) { if (tagIndex.get(i).getGuid().equals(guid)) return tagIndex.get(i).getName(); } return ""; } // Compare dates public int dateCheck(String date, long noteDate) throws java.lang.NumberFormatException { int offset = 0; boolean found = false; GregorianCalendar calendar = new GregorianCalendar(); if (date.contains("-")) { String modifier = date.substring(date.indexOf("-")+1); offset = new Integer(modifier); offset = 0-offset; date = date.substring(0,date.indexOf("-")); } if (date.contains("+")) { String modifier = date.substring(date.indexOf("+")+1); offset = new Integer(modifier); date = date.substring(0,date.indexOf("+")); } if (date.equalsIgnoreCase("today")) { calendar.add(Calendar.DATE, offset); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 1); found = true; } if (date.equalsIgnoreCase("month")) { calendar.add(Calendar.MONTH, offset); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 1); found = true; } if (date.equalsIgnoreCase("year")) { calendar.add(Calendar.YEAR, offset); calendar.set(Calendar.MONTH, Calendar.JANUARY); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 1); found = true; } if (date.equalsIgnoreCase("week")) { calendar.add(Calendar.DATE, 0-calendar.get(Calendar.DAY_OF_WEEK)+1); calendar.add(Calendar.DATE,(offset*7)); calendar.set(Calendar.HOUR, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 1); found = true; } // If nothing was found, then we have a date number if (!found) { calendar = stringToGregorianCalendar(date); } String dateTimeFormat = new String("yyyyMMdd-HHmmss"); SimpleDateFormat simple = new SimpleDateFormat(dateTimeFormat); StringBuilder creationDate = new StringBuilder(simple.format(noteDate)); GregorianCalendar nCalendar = stringToGregorianCalendar(creationDate.toString().replace("-", "T")); if (calendar == null || nCalendar == null) // If we have something invalid, it automatically fails return 1; return calendar.compareTo(nCalendar); } private GregorianCalendar stringToGregorianCalendar(String date) { String datePart = date; GregorianCalendar calendar = new GregorianCalendar(); boolean GMT = false; String timePart = ""; if (date.contains("T")) { datePart = date.substring(0,date.indexOf("T")); timePart = date.substring(date.indexOf("T")+1); } else { timePart = "000001"; } if (datePart.length() != 8) return null; calendar.set(Calendar.YEAR, new Integer(datePart.substring(0,4))); calendar.set(Calendar.MONTH, new Integer(datePart.substring(4,6))-1); calendar.set(Calendar.DAY_OF_MONTH, new Integer(datePart.substring(6))); if (timePart.endsWith("Z")) { GMT = true; timePart = timePart.substring(0,timePart.length()-1); } timePart = timePart.concat("000000"); timePart = timePart.substring(0,6); calendar.set(Calendar.HOUR, new Integer(timePart.substring(0,2))); calendar.set(Calendar.MINUTE, new Integer(timePart.substring(2,4))); calendar.set(Calendar.SECOND, new Integer(timePart.substring(4))); if (GMT) calendar.set(Calendar.ZONE_OFFSET, -1*(calendar.get(Calendar.ZONE_OFFSET)/(1000*60*60))); return calendar; } }
true
true
public List<Note> matchWords() { logger.log(logger.EXTREME, "Inside EnSearch.matchWords()"); boolean subSelect = false; NoteTable noteTable = new NoteTable(logger, conn); List<String> validGuids = new ArrayList<String>(); if (searchWords.size() > 0) subSelect = true; NSqlQuery query = new NSqlQuery(conn.getConnection()); // Build a temp table for GUID results if (!conn.dbTableExists("SEARCH_RESULTS")) { query.exec("create temporary table SEARCH_RESULTS (guid varchar)"); query.exec("create temporary table SEARCH_RESULTS_MERGE (guid varchar)"); } else { query. exec("Delete from SEARCH_RESULTS"); query. exec("Delete from SEARCH_RESULTS_MERGE"); } NSqlQuery insertQuery = new NSqlQuery(conn.getConnection()); NSqlQuery indexQuery = new NSqlQuery(conn.getIndexConnection()); NSqlQuery mergeQuery = new NSqlQuery(conn.getConnection()); NSqlQuery deleteQuery = new NSqlQuery(conn.getConnection()); insertQuery.prepare("Insert into SEARCH_RESULTS (guid) values (:guid)"); mergeQuery.prepare("Insert into SEARCH_RESULTS_MERGE (guid) values (:guid)"); if (subSelect) { for (int i=0; i<getWords().size(); i++) { if (getWords().get(i).indexOf("*") == 0) { indexQuery.prepare("Select distinct guid from words where weight >= " +minimumRecognitionWeight + " and word=:word"); indexQuery.bindValue(":word", getWords().get(i)); } else { indexQuery.prepare("Select distinct guid from words where weight >= " +minimumRecognitionWeight + " and word like :word"); indexQuery.bindValue(":word", getWords().get(i).replace("*", "%")); } indexQuery.exec(); String guid = null; while(indexQuery.next()) { guid = indexQuery.valueString(0); if (i==0 || any) { insertQuery.bindValue(":guid", guid); insertQuery.exec(); } else { mergeQuery.bindValue(":guid", guid); mergeQuery.exec(); } } if (i>0 && !any) { deleteQuery.exec("Delete from SEARCH_RESULTS where guid not in (select guid from SEARCH_RESULTS_MERGE)"); deleteQuery.exec("Delete from SEARCH_RESULTS_MERGE"); } } query.prepare("Select distinct guid from Note where guid in (Select guid from SEARCH_RESULTS)"); if (!query.exec()) logger.log(logger.LOW, "Error merging search results:" + query.lastError()); while (query.next()) { validGuids.add(query.valueString(0)); } } List<Note> noteIndex = noteTable.getAllNotes(); List<Note> guids = new ArrayList<Note>(); for (int i=0; i<noteIndex.size(); i++) { Note n = noteIndex.get(i); boolean good = true; if (!validGuids.contains(n.getGuid()) && subSelect) good = false; // Start matching special stuff, like tags & notebooks if (any) { if (good && !matchTagsAny(n.getTagNames(), getTags())) good = false; if (good && !matchNotebook(n.getNotebookGuid())) good = false; if (good && !matchNotebookStack(n.getNotebookGuid())) good = false; if (good && !matchListAny(getIntitle(), n.getTitle())) good = false; if (good && !matchListAny(getAuthor(), n.getAttributes().getAuthor())) good = false; if (good && !matchListAny(getSource(), n.getAttributes().getSource())) good = false; if (good && !matchListAny(getSourceApplication(), n.getAttributes().getSourceApplication())) good = false; if (good && !matchContentAny(n)) good = false; if (good && !matchDatesAny(getCreated(), n.getCreated())) good = false; if (good && !matchDatesAny(getUpdated(), n.getUpdated())) good = false; if (good && n.getAttributes() != null && !matchDatesAny(getSubjectDate(), n.getAttributes().getSubjectDate())) good = false; } else { if (good && !matchTagsAll(n.getTagNames(), getTags())) good = false; if (good && !matchNotebook(n.getNotebookGuid())) good = false; if (good && !matchNotebookStack(n.getNotebookGuid())) good = false; if (good && !matchListAll(getIntitle(), n.getTitle())) good = false; if (good && !matchListAll(getAuthor(), n.getAttributes().getAuthor())) good = false; if (good && !matchListAll(getSource(), n.getAttributes().getSource())) good = false; if (good && !matchListAll(getSourceApplication(), n.getAttributes().getSourceApplication())) good = false; if (good && !matchContentAll(n)) good = false; if (good && !matchDatesAll(getCreated(), n.getCreated())) good = false; if (good && !matchDatesAll(getUpdated(), n.getUpdated())) good = false; if (good && n.getAttributes() != null && !matchDatesAll(getSubjectDate(), n.getAttributes().getSubjectDate())) good = false; } if (good) { guids.add(n); } } // For performance reasons, we didn't get the tags for every note individually. We now need to // get them List<NoteTagsRecord> noteTags = noteTable.noteTagsTable.getAllNoteTags(); for (int i=0; i<guids.size(); i++) { List<String> tags = new ArrayList<String>(); List<String> names = new ArrayList<String>(); for (int j=0; j<noteTags.size(); j++) { if (guids.get(i).getGuid().equals(noteTags.get(j).noteGuid)) { tags.add(noteTags.get(j).tagGuid); names.add(getTagNameByGuid(noteTags.get(j).tagGuid)); } } guids.get(i).setTagGuids(tags); guids.get(i).setTagNames(names); }; logger.log(logger.EXTREME, "Leaving EnSearch.matchWords()"); return guids; }
public List<Note> matchWords() { logger.log(logger.EXTREME, "Inside EnSearch.matchWords()"); boolean subSelect = false; NoteTable noteTable = new NoteTable(logger, conn); List<String> validGuids = new ArrayList<String>(); if (searchWords.size() > 0) subSelect = true; NSqlQuery query = new NSqlQuery(conn.getConnection()); // Build a temp table for GUID results if (!conn.dbTableExists("SEARCH_RESULTS")) { query.exec("create temporary table SEARCH_RESULTS (guid varchar)"); query.exec("create temporary table SEARCH_RESULTS_MERGE (guid varchar)"); } else { query. exec("Delete from SEARCH_RESULTS"); query. exec("Delete from SEARCH_RESULTS_MERGE"); } NSqlQuery insertQuery = new NSqlQuery(conn.getConnection()); NSqlQuery indexQuery = new NSqlQuery(conn.getIndexConnection()); NSqlQuery mergeQuery = new NSqlQuery(conn.getConnection()); NSqlQuery deleteQuery = new NSqlQuery(conn.getConnection()); insertQuery.prepare("Insert into SEARCH_RESULTS (guid) values (:guid)"); mergeQuery.prepare("Insert into SEARCH_RESULTS_MERGE (guid) values (:guid)"); if (subSelect) { for (int i=0; i<getWords().size(); i++) { if (getWords().get(i).indexOf("*") == -1) { indexQuery.prepare("Select distinct guid from words where weight >= " +minimumRecognitionWeight + " and word=:word"); indexQuery.bindValue(":word", getWords().get(i)); } else { indexQuery.prepare("Select distinct guid from words where weight >= " +minimumRecognitionWeight + " and word like :word"); indexQuery.bindValue(":word", getWords().get(i).replace("*", "%")); } indexQuery.exec(); String guid = null; while(indexQuery.next()) { guid = indexQuery.valueString(0); if (i==0 || any) { insertQuery.bindValue(":guid", guid); insertQuery.exec(); } else { mergeQuery.bindValue(":guid", guid); mergeQuery.exec(); } } if (i>0 && !any) { deleteQuery.exec("Delete from SEARCH_RESULTS where guid not in (select guid from SEARCH_RESULTS_MERGE)"); deleteQuery.exec("Delete from SEARCH_RESULTS_MERGE"); } } query.prepare("Select distinct guid from Note where guid in (Select guid from SEARCH_RESULTS)"); if (!query.exec()) logger.log(logger.LOW, "Error merging search results:" + query.lastError()); while (query.next()) { validGuids.add(query.valueString(0)); } } List<Note> noteIndex = noteTable.getAllNotes(); List<Note> guids = new ArrayList<Note>(); for (int i=0; i<noteIndex.size(); i++) { Note n = noteIndex.get(i); boolean good = true; if (!validGuids.contains(n.getGuid()) && subSelect) good = false; // Start matching special stuff, like tags & notebooks if (any) { if (good && !matchTagsAny(n.getTagNames(), getTags())) good = false; if (good && !matchNotebook(n.getNotebookGuid())) good = false; if (good && !matchNotebookStack(n.getNotebookGuid())) good = false; if (good && !matchListAny(getIntitle(), n.getTitle())) good = false; if (good && !matchListAny(getAuthor(), n.getAttributes().getAuthor())) good = false; if (good && !matchListAny(getSource(), n.getAttributes().getSource())) good = false; if (good && !matchListAny(getSourceApplication(), n.getAttributes().getSourceApplication())) good = false; if (good && !matchContentAny(n)) good = false; if (good && !matchDatesAny(getCreated(), n.getCreated())) good = false; if (good && !matchDatesAny(getUpdated(), n.getUpdated())) good = false; if (good && n.getAttributes() != null && !matchDatesAny(getSubjectDate(), n.getAttributes().getSubjectDate())) good = false; } else { if (good && !matchTagsAll(n.getTagNames(), getTags())) good = false; if (good && !matchNotebook(n.getNotebookGuid())) good = false; if (good && !matchNotebookStack(n.getNotebookGuid())) good = false; if (good && !matchListAll(getIntitle(), n.getTitle())) good = false; if (good && !matchListAll(getAuthor(), n.getAttributes().getAuthor())) good = false; if (good && !matchListAll(getSource(), n.getAttributes().getSource())) good = false; if (good && !matchListAll(getSourceApplication(), n.getAttributes().getSourceApplication())) good = false; if (good && !matchContentAll(n)) good = false; if (good && !matchDatesAll(getCreated(), n.getCreated())) good = false; if (good && !matchDatesAll(getUpdated(), n.getUpdated())) good = false; if (good && n.getAttributes() != null && !matchDatesAll(getSubjectDate(), n.getAttributes().getSubjectDate())) good = false; } if (good) { guids.add(n); } } // For performance reasons, we didn't get the tags for every note individually. We now need to // get them List<NoteTagsRecord> noteTags = noteTable.noteTagsTable.getAllNoteTags(); for (int i=0; i<guids.size(); i++) { List<String> tags = new ArrayList<String>(); List<String> names = new ArrayList<String>(); for (int j=0; j<noteTags.size(); j++) { if (guids.get(i).getGuid().equals(noteTags.get(j).noteGuid)) { tags.add(noteTags.get(j).tagGuid); names.add(getTagNameByGuid(noteTags.get(j).tagGuid)); } } guids.get(i).setTagGuids(tags); guids.get(i).setTagNames(names); }; logger.log(logger.EXTREME, "Leaving EnSearch.matchWords()"); return guids; }
diff --git a/plugins/hdfsviewer/src/azkaban/viewer/hdfs/HdfsBrowserServlet.java b/plugins/hdfsviewer/src/azkaban/viewer/hdfs/HdfsBrowserServlet.java index c46b8be..7eff61a 100644 --- a/plugins/hdfsviewer/src/azkaban/viewer/hdfs/HdfsBrowserServlet.java +++ b/plugins/hdfsviewer/src/azkaban/viewer/hdfs/HdfsBrowserServlet.java @@ -1,537 +1,537 @@ /* * Copyright 2012 LinkedIn Corp. * * 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 azkaban.viewer.hdfs; import java.io.IOException; import java.io.ByteArrayOutputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.security.AccessControlException; import org.apache.log4j.Logger; import azkaban.security.commons.HadoopSecurityManager; import azkaban.security.commons.HadoopSecurityManagerException; import azkaban.user.User; import azkaban.utils.Props; import azkaban.webapp.servlet.LoginAbstractAzkabanServlet; import azkaban.webapp.servlet.Page; import azkaban.webapp.session.Session; public class HdfsBrowserServlet extends LoginAbstractAzkabanServlet { private static final long serialVersionUID = 1L; private static final String PROXY_USER_SESSION_KEY = "hdfs.browser.proxy.user"; private static final String HADOOP_SECURITY_MANAGER_CLASS_PARAM = "hadoop.security.manager.class"; public static final int DEFAULT_START_LINE = 1; public static final int DEFAULT_END_LINE = 100; public static final int FILE_MAX_LINES = 100; private static Logger logger = Logger.getLogger(HdfsBrowserServlet.class); private ArrayList<HdfsFileViewer> viewers = new ArrayList<HdfsFileViewer>(); private HdfsFileViewer defaultViewer; private Props props; private boolean shouldProxy; private boolean allowGroupProxy; private String viewerName; private String viewerPath; private HadoopSecurityManager hadoopSecurityManager; public HdfsBrowserServlet(Props props) { this.props = props; viewerName = props.getString("viewer.name"); viewerPath = props.getString("viewer.path"); } @Override public void init(ServletConfig config) throws ServletException { super.init(config); shouldProxy = props.getBoolean("azkaban.should.proxy", false); allowGroupProxy = props.getBoolean("allow.group.proxy", false); logger.info("Hdfs browser should proxy: " + shouldProxy); props.put("fs.hdfs.impl.disable.cache", "true"); try { hadoopSecurityManager = loadHadoopSecurityManager(props, logger); } catch (RuntimeException e) { e.printStackTrace(); throw new RuntimeException("Failed to get hadoop security manager!" + e.getCause()); } defaultViewer = new TextFileViewer(); viewers.add(new AvroFileViewer()); viewers.add(new ParquetFileViewer()); viewers.add(new JsonSequenceFileViewer()); viewers.add(new ImageFileViewer()); viewers.add(new BsonFileViewer()); viewers.add(defaultViewer); logger.info("HDFS Browser initiated"); } private HadoopSecurityManager loadHadoopSecurityManager( Props props, Logger logger) throws RuntimeException { Class<?> hadoopSecurityManagerClass = props.getClass( HADOOP_SECURITY_MANAGER_CLASS_PARAM, true, HdfsBrowserServlet.class.getClassLoader()); logger.info("Initializing hadoop security manager " + hadoopSecurityManagerClass.getName()); HadoopSecurityManager hadoopSecurityManager = null; try { Method getInstanceMethod = hadoopSecurityManagerClass.getMethod("getInstance", Props.class); hadoopSecurityManager = (HadoopSecurityManager) getInstanceMethod.invoke( hadoopSecurityManagerClass, props); } catch (InvocationTargetException e) { logger.error("Could not instantiate Hadoop Security Manager " + hadoopSecurityManagerClass.getName() + e.getCause()); throw new RuntimeException(e.getCause()); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getCause()); } return hadoopSecurityManager; } private FileSystem getFileSystem(String username) throws HadoopSecurityManagerException { return hadoopSecurityManager.getFSAsUser(username); } @Override protected void handleGet( HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { User user = session.getUser(); String username = user.getUserId(); if (hasParam(req, "action") && getParam(req, "action").equals("goHomeDir")) { username = getParam(req, "proxyname"); } else if (allowGroupProxy) { String proxyName = (String)session.getSessionData(PROXY_USER_SESSION_KEY); if (proxyName != null) { username = proxyName; } } FileSystem fs = null; try { fs = getFileSystem(username); try { if (hasParam(req, "ajax")) { handleAjaxAction(fs, username, req, resp, session); } else { handleFsDisplay(fs, username, req, resp, session); } } catch (IOException e) { throw e; } catch (ServletException se) { throw se; } catch (Exception ge) { throw ge; } finally { if(fs != null) { fs.close(); } } } catch (Exception e) { //e.printStackTrace(); Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-browser.vm"); page.add("error_message", "Error: " + e.getMessage()); page.add("user", username); page.add("allowproxy", allowGroupProxy); page.add("no_fs", "true"); page.add("viewerName", viewerName); page.render(); } finally { if (fs != null) { fs.close(); } } } @Override protected void handlePost( HttpServletRequest req, HttpServletResponse resp, Session session) throws ServletException, IOException { User user = session.getUser(); if (!hasParam(req, "action")) { return; } HashMap<String,String> results = new HashMap<String,String>(); String action = getParam(req, "action"); if (action.equals("changeProxyUser")) { if (hasParam(req, "proxyname")) { String newProxyname = getParam(req, "proxyname"); if (user.getUserId().equals(newProxyname) || user.isInGroup(newProxyname) || user.getRoles().contains("admin")) { session.setSessionData(PROXY_USER_SESSION_KEY, newProxyname); } else { results.put("error", "User '" + user.getUserId() + "' cannot proxy as '" + newProxyname + "'"); } } } else { results.put("error", "action param is not set"); } this.writeJSON(resp, results); } private void handleFsDisplay( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session) throws IOException, ServletException, IllegalArgumentException, IllegalStateException { String prefix = req.getContextPath() + req.getServletPath(); String fsPath = req.getRequestURI().substring(prefix.length()); Path path; if (fsPath.length() == 0) { fsPath = "/"; } path = new Path(fsPath); if (logger.isDebugEnabled()) logger.debug("path=" + path.toString()); if (!fs.exists(path)) { throw new IllegalArgumentException(path.toUri().getPath() + " does not exist."); } else if (fs.isFile(path)) { displayFilePage(fs, user, req, resp, session, path); } else if (fs.getFileStatus(path).isDir()) { displayDirPage(fs, user, req, resp, session, path); } else { throw new IllegalStateException( "It exists, it is not a file, and it is not a directory, what is it precious?"); } } private void displayDirPage( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-browser.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); Path curr = path; while (curr.getParent() != null) { paths.add(curr); segments.add(curr.getName()); curr = curr.getParent(); } Collections.reverse(paths); Collections.reverse(segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); String homeDirString = fs.getHomeDirectory().toString(); if (homeDirString.startsWith("file:")) { page.add("homedir", homeDirString.substring("file:".length())); } else { page.add("homedir", homeDirString.substring(fs.getUri().toString().length())); } try { FileStatus[] subdirs = fs.listStatus(path); page.add("subdirs", subdirs); long size = 0; for (int i = 0; i < subdirs.length; ++i) { if (subdirs[i].isDir()) { continue; } size += subdirs[i].getLen(); } page.add("dirsize", size); } catch (AccessControlException e) { page.add("error_message", "Permission denied. User cannot read file or directory"); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); } private void displayFilePage( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-file.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); Path curr = path; while (curr.getParent() != null) { paths.add(curr); segments.add(curr.getName()); curr = curr.getParent(); } Collections.reverse(paths); Collections.reverse(segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); - page.add("path", path.toString()); + page.add("path", path.toString()); String homeDirString = fs.getHomeDirectory().toString(); if (homeDirString.startsWith("file:")) { page.add("homedir", homeDirString.substring("file:".length())); } else { page.add("homedir", homeDirString.substring(fs.getUri().toString().length())); } boolean hasSchema = false; int viewerId = -1; for (int i = 0; i < viewers.size(); ++i) { HdfsFileViewer viewer = viewers.get(i); Set<Capability> capabilities = viewer.getCapabilities(fs, path); if (capabilities.contains(Capability.READ)) { if (capabilities.contains(Capability.SCHEMA)) { hasSchema = true; } viewerId = i; break; } } page.add("viewerId", viewerId); page.add("hasSchema", hasSchema); try { FileStatus status = fs.getFileStatus(path); page.add("status", status); } catch (AccessControlException e) { page.add("error_message", "Permission denied. User cannot read this file."); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); } private void handleAjaxAction( FileSystem fs, String username, HttpServletRequest request, HttpServletResponse response, Session session) throws ServletException, IOException { Map<String, Object> ret = new HashMap<String, Object>(); String ajaxName = getParam(request, "ajax"); Path path = null; if (!hasParam(request, "path")) { ret.put("error", "Missing parameter 'path'."); this.writeJSON(response, ret); return; } path = new Path(getParam(request, "path")); if (!fs.exists(path)) { ret.put("error", path.toUri().getPath() + " does not exist."); this.writeJSON(response, ret); return; } if (ajaxName.equals("fetchschema")) { handleAjaxFetchSchema(fs, request, ret, session, path); } else if (ajaxName.equals("fetchfile")) { handleAjaxFetchFile(fs, request, ret, session, path); } else { ret.put("error", "Unknown AJAX action " + ajaxName); } if (ret != null) { this.writeJSON(response, ret); } } private void handleAjaxFetchSchema( FileSystem fs, HttpServletRequest req, Map<String, Object> ret, Session session, Path path) throws IOException, ServletException { HdfsFileViewer fileViewer = null; if (hasParam(req, "viewerId")) { fileViewer = viewers.get(getIntParam(req, "viewerId")); if (!fileViewer.getCapabilities(fs, path).contains(Capability.SCHEMA)) { fileViewer = null; } } else { for (HdfsFileViewer viewer : viewers) { if (viewer.getCapabilities(fs, path).contains(Capability.SCHEMA)) { fileViewer = viewer; } } } if (fileViewer == null) { ret.put("error", "No viewers can display schema."); return; } ret.put("schema", fileViewer.getSchema(fs, path)); } private void handleAjaxFetchFile( FileSystem fs, HttpServletRequest req, Map<String, Object> ret, Session session, Path path) throws IOException, ServletException { int startLine = getIntParam(req, "startLine", DEFAULT_START_LINE); int endLine = getIntParam(req, "endLine", DEFAULT_END_LINE); if (endLine < startLine) { ret.put("error", "Invalid range: endLine < startLine."); return; } if (endLine - startLine > FILE_MAX_LINES) { ret.put("error", "Invalid range: range exceeds max number of lines."); return; } // use registered viewers to show the file content boolean outputed = false; ByteArrayOutputStream output = new ByteArrayOutputStream(); if (hasParam(req, "viewerId")) { HdfsFileViewer viewer = viewers.get(getIntParam(req, "viewerId")); if (viewer.getCapabilities(fs, path).contains(Capability.READ)) { viewer.displayFile(fs, path, output, startLine, endLine); outputed = true; } } for (HdfsFileViewer viewer : viewers) { if (viewer.getCapabilities(fs, path).contains(Capability.READ)) { viewer.displayFile(fs, path, output, startLine, endLine); outputed = true; break; // don't need to try other viewers } } // use default text viewer if (!outputed) { if (defaultViewer.getCapabilities(fs, path).contains(Capability.READ)) { defaultViewer.displayFile(fs, path, output, startLine, endLine); } else { ret.put("error", "Cannot retrieve file."); return; } } ret.put("chunk", output.toString()); } }
true
true
private void displayFilePage( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-file.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); Path curr = path; while (curr.getParent() != null) { paths.add(curr); segments.add(curr.getName()); curr = curr.getParent(); } Collections.reverse(paths); Collections.reverse(segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); page.add("path", path.toString()); String homeDirString = fs.getHomeDirectory().toString(); if (homeDirString.startsWith("file:")) { page.add("homedir", homeDirString.substring("file:".length())); } else { page.add("homedir", homeDirString.substring(fs.getUri().toString().length())); } boolean hasSchema = false; int viewerId = -1; for (int i = 0; i < viewers.size(); ++i) { HdfsFileViewer viewer = viewers.get(i); Set<Capability> capabilities = viewer.getCapabilities(fs, path); if (capabilities.contains(Capability.READ)) { if (capabilities.contains(Capability.SCHEMA)) { hasSchema = true; } viewerId = i; break; } } page.add("viewerId", viewerId); page.add("hasSchema", hasSchema); try { FileStatus status = fs.getFileStatus(path); page.add("status", status); } catch (AccessControlException e) { page.add("error_message", "Permission denied. User cannot read this file."); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); }
private void displayFilePage( FileSystem fs, String user, HttpServletRequest req, HttpServletResponse resp, Session session, Path path) throws IOException { Page page = newPage(req, resp, session, "azkaban/viewer/hdfs/velocity/hdfs-file.vm"); page.add("allowproxy", allowGroupProxy); page.add("viewerPath", viewerPath); page.add("viewerName", viewerName); List<Path> paths = new ArrayList<Path>(); List<String> segments = new ArrayList<String>(); Path curr = path; while (curr.getParent() != null) { paths.add(curr); segments.add(curr.getName()); curr = curr.getParent(); } Collections.reverse(paths); Collections.reverse(segments); page.add("paths", paths); page.add("segments", segments); page.add("user", user); page.add("path", path.toString()); String homeDirString = fs.getHomeDirectory().toString(); if (homeDirString.startsWith("file:")) { page.add("homedir", homeDirString.substring("file:".length())); } else { page.add("homedir", homeDirString.substring(fs.getUri().toString().length())); } boolean hasSchema = false; int viewerId = -1; for (int i = 0; i < viewers.size(); ++i) { HdfsFileViewer viewer = viewers.get(i); Set<Capability> capabilities = viewer.getCapabilities(fs, path); if (capabilities.contains(Capability.READ)) { if (capabilities.contains(Capability.SCHEMA)) { hasSchema = true; } viewerId = i; break; } } page.add("viewerId", viewerId); page.add("hasSchema", hasSchema); try { FileStatus status = fs.getFileStatus(path); page.add("status", status); } catch (AccessControlException e) { page.add("error_message", "Permission denied. User cannot read this file."); } catch (IOException e) { page.add("error_message", "Error: " + e.getMessage()); } page.render(); }
diff --git a/handin2/Assignment1/src/letter/LetterCountMapper.java b/handin2/Assignment1/src/letter/LetterCountMapper.java index 00413bf..46c000f 100644 --- a/handin2/Assignment1/src/letter/LetterCountMapper.java +++ b/handin2/Assignment1/src/letter/LetterCountMapper.java @@ -1,31 +1,31 @@ package letter; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileSplit; import org.apache.hadoop.mapred.MapReduceBase; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.JobConf; public class LetterCountMapper extends MapReduceBase implements Mapper<LongWritable, Text, Text, Text> { public LetterCountMapper() { } public void map(LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { //Split string into array of chars. Remove all characters that are not in [a-z^A-Z] - char[] letterArray = value.toString().replaceAll("[^a-z^A-Z]","").toCharArray(); + char[] letterArray = value.toString().toLowerCase().replaceAll("[^a-z]","").toCharArray(); //For each letter send it to the reducer for(int i=0; i<letterArray.length; i++){ output.collect( new Text(String.valueOf(letterArray[i])), new Text("1")); } } }
true
true
public void map(LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { //Split string into array of chars. Remove all characters that are not in [a-z^A-Z] char[] letterArray = value.toString().replaceAll("[^a-z^A-Z]","").toCharArray(); //For each letter send it to the reducer for(int i=0; i<letterArray.length; i++){ output.collect( new Text(String.valueOf(letterArray[i])), new Text("1")); } }
public void map(LongWritable key, Text value, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { //Split string into array of chars. Remove all characters that are not in [a-z^A-Z] char[] letterArray = value.toString().toLowerCase().replaceAll("[^a-z]","").toCharArray(); //For each letter send it to the reducer for(int i=0; i<letterArray.length; i++){ output.collect( new Text(String.valueOf(letterArray[i])), new Text("1")); } }
diff --git a/src/com/twobuntu/service/UpdateService.java b/src/com/twobuntu/service/UpdateService.java index 3e61678..4845dbf 100644 --- a/src/com/twobuntu/service/UpdateService.java +++ b/src/com/twobuntu/service/UpdateService.java @@ -1,124 +1,124 @@ package com.twobuntu.service; import java.net.URL; import java.util.ArrayList; import org.apache.commons.io.IOUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.AlarmManager; import android.app.IntentService; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import com.twobuntu.db.ArticleHelper; import com.twobuntu.db.ArticleProvider; import com.twobuntu.db.Articles; import com.twobuntu.twobuntu.R; // Periodically updates the internal database to reflect the current articles on the site. public class UpdateService extends IntentService { private static final long UPDATE_INTERVAL = AlarmManager.INTERVAL_HALF_HOUR; private static final String LAST_UPDATE = "last_update"; private static final String DOMAIN_NAME = "2buntu.com"; // The database we are updating. private ArticleHelper mDatabase; // Access to shared preferences. private SharedPreferences mPreferences; // TODO: have the notification launch the appropriate intent // Adds a notification indicating that a new article was added. @SuppressWarnings("deprecation") private void displayNotification(JSONObject article) throws JSONException { Notification notification = new Notification.Builder(this) .setContentTitle(getResources().getString(R.string.app_name)) .setContentText(article.getString("title")) .setSmallIcon(R.drawable.ic_stat_article).getNotification(); ((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).notify(article.getInt("id"), notification); } // TODO: there is a logic error with the code below. If more than twenty // articles are modified, some will miss getting updated because we set the // date of the last update to the current date and not the most recent date // obtained in one of the articles. This should eventually be fixed. // Processes the JSON received from the API. private void processArticles(long max, JSONObject response) throws JSONException { JSONArray articles = response.getJSONArray("articles"); ArrayList<ContentValues> articlesForInsertion = new ArrayList<ContentValues>(); for(int i=0; i<articles.length(); ++i) { // Determine if the article exists in the database already. JSONObject article = articles.getJSONObject(i); Cursor cursor = mDatabase.getReadableDatabase().query(Articles.TABLE_NAME, new String[] { Articles.COLUMN_ID }, Articles.COLUMN_ID + " = " + article.getInt("id"), null, null, null, null); // If the article does NOT exist, add it and display a notification. if(cursor.getCount() == 0) { articlesForInsertion.add(Articles.convertToContentValues(article)); displayNotification(article); } // Otherwise, update the existing article in-place. else { - Uri uri = Uri.withAppendedPath(ArticleProvider.CONTENT_LOOKUP_URI, article.getInt("id")); + Uri uri = Uri.withAppendedPath(ArticleProvider.CONTENT_LOOKUP_URI, String.valueOf(article.getInt("id"))); getContentResolver().update(uri, Articles.convertToContentValues(article), null, null); } } // If any articles are queued for insertion, then insert them. if(articlesForInsertion.size() != 0) getContentResolver().bulkInsert(ArticleProvider.CONTENT_URI, articlesForInsertion.toArray(new ContentValues[articlesForInsertion.size()])); // Store the time of last update for the next poll. mPreferences.edit().putLong(LAST_UPDATE, max).commit(); } // Process a single intent, which is simply a request to update the database. @Override protected void onHandleIntent(Intent intent) { Log.i("UpdateService", "Performing scheduled update."); // Calculate the appropriate min / max parameters. long min = mPreferences.getLong(LAST_UPDATE, 0) + 1; long max = System.currentTimeMillis() / 1000; try { // Read the raw JSON data from the server and parse it. String json = IOUtils.toString(new URL("http://" + DOMAIN_NAME + "/api/articles?min=" + min + "&max=" + max + "&sort=newest").openStream(), "utf-8"); processArticles(max, new JSONObject(json)); } catch (Exception e) { Log.e("UpdateService", "Error description: " + e.toString()); } finally { // Schedule the next update. Log.i("UpdateService", "Scheduling next update."); Intent updateIntent = new Intent(this, UpdateService.class); ((AlarmManager)getSystemService(Context.ALARM_SERVICE)).set(AlarmManager.RTC, UPDATE_INTERVAL, PendingIntent.getBroadcast(this, 0, updateIntent, 0)); } } public UpdateService() { super("UpdateService"); } // Initialize the article database and shared preferences. @Override public void onCreate() { super.onCreate(); mDatabase = new ArticleHelper(this); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); } }
true
true
private void processArticles(long max, JSONObject response) throws JSONException { JSONArray articles = response.getJSONArray("articles"); ArrayList<ContentValues> articlesForInsertion = new ArrayList<ContentValues>(); for(int i=0; i<articles.length(); ++i) { // Determine if the article exists in the database already. JSONObject article = articles.getJSONObject(i); Cursor cursor = mDatabase.getReadableDatabase().query(Articles.TABLE_NAME, new String[] { Articles.COLUMN_ID }, Articles.COLUMN_ID + " = " + article.getInt("id"), null, null, null, null); // If the article does NOT exist, add it and display a notification. if(cursor.getCount() == 0) { articlesForInsertion.add(Articles.convertToContentValues(article)); displayNotification(article); } // Otherwise, update the existing article in-place. else { Uri uri = Uri.withAppendedPath(ArticleProvider.CONTENT_LOOKUP_URI, article.getInt("id")); getContentResolver().update(uri, Articles.convertToContentValues(article), null, null); } } // If any articles are queued for insertion, then insert them. if(articlesForInsertion.size() != 0) getContentResolver().bulkInsert(ArticleProvider.CONTENT_URI, articlesForInsertion.toArray(new ContentValues[articlesForInsertion.size()])); // Store the time of last update for the next poll. mPreferences.edit().putLong(LAST_UPDATE, max).commit(); }
private void processArticles(long max, JSONObject response) throws JSONException { JSONArray articles = response.getJSONArray("articles"); ArrayList<ContentValues> articlesForInsertion = new ArrayList<ContentValues>(); for(int i=0; i<articles.length(); ++i) { // Determine if the article exists in the database already. JSONObject article = articles.getJSONObject(i); Cursor cursor = mDatabase.getReadableDatabase().query(Articles.TABLE_NAME, new String[] { Articles.COLUMN_ID }, Articles.COLUMN_ID + " = " + article.getInt("id"), null, null, null, null); // If the article does NOT exist, add it and display a notification. if(cursor.getCount() == 0) { articlesForInsertion.add(Articles.convertToContentValues(article)); displayNotification(article); } // Otherwise, update the existing article in-place. else { Uri uri = Uri.withAppendedPath(ArticleProvider.CONTENT_LOOKUP_URI, String.valueOf(article.getInt("id"))); getContentResolver().update(uri, Articles.convertToContentValues(article), null, null); } } // If any articles are queued for insertion, then insert them. if(articlesForInsertion.size() != 0) getContentResolver().bulkInsert(ArticleProvider.CONTENT_URI, articlesForInsertion.toArray(new ContentValues[articlesForInsertion.size()])); // Store the time of last update for the next poll. mPreferences.edit().putLong(LAST_UPDATE, max).commit(); }
diff --git a/src/main/java/skype/SkypeBridge.java b/src/main/java/skype/SkypeBridge.java index 1407efa..7c25b70 100644 --- a/src/main/java/skype/SkypeBridge.java +++ b/src/main/java/skype/SkypeBridge.java @@ -1,96 +1,98 @@ package skype; import java.util.Calendar; import java.util.List; import java.util.Random; import sliceWars.remote.Broadcaster; import sliceWars.remote.LocalGame; import sliceWars.remote.messages.AllPlayersInvitesResult; import sliceWars.remote.messages.AnswerToTheInvitation; import sliceWars.remote.messages.Invitation; import sliceWars.remote.messages.RemotePlay; import com.skype.ApplicationListener; import com.skype.SkypeException; import com.skype.Stream; import com.skype.StreamAdapter; import com.thoughtworks.xstream.XStream; public class SkypeBridge implements ApplicationListener { private LocalGame localGame; private boolean server = false; private List<String> _invitedNames; private int randomSeed; private int lines = 6; private int columns = 6; private int randomScenariosCellsCount = 12; public SkypeBridge(final String id) { localGame = new LocalGame(new Broadcaster(), id ); Random random = new Random(Calendar.getInstance().getTimeInMillis()); randomSeed = random.nextInt(); } @Override public void connected(Stream stream) throws SkypeException { + System.out.println("Connected to "+stream.getId()); localGame.addRemotePlayer(new SkypePlayer(stream)); if(isClient()){ SkypeServerGame game = new SkypeServerGame(stream); localGame.setServerGame(game); } if(isServer()){ - String idStartingOnOne = stream.getId()+1; - String firstPlayerIsServer = idStartingOnOne + 1; + int invitedIndexOnIntedList = _invitedNames.indexOf(stream.getId()); + int idStartingOnOne = invitedIndexOnIntedList+1; + int firstPlayerIsServer = idStartingOnOne + 1; localGame.setGameSettings(_invitedNames.size()+1,randomSeed,randomScenariosCellsCount,lines,columns); - Invitation invitation = new Invitation(randomSeed, _invitedNames, _invitedNames.indexOf(firstPlayerIsServer), lines, columns, randomScenariosCellsCount); + Invitation invitation = new Invitation(randomSeed, _invitedNames, firstPlayerIsServer, lines, columns, randomScenariosCellsCount); SkypeApp.sendMessageThroughStream(invitation, stream); } stream.addStreamListener(new StreamAdapter() { @Override public void textReceived(String receivedText) throws SkypeException { XStream xstream = new XStream(); Object received = xstream.fromXML(receivedText); if(received instanceof Invitation){ localGame.invite((Invitation) received); } if(received instanceof AllPlayersInvitesResult){ localGame.allPlayersInvitesResult((AllPlayersInvitesResult) received); } if(received instanceof AnswerToTheInvitation){ localGame.answerToTheInvitation((AnswerToTheInvitation) received); } if(received instanceof RemotePlay){ localGame.play((RemotePlay) received); } } }); } private boolean isClient() { return !server; } private boolean isServer() { return server; } @Override public void disconnected(Stream stream) throws SkypeException { SkypeApp.showDisconnectedMessageAndExit(stream); } public void setServer() { server = true; } public void setInvited(List<String> invitedNames) { _invitedNames = invitedNames; } }
false
true
public void connected(Stream stream) throws SkypeException { localGame.addRemotePlayer(new SkypePlayer(stream)); if(isClient()){ SkypeServerGame game = new SkypeServerGame(stream); localGame.setServerGame(game); } if(isServer()){ String idStartingOnOne = stream.getId()+1; String firstPlayerIsServer = idStartingOnOne + 1; localGame.setGameSettings(_invitedNames.size()+1,randomSeed,randomScenariosCellsCount,lines,columns); Invitation invitation = new Invitation(randomSeed, _invitedNames, _invitedNames.indexOf(firstPlayerIsServer), lines, columns, randomScenariosCellsCount); SkypeApp.sendMessageThroughStream(invitation, stream); } stream.addStreamListener(new StreamAdapter() { @Override public void textReceived(String receivedText) throws SkypeException { XStream xstream = new XStream(); Object received = xstream.fromXML(receivedText); if(received instanceof Invitation){ localGame.invite((Invitation) received); } if(received instanceof AllPlayersInvitesResult){ localGame.allPlayersInvitesResult((AllPlayersInvitesResult) received); } if(received instanceof AnswerToTheInvitation){ localGame.answerToTheInvitation((AnswerToTheInvitation) received); } if(received instanceof RemotePlay){ localGame.play((RemotePlay) received); } } }); }
public void connected(Stream stream) throws SkypeException { System.out.println("Connected to "+stream.getId()); localGame.addRemotePlayer(new SkypePlayer(stream)); if(isClient()){ SkypeServerGame game = new SkypeServerGame(stream); localGame.setServerGame(game); } if(isServer()){ int invitedIndexOnIntedList = _invitedNames.indexOf(stream.getId()); int idStartingOnOne = invitedIndexOnIntedList+1; int firstPlayerIsServer = idStartingOnOne + 1; localGame.setGameSettings(_invitedNames.size()+1,randomSeed,randomScenariosCellsCount,lines,columns); Invitation invitation = new Invitation(randomSeed, _invitedNames, firstPlayerIsServer, lines, columns, randomScenariosCellsCount); SkypeApp.sendMessageThroughStream(invitation, stream); } stream.addStreamListener(new StreamAdapter() { @Override public void textReceived(String receivedText) throws SkypeException { XStream xstream = new XStream(); Object received = xstream.fromXML(receivedText); if(received instanceof Invitation){ localGame.invite((Invitation) received); } if(received instanceof AllPlayersInvitesResult){ localGame.allPlayersInvitesResult((AllPlayersInvitesResult) received); } if(received instanceof AnswerToTheInvitation){ localGame.answerToTheInvitation((AnswerToTheInvitation) received); } if(received instanceof RemotePlay){ localGame.play((RemotePlay) received); } } }); }
diff --git a/src/at/epu/DataAccessLayer/DataModels/MockModels/MockBankAccountDataModel.java b/src/at/epu/DataAccessLayer/DataModels/MockModels/MockBankAccountDataModel.java index a0bc665..2c74661 100644 --- a/src/at/epu/DataAccessLayer/DataModels/MockModels/MockBankAccountDataModel.java +++ b/src/at/epu/DataAccessLayer/DataModels/MockModels/MockBankAccountDataModel.java @@ -1,23 +1,23 @@ package at.epu.DataAccessLayer.DataModels.MockModels; import java.text.SimpleDateFormat; import java.util.Date; import at.epu.DataAccessLayer.DataModels.BankAccountDataModel; /* * ID(PK) | Buchungstext | * | Betrag | Umsatzsteuer | Buchungsdatum | Kategorie(FK) */ public class MockBankAccountDataModel extends BankAccountDataModel { private static final long serialVersionUID = -1513528315959701530L; public MockBankAccountDataModel() { Object [][] data_ = { - {new Integer(1), "Ausgangsrechnung ID 1", new Double(34000.00+100050.00),new Double(26810.00), + {new Integer(1), "Eingangsrechnung ID null", "Ausgangsrechnung ID 1", new Double(34000.00+100050.00),new Double(26810.00), new SimpleDateFormat("dd.MM.yyyy").format(new Date()), "Einnahme"}, - {new Integer(2), "Ausgangsrechnung ID 2", new Double(1252.00+1003.00),new Double(45100.00), + {new Integer(2), "Eingangsrechnung ID null", "Ausgangsrechnung ID 2", new Double(1252.00+1003.00),new Double(45100.00), new SimpleDateFormat("dd.MM.yyyy").format(new Date()), "Einnahme"} }; data = data_; } }
false
true
public MockBankAccountDataModel() { Object [][] data_ = { {new Integer(1), "Ausgangsrechnung ID 1", new Double(34000.00+100050.00),new Double(26810.00), new SimpleDateFormat("dd.MM.yyyy").format(new Date()), "Einnahme"}, {new Integer(2), "Ausgangsrechnung ID 2", new Double(1252.00+1003.00),new Double(45100.00), new SimpleDateFormat("dd.MM.yyyy").format(new Date()), "Einnahme"} }; data = data_; }
public MockBankAccountDataModel() { Object [][] data_ = { {new Integer(1), "Eingangsrechnung ID null", "Ausgangsrechnung ID 1", new Double(34000.00+100050.00),new Double(26810.00), new SimpleDateFormat("dd.MM.yyyy").format(new Date()), "Einnahme"}, {new Integer(2), "Eingangsrechnung ID null", "Ausgangsrechnung ID 2", new Double(1252.00+1003.00),new Double(45100.00), new SimpleDateFormat("dd.MM.yyyy").format(new Date()), "Einnahme"} }; data = data_; }
diff --git a/src/org/omegat/gui/editor/EditorTextArea3.java b/src/org/omegat/gui/editor/EditorTextArea3.java index 861cce3b..63a0a28a 100644 --- a/src/org/omegat/gui/editor/EditorTextArea3.java +++ b/src/org/omegat/gui/editor/EditorTextArea3.java @@ -1,520 +1,522 @@ /************************************************************************** OmegaT - Computer Assisted Translation (CAT) tool with fuzzy matching, translation memory, keyword search, glossaries, and translation leveraging into updated projects. Copyright (C) 2009 Alex Buloichik 2009 Didier Briel Home page: http://www.omegat.org/ Support center: http://groups.yahoo.com/group/OmegaT/ 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **************************************************************************/ package org.omegat.gui.editor; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.List; import javax.swing.JEditorPane; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JSeparator; import javax.swing.text.AbstractDocument; import javax.swing.text.BadLocationException; import javax.swing.text.BoxView; import javax.swing.text.ComponentView; import javax.swing.text.Element; import javax.swing.text.IconView; import javax.swing.text.ParagraphView; import javax.swing.text.StyleConstants; import javax.swing.text.StyledEditorKit; import javax.swing.text.Utilities; import javax.swing.text.View; import javax.swing.text.ViewFactory; import javax.swing.undo.UndoManager; import org.omegat.core.Core; import org.omegat.util.Log; import org.omegat.util.OConsts; import org.omegat.util.OStrings; import org.omegat.util.StaticUtils; import org.omegat.util.gui.UIThreadsUtil; /** * Changes of standard JEditorPane implementation for support custom behavior. * * @author Alex Buloichik ([email protected]) * @author Didier Briel */ public class EditorTextArea3 extends JEditorPane { /** Undo Manager to store edits */ protected final UndoManager undoManager = new UndoManager(); protected final EditorController controller; public EditorTextArea3(EditorController controller) { this.controller = controller; setEditorKit(new StyledEditorKit() { public ViewFactory getViewFactory() { return factory3; } }); addMouseListener(mouseListener); } /** Orders to cancel all Undoable edits. */ public void cancelUndo() { undoManager.die(); } /** * Return OmDocument instead just a Document. If editor was not initialized * with OmDocument, it will contains other Document implementation. In this * case we don't need it. */ public Document3 getOmDocument() { try { return (Document3) getDocument(); } catch (ClassCastException ex) { return null; } } protected MouseListener mouseListener = new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) { controller.goToSegmentAtLocation(getCaretPosition()); } if (e.isPopupTrigger() || e.getButton() == MouseEvent.BUTTON3) { // any spell checking to be done? if (createSpellCheckerPopUp(e.getPoint())) return; // fall back to go to segment if (createGoToSegmentPopUp(e.getPoint())) return; } } }; /** * Redefine some keys behavior. We can't use key listeners, because we have * to make something AFTER standard keys processing. */ @Override protected void processKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { // key released super.processKeyEvent(e); return; } boolean processed = false; boolean mac = StaticUtils.onMacOSX(); Document3 doc = getOmDocument(); // non-standard processing if (isKey(e, KeyEvent.VK_TAB, 0)) { // press TAB when 'Use TAB to advance' if (controller.settings.isUseTabForAdvance()) { controller.nextEntry(); processed = true; } } else if (isKey(e, KeyEvent.VK_TAB, KeyEvent.SHIFT_MASK)) { // press Shift+TAB when 'Use TAB to advance' if (controller.settings.isUseTabForAdvance()) { controller.prevEntry(); processed = true; } } else if (isKey(e, KeyEvent.VK_ENTER, 0)) { // press ENTER if (!controller.settings.isUseTabForAdvance()) { controller.nextEntry(); processed = true; + } else { + processed = true; } } else if ((!mac && isKey(e, KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_ENTER, KeyEvent.META_MASK))) { // press Ctrl+ENTER (Cmd+Enter for MacOS) if (!controller.settings.isUseTabForAdvance()) { controller.prevEntry(); processed = true; } } else if (isKey(e, KeyEvent.VK_ENTER, KeyEvent.SHIFT_MASK)) { // convert Shift+Enter event to straight enter key KeyEvent ke = new KeyEvent(e.getComponent(), e.getID(), e.getWhen(), 0, KeyEvent.VK_ENTER, '\n'); super.processKeyEvent(ke); processed = true; } else if ((!mac && isKey(e, KeyEvent.VK_A, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_A, KeyEvent.META_MASK))) { // handling Ctrl+A manually (Cmd+A for MacOS) setSelectionStart(doc.getTranslationStart()); setSelectionEnd(doc.getTranslationEnd()); processed = true; } else if (isKey(e, KeyEvent.VK_O, KeyEvent.CTRL_MASK | KeyEvent.SHIFT_MASK)) { // handle Ctrl+Shift+O - toggle orientation LTR-RTL controller.toggleOrientation(); processed = true; } else if ((!mac && isKey(e, KeyEvent.VK_BACK_SPACE, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_BACK_SPACE, KeyEvent.ALT_MASK))) { // handle Ctrl+Backspace (Alt+Backspace for MacOS) try { int offset = getCaretPosition(); int prevWord = Utilities.getPreviousWord(this, offset); int c = Math.max(prevWord, doc.getTranslationStart()); setSelectionStart(c); setSelectionEnd(offset); replaceSelection(""); processed = true; } catch (BadLocationException ex) { // do nothing } } else if ((!mac && isKey(e, KeyEvent.VK_DELETE, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_DELETE, KeyEvent.ALT_MASK))) { // handle Ctrl+Backspace (Alt+Delete for MacOS) try { int offset = getCaretPosition(); int nextWord = Utilities.getNextWord(this, offset); int c = Math.min(nextWord, doc.getTranslationEnd()); setSelectionStart(offset); setSelectionEnd(c); replaceSelection(""); processed = true; } catch (BadLocationException ex) { // do nothing } } else if ((!mac && isKey(e, KeyEvent.VK_PAGE_UP, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_PAGE_UP, KeyEvent.META_MASK))) { // Ctrl+PgUp - to the begin of document(Cmd+PgUp for MacOS) setCaretPosition(0); processed = true; } else if ((!mac && isKey(e, KeyEvent.VK_PAGE_DOWN, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_PAGE_DOWN, KeyEvent.META_MASK))) { // Ctrl+PgDn - to the end of document(Cmd+PgDn for MacOS) setCaretPosition(getOmDocument().getLength()); processed = true; } // leave standard processing if need if (processed) { e.consume(); } else { if ((e.getModifiers() & (KeyEvent.CTRL_MASK | KeyEvent.META_MASK | KeyEvent.ALT_MASK)) == 0) { // there is no Alt,Ctrl,Cmd keys, i.e. it's char if (e.getKeyCode() != KeyEvent.VK_SHIFT) { // it's not a single 'shift' press checkAndFixCaret(); } } super.processKeyEvent(e); } controller.showLengthMessage(); // some after-processing catches if (!processed && e.getKeyChar() != 0) { switch (e.getKeyCode()) { case KeyEvent.VK_HOME: case KeyEvent.VK_END: case KeyEvent.VK_LEFT: case KeyEvent.VK_RIGHT: case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: checkAndFixCaret(); } } } /** * Checks whether the selection & caret is inside editable text, and changes * their positions accordingly if not. */ void checkAndFixCaret() { Document3 doc = getOmDocument(); if (doc == null) { // doc is not active return; } if (!doc.isEditMode()) { return; } // int pos = m_editor.getCaretPosition(); int spos = getSelectionStart(); int epos = getSelectionEnd(); /* * int start = m_segmentStartOffset + m_sourceDisplayLength + * OConsts.segmentStartStringFull.length(); */ int start = doc.getTranslationStart(); // -1 for space before tag, -2 for newlines /* * int end = editor.getTextLength() - m_segmentEndInset - * OConsts.segmentEndStringFull.length(); */ int end = doc.getTranslationEnd(); if (spos != epos) { // dealing with a selection here - make sure it's w/in bounds if (spos < start) { setSelectionStart(start); } else if (spos > end) { setSelectionStart(end); } if (epos > end) { setSelectionEnd(end); } else if (epos < start) { setSelectionStart(start); } } else { // non selected text if (spos < start) { setCaretPosition(start); } else if (spos > end) { setCaretPosition(end); } } } /** * Check if specified key pressed. * * @param e * pressed key event * @param code * required key code * @param modifiers * required modifiers * @return true if checked key pressed */ private static boolean isKey(KeyEvent e, int code, int modifiers) { return e.getKeyCode() == code && e.getModifiers() == modifiers; } /** * Allow to paste into segment, even selection outside editable segment. In * this case selection will be truncated into segment's boundaries. */ @Override public void paste() { checkAndFixCaret(); super.paste(); } /** * Allow to cut segment, even selection outside editable segment. In this * case selection will be truncated into segment's boundaries. */ @Override public void cut() { checkAndFixCaret(); super.cut(); } /** * Remove invisible direction chars on the copy text into clipboard. */ @Override public String getSelectedText() { String st = super.getSelectedText(); return st != null ? EditorUtils.removeDirectionChars(st) : null; } /** * creates a popup menu for inactive segments - with an item allowing to go * to the given segment. */ private boolean createGoToSegmentPopUp(Point point) { final int mousepos = this.viewToModel(point); if (mousepos >= getOmDocument().getTranslationStart() - OConsts.segmentStartStringFull.length() && mousepos <= getOmDocument().getTranslationEnd() + OConsts.segmentStartStringFull.length()) return false; JPopupMenu popup = new JPopupMenu(); JMenuItem item = popup .add(OStrings.getString("MW_PROMPT_SEG_NR_TITLE")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setCaretPosition(mousepos); controller.goToSegmentAtLocation(getCaretPosition()); } }); popup.show(this, (int) point.getX(), (int) point.getY()); return true; } /** * create the spell checker popup menu - suggestions for a wrong word, add * and ignore. Works only for the active segment, for the translation * * @param point : * where should the popup be shown */ protected boolean createSpellCheckerPopUp(final Point point) { if (!controller.getSettings().isAutoSpellChecking()) return false; // where is the mouse int mousepos = viewToModel(point); if (mousepos < getOmDocument().getTranslationStart() || mousepos > getOmDocument().getTranslationEnd()) return false; try { // find the word boundaries final int wordStart = Utilities.getWordStart(this, mousepos); final int wordEnd = Utilities.getWordEnd(this, mousepos); final String word = EditorUtils.removeDirection(getText(wordStart, wordEnd - wordStart)); final AbstractDocument xlDoc = (AbstractDocument) getDocument(); if (!Core.getSpellChecker().isCorrect(word)) { // get the suggestions and create a menu List<String> suggestions = Core.getSpellChecker().suggest(word); // create the menu JPopupMenu popup = new JPopupMenu(); // the suggestions for (final String replacement : suggestions) { JMenuItem item = popup.add(replacement); item.addActionListener(new ActionListener() { // the action: replace the word with the selected // suggestion public void actionPerformed(ActionEvent e) { try { int pos = getCaretPosition(); xlDoc.replace(wordStart, word.length(), replacement, null); setCaretPosition(pos); } catch (BadLocationException exc) { Log.log(exc); } } }); } // what if no action is done? if (suggestions.size() == 0) { JMenuItem item = popup.add(OStrings .getString("SC_NO_SUGGESTIONS")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // just hide the menu } }); } popup.add(new JSeparator()); // let us ignore it JMenuItem item = popup.add(OStrings.getString("SC_IGNORE_ALL")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addIgnoreWord(word, wordStart, false); } }); // or add it to the dictionary item = popup.add(OStrings.getString("SC_ADD_TO_DICTIONARY")); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { addIgnoreWord(word, wordStart, true); } }); popup.show(this, (int) point.getX(), (int) point.getY()); } } catch (BadLocationException ex) { Log.log(ex); } return true; } /** * add a new word to the spell checker or ignore a word * * @param word : * the word in question * @param offset : * the offset of the word in the editor * @param add : * true for add, false for ignore */ protected void addIgnoreWord(final String word, final int offset, final boolean add) { UIThreadsUtil.mustBeSwingThread(); if (add) { Core.getSpellChecker().learnWord(word); } else { Core.getSpellChecker().ignoreWord(word); } controller.spellCheckerThread.resetCache(); // redraw segments repaint(); } /** * Factory for create own view. */ public static ViewFactory factory3 = new ViewFactory() { public View create(Element elem) { String kind = elem.getName(); if (kind != null) { if (kind.equals(AbstractDocument.ContentElementName)) { return new ViewLabel(elem); } else if (kind.equals(AbstractDocument.ParagraphElementName)) { return new ParagraphView(elem); } else if (kind.equals(AbstractDocument.SectionElementName)) { return new BoxView(elem, View.Y_AXIS); } else if (kind.equals(StyleConstants.ComponentElementName)) { return new ComponentView(elem); } else if (kind.equals(StyleConstants.IconElementName)) { return new IconView(elem); } } // default to text display return new ViewLabel(elem); } }; }
true
true
protected void processKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { // key released super.processKeyEvent(e); return; } boolean processed = false; boolean mac = StaticUtils.onMacOSX(); Document3 doc = getOmDocument(); // non-standard processing if (isKey(e, KeyEvent.VK_TAB, 0)) { // press TAB when 'Use TAB to advance' if (controller.settings.isUseTabForAdvance()) { controller.nextEntry(); processed = true; } } else if (isKey(e, KeyEvent.VK_TAB, KeyEvent.SHIFT_MASK)) { // press Shift+TAB when 'Use TAB to advance' if (controller.settings.isUseTabForAdvance()) { controller.prevEntry(); processed = true; } } else if (isKey(e, KeyEvent.VK_ENTER, 0)) { // press ENTER if (!controller.settings.isUseTabForAdvance()) { controller.nextEntry(); processed = true; } } else if ((!mac && isKey(e, KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_ENTER, KeyEvent.META_MASK))) { // press Ctrl+ENTER (Cmd+Enter for MacOS) if (!controller.settings.isUseTabForAdvance()) { controller.prevEntry(); processed = true; } } else if (isKey(e, KeyEvent.VK_ENTER, KeyEvent.SHIFT_MASK)) { // convert Shift+Enter event to straight enter key KeyEvent ke = new KeyEvent(e.getComponent(), e.getID(), e.getWhen(), 0, KeyEvent.VK_ENTER, '\n'); super.processKeyEvent(ke); processed = true; } else if ((!mac && isKey(e, KeyEvent.VK_A, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_A, KeyEvent.META_MASK))) { // handling Ctrl+A manually (Cmd+A for MacOS) setSelectionStart(doc.getTranslationStart()); setSelectionEnd(doc.getTranslationEnd()); processed = true; } else if (isKey(e, KeyEvent.VK_O, KeyEvent.CTRL_MASK | KeyEvent.SHIFT_MASK)) { // handle Ctrl+Shift+O - toggle orientation LTR-RTL controller.toggleOrientation(); processed = true; } else if ((!mac && isKey(e, KeyEvent.VK_BACK_SPACE, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_BACK_SPACE, KeyEvent.ALT_MASK))) { // handle Ctrl+Backspace (Alt+Backspace for MacOS) try { int offset = getCaretPosition(); int prevWord = Utilities.getPreviousWord(this, offset); int c = Math.max(prevWord, doc.getTranslationStart()); setSelectionStart(c); setSelectionEnd(offset); replaceSelection(""); processed = true; } catch (BadLocationException ex) { // do nothing } } else if ((!mac && isKey(e, KeyEvent.VK_DELETE, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_DELETE, KeyEvent.ALT_MASK))) { // handle Ctrl+Backspace (Alt+Delete for MacOS) try { int offset = getCaretPosition(); int nextWord = Utilities.getNextWord(this, offset); int c = Math.min(nextWord, doc.getTranslationEnd()); setSelectionStart(offset); setSelectionEnd(c); replaceSelection(""); processed = true; } catch (BadLocationException ex) { // do nothing } } else if ((!mac && isKey(e, KeyEvent.VK_PAGE_UP, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_PAGE_UP, KeyEvent.META_MASK))) { // Ctrl+PgUp - to the begin of document(Cmd+PgUp for MacOS) setCaretPosition(0); processed = true; } else if ((!mac && isKey(e, KeyEvent.VK_PAGE_DOWN, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_PAGE_DOWN, KeyEvent.META_MASK))) { // Ctrl+PgDn - to the end of document(Cmd+PgDn for MacOS) setCaretPosition(getOmDocument().getLength()); processed = true; } // leave standard processing if need if (processed) { e.consume(); } else { if ((e.getModifiers() & (KeyEvent.CTRL_MASK | KeyEvent.META_MASK | KeyEvent.ALT_MASK)) == 0) { // there is no Alt,Ctrl,Cmd keys, i.e. it's char if (e.getKeyCode() != KeyEvent.VK_SHIFT) { // it's not a single 'shift' press checkAndFixCaret(); } } super.processKeyEvent(e); } controller.showLengthMessage(); // some after-processing catches if (!processed && e.getKeyChar() != 0) { switch (e.getKeyCode()) { case KeyEvent.VK_HOME: case KeyEvent.VK_END: case KeyEvent.VK_LEFT: case KeyEvent.VK_RIGHT: case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: checkAndFixCaret(); } } }
protected void processKeyEvent(KeyEvent e) { if (e.getID() != KeyEvent.KEY_PRESSED) { // key released super.processKeyEvent(e); return; } boolean processed = false; boolean mac = StaticUtils.onMacOSX(); Document3 doc = getOmDocument(); // non-standard processing if (isKey(e, KeyEvent.VK_TAB, 0)) { // press TAB when 'Use TAB to advance' if (controller.settings.isUseTabForAdvance()) { controller.nextEntry(); processed = true; } } else if (isKey(e, KeyEvent.VK_TAB, KeyEvent.SHIFT_MASK)) { // press Shift+TAB when 'Use TAB to advance' if (controller.settings.isUseTabForAdvance()) { controller.prevEntry(); processed = true; } } else if (isKey(e, KeyEvent.VK_ENTER, 0)) { // press ENTER if (!controller.settings.isUseTabForAdvance()) { controller.nextEntry(); processed = true; } else { processed = true; } } else if ((!mac && isKey(e, KeyEvent.VK_ENTER, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_ENTER, KeyEvent.META_MASK))) { // press Ctrl+ENTER (Cmd+Enter for MacOS) if (!controller.settings.isUseTabForAdvance()) { controller.prevEntry(); processed = true; } } else if (isKey(e, KeyEvent.VK_ENTER, KeyEvent.SHIFT_MASK)) { // convert Shift+Enter event to straight enter key KeyEvent ke = new KeyEvent(e.getComponent(), e.getID(), e.getWhen(), 0, KeyEvent.VK_ENTER, '\n'); super.processKeyEvent(ke); processed = true; } else if ((!mac && isKey(e, KeyEvent.VK_A, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_A, KeyEvent.META_MASK))) { // handling Ctrl+A manually (Cmd+A for MacOS) setSelectionStart(doc.getTranslationStart()); setSelectionEnd(doc.getTranslationEnd()); processed = true; } else if (isKey(e, KeyEvent.VK_O, KeyEvent.CTRL_MASK | KeyEvent.SHIFT_MASK)) { // handle Ctrl+Shift+O - toggle orientation LTR-RTL controller.toggleOrientation(); processed = true; } else if ((!mac && isKey(e, KeyEvent.VK_BACK_SPACE, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_BACK_SPACE, KeyEvent.ALT_MASK))) { // handle Ctrl+Backspace (Alt+Backspace for MacOS) try { int offset = getCaretPosition(); int prevWord = Utilities.getPreviousWord(this, offset); int c = Math.max(prevWord, doc.getTranslationStart()); setSelectionStart(c); setSelectionEnd(offset); replaceSelection(""); processed = true; } catch (BadLocationException ex) { // do nothing } } else if ((!mac && isKey(e, KeyEvent.VK_DELETE, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_DELETE, KeyEvent.ALT_MASK))) { // handle Ctrl+Backspace (Alt+Delete for MacOS) try { int offset = getCaretPosition(); int nextWord = Utilities.getNextWord(this, offset); int c = Math.min(nextWord, doc.getTranslationEnd()); setSelectionStart(offset); setSelectionEnd(c); replaceSelection(""); processed = true; } catch (BadLocationException ex) { // do nothing } } else if ((!mac && isKey(e, KeyEvent.VK_PAGE_UP, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_PAGE_UP, KeyEvent.META_MASK))) { // Ctrl+PgUp - to the begin of document(Cmd+PgUp for MacOS) setCaretPosition(0); processed = true; } else if ((!mac && isKey(e, KeyEvent.VK_PAGE_DOWN, KeyEvent.CTRL_MASK)) || (mac && isKey(e, KeyEvent.VK_PAGE_DOWN, KeyEvent.META_MASK))) { // Ctrl+PgDn - to the end of document(Cmd+PgDn for MacOS) setCaretPosition(getOmDocument().getLength()); processed = true; } // leave standard processing if need if (processed) { e.consume(); } else { if ((e.getModifiers() & (KeyEvent.CTRL_MASK | KeyEvent.META_MASK | KeyEvent.ALT_MASK)) == 0) { // there is no Alt,Ctrl,Cmd keys, i.e. it's char if (e.getKeyCode() != KeyEvent.VK_SHIFT) { // it's not a single 'shift' press checkAndFixCaret(); } } super.processKeyEvent(e); } controller.showLengthMessage(); // some after-processing catches if (!processed && e.getKeyChar() != 0) { switch (e.getKeyCode()) { case KeyEvent.VK_HOME: case KeyEvent.VK_END: case KeyEvent.VK_LEFT: case KeyEvent.VK_RIGHT: case KeyEvent.VK_UP: case KeyEvent.VK_DOWN: checkAndFixCaret(); } } }
diff --git a/src/com/ihunda/android/binauralbeat/VizualizationView.java b/src/com/ihunda/android/binauralbeat/VizualizationView.java index 9c491f6..f2da156 100644 --- a/src/com/ihunda/android/binauralbeat/VizualizationView.java +++ b/src/com/ihunda/android/binauralbeat/VizualizationView.java @@ -1,171 +1,171 @@ package com.ihunda.android.binauralbeat; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; public class VizualizationView extends SurfaceView implements Callback { protected static final long DRAW_REFRESH_INTERVAL_MS = 1000 / 20; private SurfaceHolder mSurfaceHolder; private int width; private int height; private Visualization v; private boolean running; protected float pos; protected float length; private Thread vThread; public VizualizationView(Context context, AttributeSet attrs) { super(context, attrs); // register our interest in hearing about changes to our surface mSurfaceHolder = getHolder(); mSurfaceHolder.addCallback(this); setFocusable(true); // make sure we get key events v = null; running = false; } /* Callback invoked when the surface dimensions change. */ public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { this.width = width; this.height = height; } public void surfaceCreated(SurfaceHolder holder) { if (vThread == null) { running = true; vThread = new Thread(vizThread); vThread.start(); } } public void surfaceDestroyed(SurfaceHolder holder) { running = false; boolean retry = true; if (vThread != null) { while (retry) { try { vThread.join(); retry = false; vThread = null; } catch (InterruptedException e) { } } } } public void startVisualization(Visualization v, float length) { assert(this.v == null); assert(vThread == null); drawClear(); if (v == null) return; this.v = v; this.pos = 0; this.length = length; running = true; vThread = new Thread(vizThread); vThread.start(); } public void stopVisualization() { boolean retry = true; this.v = null; running = false; if (vThread != null) { while (retry) { try { vThread.join(); retry = false; vThread = null; } catch (InterruptedException e) { } } } drawClear(); } public void setProgress(float pos) { this.pos = pos; } public void setFrequency(float freq) { if (v != null) v.setFrequency(freq); } void drawMain(float now, float length) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { - if (c != null) { + if (c != null && v != null ) { v.redraw(c, width, height, now, length); } } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } void drawClear() { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(null); if (c != null) synchronized (mSurfaceHolder) { c.drawColor(Color.BLACK); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } } private Runnable vizThread = new Runnable() { public void run() { while(running == true) { long now = System.currentTimeMillis(); drawMain(pos, length); long elapsed = System.currentTimeMillis() - now; while(elapsed < DRAW_REFRESH_INTERVAL_MS) { try { Thread.sleep(DRAW_REFRESH_INTERVAL_MS - elapsed, 0); } catch (InterruptedException e) { } elapsed = System.currentTimeMillis() - now; } } } }; }
true
true
void drawMain(float now, float length) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { if (c != null) { v.redraw(c, width, height, now, length); } } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } }
void drawMain(float now, float length) { Canvas c = null; try { c = mSurfaceHolder.lockCanvas(null); synchronized (mSurfaceHolder) { if (c != null && v != null ) { v.redraw(c, width, height, now, length); } } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { mSurfaceHolder.unlockCanvasAndPost(c); } } }
diff --git a/sonar/sonar-plugin-gendarme/src/main/java/org/sonar/plugin/dotnet/gendarme/GendarmeResultParser.java b/sonar/sonar-plugin-gendarme/src/main/java/org/sonar/plugin/dotnet/gendarme/GendarmeResultParser.java index 612ab35fd..f77e241d7 100644 --- a/sonar/sonar-plugin-gendarme/src/main/java/org/sonar/plugin/dotnet/gendarme/GendarmeResultParser.java +++ b/sonar/sonar-plugin-gendarme/src/main/java/org/sonar/plugin/dotnet/gendarme/GendarmeResultParser.java @@ -1,200 +1,200 @@ package org.sonar.plugin.dotnet.gendarme; import java.io.File; import java.net.URL; import java.text.ParseException; import java.util.Collection; import java.util.List; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.batch.SensorContext; import org.sonar.api.profiles.RulesProfile; import org.sonar.api.resources.Project; import org.sonar.api.resources.Resource; import org.sonar.api.rules.ActiveRule; import org.sonar.api.rules.Rule; import org.sonar.api.rules.RulesManager; import org.sonar.api.rules.Violation; import org.sonar.api.utils.ParsingUtils; import org.sonar.plugin.dotnet.core.AbstractXmlParser; import org.sonar.plugin.dotnet.core.resource.CLRAssembly; import org.sonar.plugin.dotnet.core.resource.CSharpFile; import org.w3c.dom.Element; import org.apache.maven.dotnet.commons.GeneratedCodeFilter; import org.apache.maven.dotnet.commons.project.SourceFile; public class GendarmeResultParser extends AbstractXmlParser { private final static Logger log = LoggerFactory.getLogger(GendarmeResultParser.class); private Project project; private SensorContext context; private RulesManager rulesManager; private RulesProfile profile; /** * Constructs a @link{GendarmeResultParser}. * * @param project * @param context * @param rulesManager * @param profile */ public GendarmeResultParser(Project project, SensorContext context, RulesManager rulesManager, RulesProfile profile) { super(); this.project = project; this.context = context; this.rulesManager = rulesManager; this.profile = profile; } /** * Parses a processed violation file. * * @param stream */ public void parse(URL url) { List<Element> issues = extractElements(url, "//issue"); // We add each issue for (Element issueElement : issues) { String key = getNodeContent(issueElement, "key"); String source = getNodeContent(issueElement, "source"); String message = getNodeContent(issueElement, "message"); String location = getNodeContent(issueElement, "location"); final String filePath; final String lineNumber; if (StringUtils.isEmpty(source) || StringUtils.contains(source, "debugging symbols unavailable")) { String assemblyName = StringUtils.substringBefore(getNodeContent( issueElement, "assembly-name"), ","); CLRAssembly assembly = CLRAssembly.fromName(project, assemblyName); if (StringUtils.contains(key, "Assembly")) { // we assume we have a violation at the // assembly level filePath = assembly.getVisualProject().getDirectory() .getAbsolutePath() + File.separator + "Properties" + File.separator + "AssemblyInfo.cs"; lineNumber = ""; } else { if (StringUtils.containsNone(location, " ")) { // we will try to find a cs file that match with the class name - final String className = StringUtils.substringAfterLast(location, "."); + final String className = StringUtils.substringBeforeLast(StringUtils.substringAfterLast(location, "."), "/"); Collection<SourceFile> sourceFiles = assembly.getVisualProject().getSourceFiles(); SourceFile sourceFile = null; for (SourceFile currentSourceFile : sourceFiles) { if (StringUtils.startsWith(currentSourceFile.getName(), className)) { sourceFile = currentSourceFile; break; } } if (sourceFile == null) { // this one will be ignored log.info("ignoring gendarme violation {} {} {}", new Object[]{key, source, message}); continue; } else { filePath = sourceFile.getFile().getAbsolutePath(); lineNumber = ""; } } else { // this one will be ignored log.info("ignoring gendarme violation {} {} {}", new Object[]{key, source, message}); continue; } } } else { filePath = StringUtils.substringBefore(source, "("); lineNumber = StringUtils.substring(StringUtils.substringBetween(source, "(", ")"), 1); // // we do not care about violations in generated files // if (GeneratedCodeFilter.INSTANCE.isGenerated(StringUtils .substringAfterLast(filePath, File.separator))) { continue; } } if (StringUtils.isEmpty(lineNumber) && StringUtils.contains(location, "::")) { // append a more specific location information // to the message String codeElement = StringUtils.substringAfter(location, "::"); if (!StringUtils.contains(message, codeElement)) { message = StringUtils.substringAfter(location, "::") + " " + message; } } Resource<?> resource = getResource(filePath); Integer line = getIntValue(lineNumber); Rule rule = rulesManager.getPluginRule(GendarmePlugin.KEY, key); if (rule == null) { // We skip the rules that were not registered continue; } ActiveRule activeRule = profile.getActiveRule(GendarmePlugin.KEY, key); Violation violation = new Violation(rule, resource); violation.setLineId(line); violation.setMessage(message); if (activeRule != null) { violation.setPriority(activeRule.getPriority()); } // We store the violation context.saveViolation(violation); } } public Resource<?> getResource(String filePath) { if (StringUtils.isBlank(filePath)) { return null; } if (log.isDebugEnabled()) { log.debug("Getting resource for path: "+filePath); } File file = new File(filePath); final CSharpFile fileResource; if (file.exists()) { fileResource = CSharpFile.from(project, file, false); } else { log.error("Unable to ge resource for path "+filePath); fileResource = null; } return fileResource; } /** * Extracts the line number. * * @param lineStr * @return */ protected Integer getIntValue(String lineStr) { if (StringUtils.isBlank(lineStr)) { return null; } try { return (int) ParsingUtils.parseNumber(lineStr); } catch (ParseException ignore) { return null; } } }
true
true
public void parse(URL url) { List<Element> issues = extractElements(url, "//issue"); // We add each issue for (Element issueElement : issues) { String key = getNodeContent(issueElement, "key"); String source = getNodeContent(issueElement, "source"); String message = getNodeContent(issueElement, "message"); String location = getNodeContent(issueElement, "location"); final String filePath; final String lineNumber; if (StringUtils.isEmpty(source) || StringUtils.contains(source, "debugging symbols unavailable")) { String assemblyName = StringUtils.substringBefore(getNodeContent( issueElement, "assembly-name"), ","); CLRAssembly assembly = CLRAssembly.fromName(project, assemblyName); if (StringUtils.contains(key, "Assembly")) { // we assume we have a violation at the // assembly level filePath = assembly.getVisualProject().getDirectory() .getAbsolutePath() + File.separator + "Properties" + File.separator + "AssemblyInfo.cs"; lineNumber = ""; } else { if (StringUtils.containsNone(location, " ")) { // we will try to find a cs file that match with the class name final String className = StringUtils.substringAfterLast(location, "."); Collection<SourceFile> sourceFiles = assembly.getVisualProject().getSourceFiles(); SourceFile sourceFile = null; for (SourceFile currentSourceFile : sourceFiles) { if (StringUtils.startsWith(currentSourceFile.getName(), className)) { sourceFile = currentSourceFile; break; } } if (sourceFile == null) { // this one will be ignored log.info("ignoring gendarme violation {} {} {}", new Object[]{key, source, message}); continue; } else { filePath = sourceFile.getFile().getAbsolutePath(); lineNumber = ""; } } else { // this one will be ignored log.info("ignoring gendarme violation {} {} {}", new Object[]{key, source, message}); continue; } } } else { filePath = StringUtils.substringBefore(source, "("); lineNumber = StringUtils.substring(StringUtils.substringBetween(source, "(", ")"), 1); // // we do not care about violations in generated files // if (GeneratedCodeFilter.INSTANCE.isGenerated(StringUtils .substringAfterLast(filePath, File.separator))) { continue; } } if (StringUtils.isEmpty(lineNumber) && StringUtils.contains(location, "::")) { // append a more specific location information // to the message String codeElement = StringUtils.substringAfter(location, "::"); if (!StringUtils.contains(message, codeElement)) { message = StringUtils.substringAfter(location, "::") + " " + message; } } Resource<?> resource = getResource(filePath); Integer line = getIntValue(lineNumber); Rule rule = rulesManager.getPluginRule(GendarmePlugin.KEY, key); if (rule == null) { // We skip the rules that were not registered continue; } ActiveRule activeRule = profile.getActiveRule(GendarmePlugin.KEY, key); Violation violation = new Violation(rule, resource); violation.setLineId(line); violation.setMessage(message); if (activeRule != null) { violation.setPriority(activeRule.getPriority()); } // We store the violation context.saveViolation(violation); } }
public void parse(URL url) { List<Element> issues = extractElements(url, "//issue"); // We add each issue for (Element issueElement : issues) { String key = getNodeContent(issueElement, "key"); String source = getNodeContent(issueElement, "source"); String message = getNodeContent(issueElement, "message"); String location = getNodeContent(issueElement, "location"); final String filePath; final String lineNumber; if (StringUtils.isEmpty(source) || StringUtils.contains(source, "debugging symbols unavailable")) { String assemblyName = StringUtils.substringBefore(getNodeContent( issueElement, "assembly-name"), ","); CLRAssembly assembly = CLRAssembly.fromName(project, assemblyName); if (StringUtils.contains(key, "Assembly")) { // we assume we have a violation at the // assembly level filePath = assembly.getVisualProject().getDirectory() .getAbsolutePath() + File.separator + "Properties" + File.separator + "AssemblyInfo.cs"; lineNumber = ""; } else { if (StringUtils.containsNone(location, " ")) { // we will try to find a cs file that match with the class name final String className = StringUtils.substringBeforeLast(StringUtils.substringAfterLast(location, "."), "/"); Collection<SourceFile> sourceFiles = assembly.getVisualProject().getSourceFiles(); SourceFile sourceFile = null; for (SourceFile currentSourceFile : sourceFiles) { if (StringUtils.startsWith(currentSourceFile.getName(), className)) { sourceFile = currentSourceFile; break; } } if (sourceFile == null) { // this one will be ignored log.info("ignoring gendarme violation {} {} {}", new Object[]{key, source, message}); continue; } else { filePath = sourceFile.getFile().getAbsolutePath(); lineNumber = ""; } } else { // this one will be ignored log.info("ignoring gendarme violation {} {} {}", new Object[]{key, source, message}); continue; } } } else { filePath = StringUtils.substringBefore(source, "("); lineNumber = StringUtils.substring(StringUtils.substringBetween(source, "(", ")"), 1); // // we do not care about violations in generated files // if (GeneratedCodeFilter.INSTANCE.isGenerated(StringUtils .substringAfterLast(filePath, File.separator))) { continue; } } if (StringUtils.isEmpty(lineNumber) && StringUtils.contains(location, "::")) { // append a more specific location information // to the message String codeElement = StringUtils.substringAfter(location, "::"); if (!StringUtils.contains(message, codeElement)) { message = StringUtils.substringAfter(location, "::") + " " + message; } } Resource<?> resource = getResource(filePath); Integer line = getIntValue(lineNumber); Rule rule = rulesManager.getPluginRule(GendarmePlugin.KEY, key); if (rule == null) { // We skip the rules that were not registered continue; } ActiveRule activeRule = profile.getActiveRule(GendarmePlugin.KEY, key); Violation violation = new Violation(rule, resource); violation.setLineId(line); violation.setMessage(message); if (activeRule != null) { violation.setPriority(activeRule.getPriority()); } // We store the violation context.saveViolation(violation); } }
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/ExecDriver.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/ExecDriver.java index 6212b231..bfc0c10a 100644 --- a/ql/src/java/org/apache/hadoop/hive/ql/exec/ExecDriver.java +++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/ExecDriver.java @@ -1,632 +1,634 @@ /** * 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.hadoop.hive.ql.exec; import java.io.*; import java.util.*; import java.net.URI; import java.net.URLEncoder; import java.net.URLDecoder; import java.net.URL; import java.net.URLClassLoader; import org.apache.commons.logging.LogFactory; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.fs.ContentSummary; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.*; import org.apache.hadoop.mapred.*; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.hadoop.hive.ql.plan.mapredWork; import org.apache.hadoop.hive.ql.metadata.HiveException; import org.apache.hadoop.hive.ql.history.HiveHistory.Keys; import org.apache.hadoop.hive.ql.io.*; import org.apache.hadoop.hive.ql.session.SessionState.LogHelper; import org.apache.hadoop.hive.ql.session.SessionState; public class ExecDriver extends Task<mapredWork> implements Serializable { private static final long serialVersionUID = 1L; transient protected JobConf job; /** * Constructor when invoked from QL */ public ExecDriver() { super(); } public static String getRealFiles(Configuration conf) { // fill in local files to be added to the task environment SessionState ss = SessionState.get(); Set<String> files = (ss == null) ? null : ss.list_resource( SessionState.ResourceType.FILE, null); if (files != null) { ArrayList<String> realFiles = new ArrayList<String>(files.size()); for (String one : files) { try { realFiles.add(Utilities.realFile(one, conf)); } catch (IOException e) { throw new RuntimeException("Cannot validate file " + one + "due to exception: " + e.getMessage(), e); } } return StringUtils.join(realFiles, ","); } else { return ""; } } /** * Initialization when invoked from QL */ public void initialize(HiveConf conf) { super.initialize(conf); job = new JobConf(conf, ExecDriver.class); String realFiles = getRealFiles(job); if (realFiles != null && realFiles.length() > 0) { job.set("tmpfiles", realFiles); // workaround for hadoop-17 - jobclient only looks at commandlineconfig Configuration commandConf = JobClient.getCommandLineConfig(); if (commandConf != null) { commandConf.set("tmpfiles", realFiles); } } } /** * Constructor/Initialization for invocation as independent utility */ public ExecDriver(mapredWork plan, JobConf job, boolean isSilent) throws HiveException { setWork(plan); this.job = job; LOG = LogFactory.getLog(this.getClass().getName()); console = new LogHelper(LOG, isSilent); } /** * A list of the currently running jobs spawned in this Hive instance that is * used to kill all running jobs in the event of an unexpected shutdown - * i.e., the JVM shuts down while there are still jobs running. */ public static HashMap<String, String> runningJobKillURIs = new HashMap<String, String>(); /** * In Hive, when the user control-c's the command line, any running jobs * spawned from that command line are best-effort killed. * * This static constructor registers a shutdown thread to iterate over all the * running job kill URLs and do a get on them. * */ static { if (new org.apache.hadoop.conf.Configuration().getBoolean( "webinterface.private.actions", false)) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { for (Iterator<String> elems = runningJobKillURIs.values().iterator(); elems .hasNext();) { String uri = elems.next(); try { System.err.println("killing job with: " + uri); int retCode = ((java.net.HttpURLConnection) new java.net.URL(uri) .openConnection()).getResponseCode(); if (retCode != 200) { System.err.println("Got an error trying to kill job with URI: " + uri + " = " + retCode); } } catch (Exception e) { System.err.println("trying to kill job, caught: " + e); // do nothing } } } }); } } /** * from StreamJob.java */ public void jobInfo(RunningJob rj) { if (job.get("mapred.job.tracker", "local").equals("local")) { console.printInfo("Job running in-process (local Hadoop)"); } else { String hp = job.get("mapred.job.tracker"); if (SessionState.get() != null) { SessionState.get().getHiveHistory().setTaskProperty( SessionState.get().getQueryId(), getId(), Keys.TASK_HADOOP_ID, rj.getJobID()); } console.printInfo("Starting Job = " + rj.getJobID() + ", Tracking URL = " + rj.getTrackingURL()); console.printInfo("Kill Command = " + HiveConf.getVar(job, HiveConf.ConfVars.HADOOPBIN) + " job -Dmapred.job.tracker=" + hp + " -kill " + rj.getJobID()); } } /** * from StreamJob.java */ public RunningJob jobProgress(JobClient jc, RunningJob rj) throws IOException { String lastReport = ""; while (!rj.isComplete()) { try { Thread.sleep(1000); } catch (InterruptedException e) { } rj = jc.getJob(rj.getJobID()); String report = null; report = " map = " + Math.round(rj.mapProgress() * 100) + "%, reduce =" + Math.round(rj.reduceProgress() * 100) + "%"; if (!report.equals(lastReport)) { SessionState ss = SessionState.get(); if (ss != null) { ss.getHiveHistory().setTaskCounters( SessionState.get().getQueryId(), getId(), rj); ss.getHiveHistory().setTaskProperty( SessionState.get().getQueryId(), getId(), Keys.TASK_HADOOP_PROGRESS, report); ss.getHiveHistory().progressTask( SessionState.get().getQueryId(), this); } console.printInfo(report); lastReport = report; } } return rj; } /** * Estimate the number of reducers needed for this job, based on job input, * and configuration parameters. * @return the number of reducers. */ public int estimateNumberOfReducers(HiveConf hive, JobConf job, mapredWork work) throws IOException { if (hive == null) { hive = new HiveConf(); } long bytesPerReducer = hive.getLongVar(HiveConf.ConfVars.BYTESPERREDUCER); int maxReducers = hive.getIntVar(HiveConf.ConfVars.MAXREDUCERS); long totalInputFileSize = getTotalInputFileSize(job, work); LOG.info("BytesPerReducer=" + bytesPerReducer + " maxReducers=" + maxReducers + " totalInputFileSize=" + totalInputFileSize); int reducers = (int)((totalInputFileSize + bytesPerReducer - 1) / bytesPerReducer); reducers = Math.max(1, reducers); reducers = Math.min(maxReducers, reducers); return reducers; } /** * Set the number of reducers for the mapred work. */ protected void setNumberOfReducers() throws IOException { // this is a temporary hack to fix things that are not fixed in the compiler Integer numReducersFromWork = work.getNumReduceTasks(); if(work.getReducer() == null) { console.printInfo("Number of reduce tasks is set to 0 since there's no reduce operator"); work.setNumReduceTasks(Integer.valueOf(0)); } else { if (numReducersFromWork >= 0) { console.printInfo("Number of reduce tasks determined at compile time: " + work.getNumReduceTasks()); } else if (job.getNumReduceTasks() > 0) { int reducers = job.getNumReduceTasks(); work.setNumReduceTasks(reducers); console.printInfo("Number of reduce tasks not specified. Defaulting to jobconf value of: " + reducers); } else { int reducers = estimateNumberOfReducers(conf, job, work); work.setNumReduceTasks(reducers); console.printInfo("Number of reduce tasks not specified. Estimated from input data size: " + reducers); } console.printInfo("In order to change the average load for a reducer (in bytes):"); console.printInfo(" set " + HiveConf.ConfVars.BYTESPERREDUCER.varname + "=<number>"); console.printInfo("In order to limit the maximum number of reducers:"); console.printInfo(" set " + HiveConf.ConfVars.MAXREDUCERS.varname + "=<number>"); console.printInfo("In order to set a constant number of reducers:"); console.printInfo(" set " + HiveConf.ConfVars.HADOOPNUMREDUCERS + "=<number>"); } } /** * Add new elements to the classpath * * @param newPaths * Array of classpath elements */ private static void addToClassPath(String[] newPaths) throws Exception { Thread curThread = Thread.currentThread(); URLClassLoader loader = (URLClassLoader) curThread.getContextClassLoader(); List<URL> curPath = Arrays.asList(loader.getURLs()); ArrayList<URL> newPath = new ArrayList<URL>(); for (String onestr : newPaths) { URL oneurl = (new File(onestr)).toURL(); if (!curPath.contains(oneurl)) { newPath.add(oneurl); } } loader = new URLClassLoader(newPath.toArray(new URL[0]), loader); curThread.setContextClassLoader(loader); } /** * Calculate the total size of input files. * @param job the hadoop job conf. * @return the total size in bytes. * @throws IOException */ public long getTotalInputFileSize(JobConf job, mapredWork work) throws IOException { long r = 0; FileSystem fs = FileSystem.get(job); // For each input path, calculate the total size. for (String path: work.getPathToAliases().keySet()) { try { ContentSummary cs = fs.getContentSummary(new Path(path)); r += cs.getLength(); } catch (IOException e) { LOG.info("Cannot get size of " + path + ". Safely ignored."); } } return r; } /** * Execute a query plan using Hadoop */ public int execute() { try { setNumberOfReducers(); } catch(IOException e) { String statusMesg = "IOException while accessing HDFS to estimate the number of reducers: " + e.getMessage(); console.printError(statusMesg, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); return 1; } String invalidReason = work.isInvalid(); if (invalidReason != null) { throw new RuntimeException("Plan invalid, Reason: " + invalidReason); } Utilities.setMapRedWork(job, work); for (String onefile : work.getPathToAliases().keySet()) { LOG.info("Adding input file " + onefile); FileInputFormat.addInputPaths(job, onefile); } String hiveScratchDir = HiveConf.getVar(job, HiveConf.ConfVars.SCRATCHDIR); String jobScratchDir = hiveScratchDir + Utilities.randGen.nextInt(); FileOutputFormat.setOutputPath(job, new Path(jobScratchDir)); job.setMapperClass(ExecMapper.class); job.setMapOutputKeyClass(HiveKey.class); // LazySimpleSerDe writes to Text // Revert to DynamicSerDe: job.setMapOutputValueClass(BytesWritable.class); job.setMapOutputValueClass(Text.class); job.setNumReduceTasks(work.getNumReduceTasks().intValue()); job.setReducerClass(ExecReducer.class); job.setInputFormat(org.apache.hadoop.hive.ql.io.HiveInputFormat.class); // No-Op - we don't really write anything here .. job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); String auxJars = HiveConf.getVar(job, HiveConf.ConfVars.HIVEAUXJARS); if (StringUtils.isNotBlank(auxJars)) { LOG.info("adding libjars: " + auxJars); job.set("tmpjars", auxJars); } int returnVal = 0; FileSystem fs = null; RunningJob rj = null, orig_rj = null; boolean success = false; try { fs = FileSystem.get(job); // if the input is empty exit gracefully Path[] inputPaths = FileInputFormat.getInputPaths(job); boolean emptyInput = true; for (Path inputP : inputPaths) { if (!fs.exists(inputP)) continue; FileStatus[] fStats = fs.listStatus(inputP); for (FileStatus fStat : fStats) { if (fStat.getLen() > 0) { emptyInput = false; break; } } } if (emptyInput) { console.printInfo("Job need not be submitted: no output: Success"); return 0; } // remove the pwd from conf file so that job tracker doesn't show this logs String pwd = job.get(HiveConf.ConfVars.METASTOREPWD.varname); - job.set(HiveConf.ConfVars.METASTOREPWD.varname, "HIVE"); + if (pwd != null) + job.set(HiveConf.ConfVars.METASTOREPWD.varname, "HIVE"); JobClient jc = new JobClient(job); // make this client wait if job trcker is not behaving well. Throttle.checkJobTracker(job, LOG); orig_rj = rj = jc.submitJob(job); // replace it back - job.set(HiveConf.ConfVars.METASTOREPWD.varname, pwd); + if (pwd != null) + job.set(HiveConf.ConfVars.METASTOREPWD.varname, pwd); // add to list of running jobs so in case of abnormal shutdown can kill // it. runningJobKillURIs.put(rj.getJobID(), rj.getTrackingURL() + "&action=kill"); jobInfo(rj); rj = jobProgress(jc, rj); if(rj == null) { // in the corner case where the running job has disappeared from JT memory // remember that we did actually submit the job. rj = orig_rj; success = false; } else { success = rj.isSuccessful(); } String statusMesg = "Ended Job = " + rj.getJobID(); if (!success) { statusMesg += " with errors"; returnVal = 2; console.printError(statusMesg); } else { console.printInfo(statusMesg); } } catch (Exception e) { String mesg = " with exception '" + Utilities.getNameMessage(e) + "'"; if (rj != null) { mesg = "Ended Job = " + rj.getJobID() + mesg; } else { mesg = "Job Submission failed" + mesg; } // Has to use full name to make sure it does not conflict with // org.apache.commons.lang.StringUtils console.printError(mesg, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); success = false; returnVal = 1; } finally { Utilities.clearMapRedWork(job); try { fs.delete(new Path(jobScratchDir), true); if (returnVal != 0 && rj != null) { rj.killJob(); } runningJobKillURIs.remove(rj.getJobID()); } catch (Exception e) { } } try { if (rj != null) { if(work.getAliasToWork() != null) { for(Operator<? extends Serializable> op: work.getAliasToWork().values()) { op.jobClose(job, success); } } if(work.getReducer() != null) { work.getReducer().jobClose(job, success); } } } catch (Exception e) { // jobClose needs to execute successfully otherwise fail task if(success) { success = false; returnVal = 3; String mesg = "Job Commit failed with exception '" + Utilities.getNameMessage(e) + "'"; console.printError(mesg, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); } } return (returnVal); } private static void printUsage() { System.out .println("ExecDriver -plan <plan-file> [-jobconf k1=v1 [-jobconf k2=v2] ...] " + "[-files <file1>[,<file2>] ...]"); System.exit(1); } public static void main(String[] args) throws IOException, HiveException { String planFileName = null; ArrayList<String> jobConfArgs = new ArrayList<String>(); boolean isSilent = false; String files = null; try { for (int i = 0; i < args.length; i++) { if (args[i].equals("-plan")) { planFileName = args[++i]; System.out.println("plan = " + planFileName); } else if (args[i].equals("-jobconf")) { jobConfArgs.add(args[++i]); } else if (args[i].equals("-silent")) { isSilent = true; } else if (args[i].equals("-files")) { files = args[++i]; } } } catch (IndexOutOfBoundsException e) { System.err.println("Missing argument to option"); printUsage(); } if (planFileName == null) { System.err.println("Must specify Plan File Name"); printUsage(); } JobConf conf = new JobConf(ExecDriver.class); for (String one : jobConfArgs) { int eqIndex = one.indexOf('='); if (eqIndex != -1) { try { conf.set(one.substring(0, eqIndex), URLDecoder.decode(one .substring(eqIndex + 1), "UTF-8")); } catch (UnsupportedEncodingException e) { System.err.println("Unexpected error " + e.getMessage() + " while encoding " + one.substring(eqIndex + 1)); System.exit(3); } } } if (files != null) { conf.set("tmpfiles", files); } URI pathURI = (new Path(planFileName)).toUri(); InputStream pathData; if (StringUtils.isEmpty(pathURI.getScheme())) { // default to local file system pathData = new FileInputStream(planFileName); } else { // otherwise may be in hadoop .. FileSystem fs = FileSystem.get(conf); pathData = fs.open(new Path(planFileName)); } // workaround for hadoop-17 - libjars are not added to classpath. this // affects local // mode execution boolean localMode = HiveConf.getVar(conf, HiveConf.ConfVars.HADOOPJT) .equals("local"); if (localMode) { String auxJars = HiveConf.getVar(conf, HiveConf.ConfVars.HIVEAUXJARS); if (StringUtils.isNotBlank(auxJars)) { try { addToClassPath(StringUtils.split(auxJars, ",")); } catch (Exception e) { throw new HiveException(e.getMessage(), e); } } } mapredWork plan = Utilities.deserializeMapRedWork(pathData); ExecDriver ed = new ExecDriver(plan, conf, isSilent); int ret = ed.execute(); if (ret != 0) { System.out.println("Job Failed"); System.exit(2); } } /** * Given a Hive Configuration object - generate a command line fragment for * passing such configuration information to ExecDriver */ public static String generateCmdLine(HiveConf hconf) { try { StringBuilder sb = new StringBuilder(); Properties deltaP = hconf.getChangedProperties(); boolean localMode = hconf.getVar(HiveConf.ConfVars.HADOOPJT).equals( "local"); String hadoopSysDir = "mapred.system.dir"; String hadoopWorkDir = "mapred.local.dir"; for (Object one : deltaP.keySet()) { String oneProp = (String) one; if (localMode && (oneProp.equals(hadoopSysDir) || oneProp.equals(hadoopWorkDir))) continue; String oneValue = deltaP.getProperty(oneProp); sb.append("-jobconf "); sb.append(oneProp); sb.append("="); sb.append(URLEncoder.encode(oneValue, "UTF-8")); sb.append(" "); } // Multiple concurrent local mode job submissions can cause collisions in // working dirs // Workaround is to rename map red working dir to a temp dir in such a // case if (localMode) { sb.append("-jobconf "); sb.append(hadoopSysDir); sb.append("="); sb.append(URLEncoder.encode(hconf.get(hadoopSysDir) + "/" + Utilities.randGen.nextInt(), "UTF-8")); sb.append(" "); sb.append("-jobconf "); sb.append(hadoopWorkDir); sb.append("="); sb.append(URLEncoder.encode(hconf.get(hadoopWorkDir) + "/" + Utilities.randGen.nextInt(), "UTF-8")); } return sb.toString(); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @Override public boolean isMapRedTask() { return true; } @Override public boolean hasReduce() { mapredWork w = getWork(); return w.getReducer() != null; } }
false
true
public int execute() { try { setNumberOfReducers(); } catch(IOException e) { String statusMesg = "IOException while accessing HDFS to estimate the number of reducers: " + e.getMessage(); console.printError(statusMesg, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); return 1; } String invalidReason = work.isInvalid(); if (invalidReason != null) { throw new RuntimeException("Plan invalid, Reason: " + invalidReason); } Utilities.setMapRedWork(job, work); for (String onefile : work.getPathToAliases().keySet()) { LOG.info("Adding input file " + onefile); FileInputFormat.addInputPaths(job, onefile); } String hiveScratchDir = HiveConf.getVar(job, HiveConf.ConfVars.SCRATCHDIR); String jobScratchDir = hiveScratchDir + Utilities.randGen.nextInt(); FileOutputFormat.setOutputPath(job, new Path(jobScratchDir)); job.setMapperClass(ExecMapper.class); job.setMapOutputKeyClass(HiveKey.class); // LazySimpleSerDe writes to Text // Revert to DynamicSerDe: job.setMapOutputValueClass(BytesWritable.class); job.setMapOutputValueClass(Text.class); job.setNumReduceTasks(work.getNumReduceTasks().intValue()); job.setReducerClass(ExecReducer.class); job.setInputFormat(org.apache.hadoop.hive.ql.io.HiveInputFormat.class); // No-Op - we don't really write anything here .. job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); String auxJars = HiveConf.getVar(job, HiveConf.ConfVars.HIVEAUXJARS); if (StringUtils.isNotBlank(auxJars)) { LOG.info("adding libjars: " + auxJars); job.set("tmpjars", auxJars); } int returnVal = 0; FileSystem fs = null; RunningJob rj = null, orig_rj = null; boolean success = false; try { fs = FileSystem.get(job); // if the input is empty exit gracefully Path[] inputPaths = FileInputFormat.getInputPaths(job); boolean emptyInput = true; for (Path inputP : inputPaths) { if (!fs.exists(inputP)) continue; FileStatus[] fStats = fs.listStatus(inputP); for (FileStatus fStat : fStats) { if (fStat.getLen() > 0) { emptyInput = false; break; } } } if (emptyInput) { console.printInfo("Job need not be submitted: no output: Success"); return 0; } // remove the pwd from conf file so that job tracker doesn't show this logs String pwd = job.get(HiveConf.ConfVars.METASTOREPWD.varname); job.set(HiveConf.ConfVars.METASTOREPWD.varname, "HIVE"); JobClient jc = new JobClient(job); // make this client wait if job trcker is not behaving well. Throttle.checkJobTracker(job, LOG); orig_rj = rj = jc.submitJob(job); // replace it back job.set(HiveConf.ConfVars.METASTOREPWD.varname, pwd); // add to list of running jobs so in case of abnormal shutdown can kill // it. runningJobKillURIs.put(rj.getJobID(), rj.getTrackingURL() + "&action=kill"); jobInfo(rj); rj = jobProgress(jc, rj); if(rj == null) { // in the corner case where the running job has disappeared from JT memory // remember that we did actually submit the job. rj = orig_rj; success = false; } else { success = rj.isSuccessful(); } String statusMesg = "Ended Job = " + rj.getJobID(); if (!success) { statusMesg += " with errors"; returnVal = 2; console.printError(statusMesg); } else { console.printInfo(statusMesg); } } catch (Exception e) { String mesg = " with exception '" + Utilities.getNameMessage(e) + "'"; if (rj != null) { mesg = "Ended Job = " + rj.getJobID() + mesg; } else { mesg = "Job Submission failed" + mesg; } // Has to use full name to make sure it does not conflict with // org.apache.commons.lang.StringUtils console.printError(mesg, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); success = false; returnVal = 1; } finally { Utilities.clearMapRedWork(job); try { fs.delete(new Path(jobScratchDir), true); if (returnVal != 0 && rj != null) { rj.killJob(); } runningJobKillURIs.remove(rj.getJobID()); } catch (Exception e) { } } try { if (rj != null) { if(work.getAliasToWork() != null) { for(Operator<? extends Serializable> op: work.getAliasToWork().values()) { op.jobClose(job, success); } } if(work.getReducer() != null) { work.getReducer().jobClose(job, success); } } } catch (Exception e) { // jobClose needs to execute successfully otherwise fail task if(success) { success = false; returnVal = 3; String mesg = "Job Commit failed with exception '" + Utilities.getNameMessage(e) + "'"; console.printError(mesg, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); } } return (returnVal); }
public int execute() { try { setNumberOfReducers(); } catch(IOException e) { String statusMesg = "IOException while accessing HDFS to estimate the number of reducers: " + e.getMessage(); console.printError(statusMesg, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); return 1; } String invalidReason = work.isInvalid(); if (invalidReason != null) { throw new RuntimeException("Plan invalid, Reason: " + invalidReason); } Utilities.setMapRedWork(job, work); for (String onefile : work.getPathToAliases().keySet()) { LOG.info("Adding input file " + onefile); FileInputFormat.addInputPaths(job, onefile); } String hiveScratchDir = HiveConf.getVar(job, HiveConf.ConfVars.SCRATCHDIR); String jobScratchDir = hiveScratchDir + Utilities.randGen.nextInt(); FileOutputFormat.setOutputPath(job, new Path(jobScratchDir)); job.setMapperClass(ExecMapper.class); job.setMapOutputKeyClass(HiveKey.class); // LazySimpleSerDe writes to Text // Revert to DynamicSerDe: job.setMapOutputValueClass(BytesWritable.class); job.setMapOutputValueClass(Text.class); job.setNumReduceTasks(work.getNumReduceTasks().intValue()); job.setReducerClass(ExecReducer.class); job.setInputFormat(org.apache.hadoop.hive.ql.io.HiveInputFormat.class); // No-Op - we don't really write anything here .. job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); String auxJars = HiveConf.getVar(job, HiveConf.ConfVars.HIVEAUXJARS); if (StringUtils.isNotBlank(auxJars)) { LOG.info("adding libjars: " + auxJars); job.set("tmpjars", auxJars); } int returnVal = 0; FileSystem fs = null; RunningJob rj = null, orig_rj = null; boolean success = false; try { fs = FileSystem.get(job); // if the input is empty exit gracefully Path[] inputPaths = FileInputFormat.getInputPaths(job); boolean emptyInput = true; for (Path inputP : inputPaths) { if (!fs.exists(inputP)) continue; FileStatus[] fStats = fs.listStatus(inputP); for (FileStatus fStat : fStats) { if (fStat.getLen() > 0) { emptyInput = false; break; } } } if (emptyInput) { console.printInfo("Job need not be submitted: no output: Success"); return 0; } // remove the pwd from conf file so that job tracker doesn't show this logs String pwd = job.get(HiveConf.ConfVars.METASTOREPWD.varname); if (pwd != null) job.set(HiveConf.ConfVars.METASTOREPWD.varname, "HIVE"); JobClient jc = new JobClient(job); // make this client wait if job trcker is not behaving well. Throttle.checkJobTracker(job, LOG); orig_rj = rj = jc.submitJob(job); // replace it back if (pwd != null) job.set(HiveConf.ConfVars.METASTOREPWD.varname, pwd); // add to list of running jobs so in case of abnormal shutdown can kill // it. runningJobKillURIs.put(rj.getJobID(), rj.getTrackingURL() + "&action=kill"); jobInfo(rj); rj = jobProgress(jc, rj); if(rj == null) { // in the corner case where the running job has disappeared from JT memory // remember that we did actually submit the job. rj = orig_rj; success = false; } else { success = rj.isSuccessful(); } String statusMesg = "Ended Job = " + rj.getJobID(); if (!success) { statusMesg += " with errors"; returnVal = 2; console.printError(statusMesg); } else { console.printInfo(statusMesg); } } catch (Exception e) { String mesg = " with exception '" + Utilities.getNameMessage(e) + "'"; if (rj != null) { mesg = "Ended Job = " + rj.getJobID() + mesg; } else { mesg = "Job Submission failed" + mesg; } // Has to use full name to make sure it does not conflict with // org.apache.commons.lang.StringUtils console.printError(mesg, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); success = false; returnVal = 1; } finally { Utilities.clearMapRedWork(job); try { fs.delete(new Path(jobScratchDir), true); if (returnVal != 0 && rj != null) { rj.killJob(); } runningJobKillURIs.remove(rj.getJobID()); } catch (Exception e) { } } try { if (rj != null) { if(work.getAliasToWork() != null) { for(Operator<? extends Serializable> op: work.getAliasToWork().values()) { op.jobClose(job, success); } } if(work.getReducer() != null) { work.getReducer().jobClose(job, success); } } } catch (Exception e) { // jobClose needs to execute successfully otherwise fail task if(success) { success = false; returnVal = 3; String mesg = "Job Commit failed with exception '" + Utilities.getNameMessage(e) + "'"; console.printError(mesg, "\n" + org.apache.hadoop.util.StringUtils.stringifyException(e)); } } return (returnVal); }
diff --git a/src/main/java/org/geonode/security/GeoNodeSecurityProvider.java b/src/main/java/org/geonode/security/GeoNodeSecurityProvider.java index e433313..b5eb419 100644 --- a/src/main/java/org/geonode/security/GeoNodeSecurityProvider.java +++ b/src/main/java/org/geonode/security/GeoNodeSecurityProvider.java @@ -1,144 +1,147 @@ package org.geonode.security; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.logging.Level; import org.apache.commons.dbcp.BasicDataSource; import org.geoserver.config.GeoServerDataDirectory; import org.geoserver.platform.GeoServerExtensions; import org.geoserver.security.GeoServerSecurityFilterChain; import org.geoserver.security.GeoServerSecurityManager; import org.geoserver.security.GeoServerSecurityProvider; import org.geoserver.security.config.SecurityManagerConfig; import org.geoserver.security.config.SecurityNamedServiceConfig; import org.geoserver.security.validation.SecurityConfigException; import org.geotools.util.logging.Logging; import org.vfny.geoserver.global.GeoserverDataDirectory; public class GeoNodeSecurityProvider extends GeoServerSecurityProvider implements GeoNodeSecurityClient.Provider { private GeoNodeSecurityClient client; @Override public Class<GeoNodeAuthenticationProvider> getAuthenticationProviderClass() { return GeoNodeAuthenticationProvider.class; } @Override public GeoNodeAuthenticationProvider createAuthenticationProvider( SecurityNamedServiceConfig config) { client = configuredClient(((GeoNodeAuthProviderConfig)config).getBaseUrl()); return new GeoNodeAuthenticationProvider(client); } @Override public Class<GeoNodeCookieProcessingFilter> getFilterClass() { return GeoNodeCookieProcessingFilter.class; } @Override public GeoNodeCookieProcessingFilter createFilter(SecurityNamedServiceConfig config) { return new GeoNodeCookieProcessingFilter(); } public GeoNodeSecurityClient getSecurityClient() { return client; } protected GeoNodeSecurityClient configuredClient(String baseUrl) { HTTPClient httpClient = new HTTPClient(10, 1000, 1000); String securityClientDatabaseURL = GeoServerExtensions.getProperty("org.geonode.security.databaseSecurityClient.url"); GeoNodeSecurityClient configured; String securityClient = "default"; if (securityClientDatabaseURL == null) { DefaultSecurityClient defaultClient = new DefaultSecurityClient(baseUrl, httpClient); configured = defaultClient; } else { securityClient = "database"; BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("org.postgresql.Driver"); dataSource.setUrl(securityClientDatabaseURL); configured = new DatabaseSecurityClient(dataSource, baseUrl, httpClient); } Logging.getLogger(getClass()).log(Level.INFO, "using geonode {0} security client", securityClient); return configured; } @Override public void init(GeoServerSecurityManager manager) { try { File cookie = geonodeCookie(); if (!cookie.exists()) { configureGeoNodeSecurity(manager); writeCookie(cookie); } } catch (Exception e) { throw new RuntimeException("Failed to initialize GeoNode settings", e); } } private static File geonodeCookie() throws IOException { GeoServerDataDirectory directory = GeoserverDataDirectory.accessor(); File geonodeDir = directory.findOrCreateDir("geonode"); return new File(geonodeDir, "geonode_initialized"); } private static void writeCookie(File cookie) throws IOException { FileWriter writer = new java.io.FileWriter(cookie); writer.write("This file was created to flag that the GeoNode extensions have been configured in this server."); writer.write("If you delete it, the GeoNode settings will be applied again the next time you restart GeoServer."); writer.close(); } private static void configureGeoNodeSecurity(GeoServerSecurityManager manager) throws Exception { addServices(manager); configureChains(manager); } private static void addServices(GeoServerSecurityManager manager) throws IOException, SecurityConfigException { GeoNodeAuthProviderConfig providerConfig = new GeoNodeAuthProviderConfig(); providerConfig.setName("geonodeAuthProvider"); providerConfig.setClassName(GeoNodeAuthenticationProvider.class.getCanonicalName()); providerConfig.setBaseUrl("http://localhost:8000/"); manager.saveAuthenticationProvider(providerConfig); GeoNodeAuthFilterConfig filterConfig = new GeoNodeAuthFilterConfig(); filterConfig.setName("geonodeCookieFilter"); filterConfig.setClassName(GeoNodeCookieProcessingFilter.class.getCanonicalName()); manager.saveFilter(filterConfig); GeoNodeAnonymousAuthFilterConfig anonymousFilterConfig = new GeoNodeAnonymousAuthFilterConfig(); anonymousFilterConfig.setName("geonodeAnonymousFilter"); anonymousFilterConfig.setClassName(GeoNodeAnonymousProcessingFilter.class.getCanonicalName()); manager.saveFilter(anonymousFilterConfig); } private static void configureChains(GeoServerSecurityManager manager) throws Exception { SecurityManagerConfig config = manager.getSecurityConfig(); config.getAuthProviderNames().add(0, "geonodeAuthProvider"); GeoServerSecurityFilterChain filterChain = config.getFilterChain(); - String[] anonymousChains = { + // place the geonodeCookieFilter before the anonymous filter + String[] geonodeCookieChains = { GeoServerSecurityFilterChain.WEB_CHAIN, GeoServerSecurityFilterChain.REST_CHAIN, + GeoServerSecurityFilterChain.GWC_WEB_CHAIN, GeoServerSecurityFilterChain.GWC_REST_CHAIN, GeoServerSecurityFilterChain.DEFAULT_CHAIN }; - for (String chain : anonymousChains) { - filterChain.insertBefore(chain, "geonodeAnonymousFilter", "anonymous"); + for (String chain : geonodeCookieChains) { + filterChain.insertFirst(chain, "geonodeCookieFilter"); } - filterChain.insertBefore(GeoServerSecurityFilterChain.DEFAULT_CHAIN, "geonodeCookieFilter", "geonodeAnonymousFilter"); + // stick the geonodeAnonymousFilter filter before the anonymous + filterChain.insertBefore(GeoServerSecurityFilterChain.DEFAULT_CHAIN, "geonodeAnonymousFilter", GeoServerSecurityFilterChain.ANONYMOUS_FILTER); manager.saveSecurityConfig(config); } }
false
true
private static void configureChains(GeoServerSecurityManager manager) throws Exception { SecurityManagerConfig config = manager.getSecurityConfig(); config.getAuthProviderNames().add(0, "geonodeAuthProvider"); GeoServerSecurityFilterChain filterChain = config.getFilterChain(); String[] anonymousChains = { GeoServerSecurityFilterChain.WEB_CHAIN, GeoServerSecurityFilterChain.REST_CHAIN, GeoServerSecurityFilterChain.GWC_REST_CHAIN, GeoServerSecurityFilterChain.DEFAULT_CHAIN }; for (String chain : anonymousChains) { filterChain.insertBefore(chain, "geonodeAnonymousFilter", "anonymous"); } filterChain.insertBefore(GeoServerSecurityFilterChain.DEFAULT_CHAIN, "geonodeCookieFilter", "geonodeAnonymousFilter"); manager.saveSecurityConfig(config); }
private static void configureChains(GeoServerSecurityManager manager) throws Exception { SecurityManagerConfig config = manager.getSecurityConfig(); config.getAuthProviderNames().add(0, "geonodeAuthProvider"); GeoServerSecurityFilterChain filterChain = config.getFilterChain(); // place the geonodeCookieFilter before the anonymous filter String[] geonodeCookieChains = { GeoServerSecurityFilterChain.WEB_CHAIN, GeoServerSecurityFilterChain.REST_CHAIN, GeoServerSecurityFilterChain.GWC_WEB_CHAIN, GeoServerSecurityFilterChain.GWC_REST_CHAIN, GeoServerSecurityFilterChain.DEFAULT_CHAIN }; for (String chain : geonodeCookieChains) { filterChain.insertFirst(chain, "geonodeCookieFilter"); } // stick the geonodeAnonymousFilter filter before the anonymous filterChain.insertBefore(GeoServerSecurityFilterChain.DEFAULT_CHAIN, "geonodeAnonymousFilter", GeoServerSecurityFilterChain.ANONYMOUS_FILTER); manager.saveSecurityConfig(config); }
diff --git a/ttools/src/main/uk/ac/starlink/ttools/build/JyStilts.java b/ttools/src/main/uk/ac/starlink/ttools/build/JyStilts.java index 99484a48d..9b3aafa47 100644 --- a/ttools/src/main/uk/ac/starlink/ttools/build/JyStilts.java +++ b/ttools/src/main/uk/ac/starlink/ttools/build/JyStilts.java @@ -1,1481 +1,1484 @@ package uk.ac.starlink.ttools.build; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.xml.sax.SAXException; import uk.ac.starlink.table.ColumnInfo; import uk.ac.starlink.table.MultiStarTableWriter; import uk.ac.starlink.table.StarTable; import uk.ac.starlink.table.StarTableFactory; import uk.ac.starlink.table.StarTableOutput; import uk.ac.starlink.table.TableSequence; import uk.ac.starlink.table.WrapperRowSequence; import uk.ac.starlink.table.WrapperStarTable; import uk.ac.starlink.task.DoubleParameter; import uk.ac.starlink.task.IntegerParameter; import uk.ac.starlink.task.InvokeUtils; import uk.ac.starlink.task.Parameter; import uk.ac.starlink.task.Task; import uk.ac.starlink.ttools.Formatter; import uk.ac.starlink.ttools.Stilts; import uk.ac.starlink.ttools.filter.ProcessingFilter; import uk.ac.starlink.ttools.filter.StepFactory; import uk.ac.starlink.ttools.jel.JELUtils; import uk.ac.starlink.ttools.mode.ProcessingMode; import uk.ac.starlink.ttools.task.AbstractInputTableParameter; import uk.ac.starlink.ttools.task.Calc; import uk.ac.starlink.ttools.task.ConsumerTask; import uk.ac.starlink.ttools.task.FilterParameter; import uk.ac.starlink.ttools.task.InputFormatParameter; import uk.ac.starlink.ttools.task.InputTableParameter; import uk.ac.starlink.ttools.task.InputTablesParameter; import uk.ac.starlink.ttools.task.MapEnvironment; import uk.ac.starlink.ttools.task.MultiOutputFormatParameter; import uk.ac.starlink.ttools.task.OutputFormatParameter; import uk.ac.starlink.ttools.task.OutputTableParameter; import uk.ac.starlink.ttools.task.OutputModeParameter; import uk.ac.starlink.util.DataSource; import uk.ac.starlink.util.LoadException; import uk.ac.starlink.util.ObjectFactory; /** * Writes a Jython module which facilitates use of STILTS functionality * from Jython. * The <code>main</code> method will write the jython source code * to standard output. * * @author Mark Taylor * @since 12 Feb 2010 */ public class JyStilts { private final Stilts stilts_; private final Formatter formatter_; private final Map clazzMap_; private final String[] imports_; private final Map paramAliasMap_; private static final String paramAliasDictName_ = "_param_alias_dict"; /** Java classes which are used by python source code. */ private static final Class[] IMPORT_CLASSES = new Class[] { java.io.ByteArrayInputStream.class, java.io.OutputStream.class, java.lang.Class.class, java.lang.System.class, java.lang.reflect.Array.class, java.util.ArrayList.class, uk.ac.starlink.table.ColumnInfo.class, uk.ac.starlink.table.MultiStarTableWriter.class, uk.ac.starlink.table.StarTable.class, uk.ac.starlink.table.StarTableFactory.class, uk.ac.starlink.table.StarTableOutput.class, uk.ac.starlink.table.TableSequence.class, uk.ac.starlink.table.WrapperStarTable.class, uk.ac.starlink.table.WrapperRowSequence.class, uk.ac.starlink.task.InvokeUtils.class, uk.ac.starlink.ttools.Stilts.class, uk.ac.starlink.ttools.filter.StepFactory.class, uk.ac.starlink.ttools.task.MapEnvironment.class, uk.ac.starlink.util.DataSource.class, }; /** * Constructor. * * @param stilts stilts instance defining available tasks etc */ public JyStilts( Stilts stilts ) { stilts_ = stilts; formatter_ = new Formatter(); /* Prepare python imports. */ clazzMap_ = new HashMap(); Class[] clazzes = IMPORT_CLASSES; List importList = new ArrayList(); importList.add( "import jarray.array" ); for ( int ic = 0; ic < clazzes.length; ic++ ) { Class clazz = clazzes[ ic ]; String clazzName = clazz.getName(); String importName = clazzName; importName = importName.replaceFirst( ".*\\.", "_" ); if ( clazzMap_.containsValue( importName ) ) { throw new RuntimeException( "import name clash: " + importName ); } clazzMap_.put( clazz, importName ); String line = "import " + clazzName; if ( ! importName.equals( clazzName ) ) { line += " as " + importName; } importList.add( line ); } /* Imports providing calculation static functions for use by users. */ Class[] calcClazzes = (Class[]) JELUtils.getStaticClasses().toArray( new Class[ 0 ] ); for ( int ic = 0; ic < calcClazzes.length; ic++ ) { Class clazz = calcClazzes[ ic ]; String clazzName = clazz.getName(); String importName = clazzName; importName = importName.replaceFirst( ".*\\.", "" ); if ( clazzMap_.containsValue( importName ) ) { throw new RuntimeException( "import name clash: " + importName ); } String line = "import " + clazzName + " as " + importName; importList.add( line ); } imports_ = (String[]) importList.toArray( new String[ 0 ] ); /* Some parameter names need to be aliased because they are python * reserved words. */ paramAliasMap_ = new HashMap(); paramAliasMap_.put( "in", "in_" ); } /** * Generates python source giving module header lines. * * @return python source code lines */ private String[] header() { return new String[] { "# This module auto-generated by java class " + getClass().getName() + ".", "", "'''Provides access to STILTS commands.", "", "See the manual, http://www.starlink.ac.uk/stilts/sun256/", "for tutorial and full usage information.", "'''", "", "from __future__ import generators", "__author__ = 'Mark Taylor'", "", }; } /** * Generates python source giving statements which * import java classes required for the rest of the python source * generated by this class. * * @return python source code lines */ private String[] imports() { return imports_; } /** * Returns the python name under which a given Java class has been * imported into python for use by this class. * * @param clazz java class * @return python name for <code>clazz</code> */ private String getImportName( Class clazz ) { String cname = (String) clazzMap_.get( clazz ); if ( cname == null ) { throw new IllegalArgumentException( "Class " + clazz.getName() + " not imported" ); } return cname; } /** * Generates python source defining utility functions. * * @return python source code lines */ private String[] defUtils() { List lineList = new ArrayList( Arrays.asList( new String[] { /* WrapperStarTable implementation which is a python container. */ "class RandomJyStarTable(JyStarTable):", " '''Extends the JyStarTable wrapper class for random access.", "", " Instances of this class can be subscripted.", " '''", " def __init__(self, base_table):", " JyStarTable.__init__(self, base_table)", " def __len__(self):", " return int(self.getRowCount())", " def __getitem__(self, key):", " if type(key) is type(slice(0)):", " return [self._create_row(self.getRow(irow))", " for irow in _slice_range(key, len(self))]", " elif key < 0:", " irow = self.getRowCount() + key", " return self._create_row(self.getRow(irow))", " else:", " return self._create_row(self.getRow(key))", " def __str__(self):", " return str(self.getName())" + " + '(' + str(self.getRowCount()) + 'x'" + " + str(self.getColumnCount()) + ')'", " def coldata(self, key):", " '''Returns a sequence of all the values" + " in a given column.'''", " icol = self._column_index(key)", " return _Coldata(self, icol)", "", "class _Coldata(object):", " def __init__(self, table, icol):", " self.table = table", " self.icol = icol", " self.nrow = len(table)", " def __iter__(self):", " rowseq = self.table.getRowSequence()", " while rowseq.next():", " yield rowseq.getCell(self.icol)", " def __len__(self):", " return self.nrow", " def __getitem__(self, key):", " if type(key) is type(slice(0)):", " return [self.table.getCell(irow, self.icol)", " for irow in _slice_range(key, self.nrow)]", " elif key < 0:", " irow = self.nrow + key", " return self.table.getCell(irow, self.icol)", " else:", " return self.table.getCell(key, self.icol)", "", /* Wrapper ColumnInfo implementation with some pythonic knobs on. */ "class _JyColumnInfo(" + getImportName( ColumnInfo.class ) + "):", " def __init__(self, base):", " " + getImportName( ColumnInfo.class ) + ".__init__(self, base)", " def __str__(self):", " return self.getName()", "", /* Wrapper row class. */ "class _JyRow(tuple):", " def __init__(self, array):", " tuple.__init__(self, array)", " def __getitem__(self, key):", " icol = self.table._column_index(key)", " return tuple.__getitem__(self, icol)", "", /* Execution environment implementation. */ "class _JyEnvironment(" + getImportName( MapEnvironment.class ) + "):", " def __init__(self, grab_output=False):", " " + getImportName( MapEnvironment.class ) + ".__init__(self)", " if grab_output:", " self._out = " + getImportName( MapEnvironment.class ) + ".getOutputStream(self)", " else:", " self._out = " + getImportName( System.class ) + ".out", " self._err = " + getImportName( System.class ) + ".err", " self._used = {}", " def getOutputStream(self):", " return self._out", " def getErrorStream(self):", " return self._err", " def acquireValue(self, param):", " " + getImportName( MapEnvironment.class ) + ".acquireValue(self, param)", " self._used[param.getName()] = True", " def getUnusedArgs(self):", " return filter(lambda n: n not in self._used," + " self.getNames())", "", /* Utility to raise an error if some args in the environment * were supplied but unused. */ "def _check_unused_args(env):", " names = env.getUnusedArgs()", " if (names):", " raise SyntaxError('Unused STILTS parameters %s' % " + "str(tuple([str(n) for n in names])))", "", /* Utility to raise an error if a handler can't write multiple * tables. */ "def _check_multi_handler(handler):", " if not " + getImportName( Class.class ) + ".forName('" + MultiStarTableWriter.class.getName() + "')" + ".isInstance(handler):", " raise TypeError('Handler %s cannot write multiple tables' " + "% handler.getFormatName())", "", /* Converts a slice into a range. */ "def _slice_range(slice, leng):", " start = slice.start", " stop = slice.stop", " step = slice.step", " if start is None:", " start = 0", " elif start < 0:", " start += leng", " if stop is None:", " stop = leng", " elif stop < 0:", " stop += leng", " if step is None:", " return xrange(start, stop)", " else:", " return xrange(start, stop, step)", "", /* OutputStream based on a python file. */ "class _JyOutputStream(" + getImportName( OutputStream.class ) + "):", " def __init__(self, file):", " self._file = file", " def write(self, *args):", " narg = len(args)", " if narg is 1:", " arg0 = args[0]", " if type(arg0) is type(1):", " pyarg = chr(arg0)", " else:", " pyarg = arg0", " elif narg is 3:", " buf, off, leng = args", " pyarg = buf[off:off + leng].tostring()", " else:", " raise SyntaxError('%d args?' % narg)", " self._file.write(pyarg)", " def close(self):", " self._file.close()", " def flush(self):", " self._file.flush()", "", /* TableSequence based on a python iterable. */ "class _JyTableSequence(" + getImportName( TableSequence.class ) + "):", " def __init__(self, seq):", " self._iter = iter(seq)", " self._advance()", " def _advance(self):", " try:", " self._nxt = self._iter.next()", " except StopIteration:", " self._nxt = None", " def hasNextTable(self):", " return self._nxt is not None", " def nextTable(self):", " nxt = self._nxt", " self._advance()", " return nxt", "", /* DataSource based on a python file. * This is not very efficient (it slurps up the whole file into * memory at construction time), but it's difficult to do it * correctly, at least without a lot of mucking about with * threads. */ "class _JyDataSource(" + getImportName( DataSource.class ) + "):", " def __init__(self, file):", " buf = file.read(-1)", " self._buffer = jarray.array(buf, 'b')", " if hasattr(file, 'name'):", " self.setName(file.name)", " def getRawInputStream(self):", " return " + getImportName( ByteArrayInputStream.class ) + "(self._buffer)", /* Returns a StarTable with suitable python decoration. */ "def import_star_table(table):", " '''Imports a StarTable instance for use with JyStilts.", "", " This factory function takes an instance of the Java class", " " + StarTable.class.getName(), " and returns an instance of a wrapper subclass which has some", " decorations useful in a python environment.", " This includes stilts cmd_* and mode_* methods, as well as", " python-friendly standard methods to make it behave as an", " iterable, and where possible a container, of data rows,", " and overloaded addition and multiplication operators", " with the semantics of concatenation.", " '''", " if table.isRandom():", " return RandomJyStarTable(table)", " else:", " return JyStarTable(table)", "", /* Takes a python value and returns a value suitable for passing * to a java Stilts execution environment. */ "def _map_env_value(pval):", " if pval is None:", " return None", " elif pval is True:", " return 'true'", " elif pval is False:", " return 'false'", " elif isinstance(pval, " + getImportName( StarTable.class ) + "):", " return pval", " elif _is_container(pval, " + getImportName( StarTable.class ) + "):", " return jarray.array(pval, " + getImportName( StarTable.class ) + ")", " else:", " return str(pval)", "", /* Utility method to determine if a python object can be treated * as a container. */ "def _is_container(value, type):", " try:", - " for item in value:", - " if not isinstance(item, type):", - " return False", - " return True", + " if len(value) > 0:", + " for item in value:", + " if not isinstance(item, type):", + " return False", + " return True", + " else:", + " return False", " except TypeError:", " return False", "", /* Stilts class instance. */ "_stilts = " + getImportName( Stilts.class ) + "()", "", /* Set up verbosity. */ getImportName( InvokeUtils.class ) + ".configureLogging(0, False)", "", } ) ); /* Creates and populates a dictionary mapping parameter names to * their aliases where appropriate. */ lineList.add( paramAliasDictName_ + " = {}" ); for ( Iterator it = paramAliasMap_.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); lineList.add( paramAliasDictName_ + "['" + entry.getKey() + "']='" + entry.getValue() + "'" ); } lineList.add( "" ); /* Return source line list array. */ return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Generates python source which checks version mismatches between the * module generated by this class and the runtime java library. * * @return python source code lines */ private String[] defVersionCheck() { return new String[] { "_stilts_lib_version = _stilts.getVersion()", "_stilts_script_version = '" + stilts_.getVersion() + "'", "if _stilts_lib_version != _stilts_script_version:", " print('WARNING: STILTS script/class library version mismatch" + " (' + _stilts_script_version + '/'" + " + _stilts_lib_version + ').')", " print(' This may or may not cause trouble.')", }; } /** * Generates python source defining a wrapper class for use with StarTables. * This can be applied to every StarTable generated by JyStilts * to provide additional functionality. * It supplies the various filters and modes as methods. * * @param cname class name * @return python source code lines */ private String[] defTableClass( String cname ) throws LoadException, SAXException { List lineList = new ArrayList(); lineList.add( "class " + cname + "(" + getImportName( WrapperStarTable.class ) + "):" ); /* Doc string. */ lineList.add( " '''StarTable wrapper class for use within Jython." ); lineList.add( "" ); lineList.add( "Decorates a " + StarTable.class.getName() ); lineList.add( "java object with methods for use within jython." ); lineList.add( "These include special bound functions to make it an" ); lineList.add( "iterable object (with items which are table rows)," ); lineList.add( "arithmetic + and * overloads for concatenation," ); lineList.add( "a write method for table viewing or output," ); lineList.add( "and methods representing STILTS filter functionality," ); lineList.add( "namely cmd_* methods for filters and mode_* methods" ); lineList.add( "for output modes." ); lineList.add( "" ); lineList.add( "As a general rule, any StarTable object which is" ); lineList.add( "intented for use by JyStilts program code should be" ); lineList.add( "wrapped in an instance of this class." ); lineList.add( " '''" ); /* Constructor. */ lineList.add( " def __init__(self, base_table):" ); lineList.add( " " + getImportName( WrapperStarTable.class ) + ".__init__(self, base_table)" ); /* Iterability. */ lineList.add( " def __iter__(self):" ); lineList.add( " rowseq = self.getRowSequence()" ); lineList.add( " while rowseq.next():" ); lineList.add( " yield self._create_row(rowseq.getRow())" ); /* String conversion. */ lineList.add( " def __str__(self):" ); lineList.add( " return '%s (?x%d)' % " + "(self.getName(), self.getColumnCount())" ); /* Overload add/multiply arithmetic operators with concatenation * semantics. */ lineList.add( " def __add__(self, other):" ); lineList.add( " return tcat([self, other])" ); lineList.add( " def __mul__(self, count):" ); lineList.add( " return tcat([self] * count)" ); lineList.add( " def __rmul__(self, count):" ); lineList.add( " return tcat([self] * count)" ); /* Add column tuple access method. */ lineList.add( " def columns(self):" ); lineList.add( " '''Returns a tuple of ColumnInfo objects" + " describing the columns of this table.'''" ); lineList.add( " if hasattr(self, '_columns'):" ); lineList.add( " return self._columns" ); lineList.add( " else:" ); lineList.add( " col_list = []" ); lineList.add( " for i in xrange(self.getColumnCount()):" ); lineList.add( " col_list.append(_JyColumnInfo(" + "self.getColumnInfo(i)))" ); lineList.add( " self._columns = tuple(col_list)" ); lineList.add( " return self.columns()" ); /* Add parameter dictionary access method. */ lineList.add( " def parameters(self):" ); lineList.add( " '''" ); lineList.add( "Returns a mapping of table parameter names to values." ); lineList.add( "" ); lineList.add( "This does not provide all the information " + "about the parameters," ); lineList.add( "for instance units and UCDs are not included." ); lineList.add( "For more detail, use the relevant StarTable methods." ); lineList.add( "Currently, this is not a live list, " + "in the sense that changing" ); lineList.add( "the returned dictionary will not affect " + "the table parameter values." ); lineList.add( " '''" ); lineList.add( " if hasattr(self, '_parameters'):" ); lineList.add( " return self._parameters" ); lineList.add( " else:" ); lineList.add( " params = {}" ); lineList.add( " for p in self.getParameters():" ); lineList.add( " params[p.getInfo().getName()]" + " = p.getValue()" ); lineList.add( " self._parameters = params" ); lineList.add( " return self.parameters()" ); /* Add column data extraction method. */ lineList.add( " def coldata(self, key):" ); lineList.add( " '''Returns a sequence of all the values " + "in a given column.'''" ); lineList.add( " icol = self._column_index(key)" ); lineList.add( " rowseq = self.getRowSequence()" ); lineList.add( " while rowseq.next():" ); lineList.add( " yield rowseq.getCell(icol)" ); /* Row wrapper. */ lineList.add( " def _create_row(self, array):" ); lineList.add( " row = _JyRow(array)" ); lineList.add( " row.table = self" ); lineList.add( " return row" ); /* Column subscripting. */ lineList.add( " def _column_index(self, key):" ); lineList.add( " if type(key) is type(1):" ); lineList.add( " if key >= 0:" ); lineList.add( " return key" ); lineList.add( " else:" ); lineList.add( " return key + self.getColumnCount()" ); lineList.add( " if hasattr(self, '_colmap'):" ); lineList.add( " return self._colmap[key]" ); lineList.add( " else:" ); lineList.add( " colmap = {}" ); lineList.add( " for ic, col in enumerate(self.columns()):" ); lineList.add( " if not col in colmap:" ); lineList.add( " colmap[col] = ic" ); lineList.add( " colname = col.getName()" ); lineList.add( " if not colname in colmap:" ); lineList.add( " colmap[colname] = ic" ); lineList.add( " self._colmap = colmap" ); lineList.add( " return self._column_index(key)" ); /* Add special write method. */ String[] writeLines = defWrite( "write", true ); lineList.addAll( Arrays.asList( prefixLines( " ", writeLines ) ) ); /* Add filters as methods. */ ObjectFactory filterFactory = StepFactory.getInstance().getFilterFactory(); String[] filterNames = filterFactory.getNickNames(); for ( int i = 0; i < filterNames.length; i++ ) { String name = filterNames[ i ]; String[] filterLines = defCmd( "cmd_" + name, name, true ); lineList.addAll( Arrays.asList( prefixLines( " ", filterLines ) ) ); } /* Add modes as methods. */ ObjectFactory modeFactory = stilts_.getModeFactory(); String[] modeNames = modeFactory.getNickNames(); for ( int i = 0; i < modeNames.length; i++ ) { String name = modeNames[ i ]; String[] modeLines = defMode( "mode_" + name, name, true ); lineList.addAll( Arrays.asList( prefixLines( " ", modeLines ) ) ); } /* Return the source code lines. */ return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Generates python source defining the table read function. * * @param fname name of function * @return python source code lines */ private String[] defRead( String fname ) { List lineList = new ArrayList(); lineList.add( "def " + fname + "(location, fmt='(auto)', random=False):" ); lineList.add( " '''Reads a table from a filename, URL or " + "python file object." ); lineList.add( "" ); lineList.add( " The random argument determines whether random " + "access is required" ); lineList.add( " for the table." ); lineList.add( " Setting it true may improve efficiency, " + "but perhaps at the cost" ); lineList.add( " of memory usage and load time for large tables." ); lineList.add( "" ); lineList.add( " The fmt argument must be supplied if " + "the table format cannot" ); lineList.add( " be auto-detected." ); lineList.add( "" ); lineList.add( " In general supplying a filename is preferred; " + "the current implementation" ); lineList.add( " may be much more expensive on memory " + "if a python file object is used." ); lineList.add( "" ); String fmtInfo = new InputFormatParameter( "location" ) .getExtraUsage( new MapEnvironment() ); lineList.addAll( Arrays.asList( prefixLines( " ", fmtInfo ) ) ); lineList.add( "" ); lineList.add( " The result of the function is a " + "JyStilts table object." ); lineList.add( " '''" ); lineList.add( " fact = " + getImportName( StarTableFactory.class ) + "(random)" ); lineList.add( " if hasattr(location, 'read'):" ); lineList.add( " datsrc = _JyDataSource(location)" ); lineList.add( " table = fact.makeStarTable(datsrc, fmt)" ); lineList.add( " else:" ); lineList.add( " table = fact.makeStarTable(location, fmt)" ); lineList.add( " return import_star_table(table)" ); return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Generates python source defining the multi-table read function. * * @param fname name of function * @return python source code lines */ private String[] defReads( String fname ) { List lineList = new ArrayList(); lineList.add( "def " + fname + "(location, fmt='(auto)', random=False):" ); lineList.add( " '''Reads multiple tables from a filename, URL or " + "python file object." ); lineList.add( "" ); lineList.add( " It only makes sense to use this function rather " + "than tread() if the" ); lineList.add( " format is, or may be, one which can contain " + "multiple tables." ); lineList.add( " Generally this means VOTable or FITS or one of " + "their variants." ); lineList.add( "" ); lineList.add( " The random argument determines whether random " + "access is required" ); lineList.add( " for the table." ); lineList.add( " Setting it true may improve efficiency, " + "but perhaps at the cost" ); lineList.add( " of memory usage and load time for large tables." ); lineList.add( "" ); lineList.add( " The fmt argument must be supplied if " + "the table format cannot" ); lineList.add( " be auto-detected." ); lineList.add( "" ); lineList.add( " In general supplying a filename is preferred; " + "the current implementation" ); lineList.add( " may be much more expensive on memory " + "if a python file object is used." ); lineList.add( "" ); lineList.add( " The result of the function is a list of JyStilts " + "table objects." ); lineList.add( " '''" ); lineList.add( " fact = " + getImportName( StarTableFactory.class ) + "(random)" ); lineList.add( " if hasattr(location, 'read'):" ); lineList.add( " datsrc = _JyDataSource(location)" ); lineList.add( " else:" ); lineList.add( " datsrc = " + getImportName( DataSource.class ) + ".makeDataSource(location)" ); lineList.add( " tables = fact.makeStarTables(datsrc, fmt)" ); lineList.add( " return map(import_star_table, tables)" ); return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Generates python source defining the table write function. * * @param fname name of function * @param isBound true for a bound method, false for a standalone function * @return python source code lines */ private String[] defWrite( String fname, boolean isBound ) { String tArgName = isBound ? "self" : "table"; List lineList = new ArrayList(); lineList.add( "def " + fname + "(" + tArgName + ", location=None, fmt='(auto)'):" ); lineList.add( " '''Writes table to a file." ); lineList.add( "" ); lineList.add( " The location parameter may give a filename or a" ); lineList.add( " python file object open for writing." ); lineList.add( " if it is not supplied, standard output is used." ); lineList.add( "" ); lineList.add( " The fmt parameter specifies output format." ); String fmtInfo = new OutputFormatParameter( "out" ) .getExtraUsage( new MapEnvironment() ); lineList.addAll( Arrays.asList( prefixLines( " ", fmtInfo ) ) ); lineList.add( " '''" ); lineList.add( " sto = " + getImportName( StarTableOutput.class ) + "()" ); lineList.add( " if hasattr(location, 'write') and " + "hasattr(location, 'flush'):" ); lineList.add( " ostrm = _JyOutputStream(location)" ); lineList.add( " name = getattr(location, 'name', None)" ); lineList.add( " handler = sto.getHandler(fmt, name)" ); lineList.add( " sto.writeStarTable(" + tArgName + ", ostrm, handler)" ); lineList.add( " else:" ); lineList.add( " if location is None:" ); lineList.add( " location = '-'" ); lineList.add( " sto.writeStarTable(" + tArgName + ", location, fmt)" ); return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Generates python source defining the multi-table write function. * * @param fname name of function * @return python source code lines */ private String[] defWrites( String fname ) { List lineList = new ArrayList(); lineList.add( "def " + fname + "(tables, location=None, fmt='(auto)'):" ); lineList.add( " '''Writes a sequence of tables " + "to a single container file." ); lineList.add( "" ); lineList.add( " The tables parameter gives an iterable over " + "JyStilts table objects" ); lineList.add( " The location parameter may give a filename " + "or a python file object" ); lineList.add( " open for writing. If it is not supplied, " + " standard output is used." ); lineList.add( "" ); lineList.add( " The fmt parameter specifies output format." ); lineList.add( " Note that not all formats can write multiple " + "tables;" ); lineList.add( " an error will result if an attempt is made " + "to write" ); lineList.add( " multiple tables to a single-table only format." ); String fmtInfo = new MultiOutputFormatParameter( "out" ) .getExtraUsage( new MapEnvironment() ); lineList.addAll( Arrays.asList( prefixLines( " ", fmtInfo ) ) ); lineList.add( " '''" ); lineList.add( " sto = " + getImportName( StarTableOutput.class ) + "()" ); lineList.add( " tseq = _JyTableSequence(tables)" ); lineList.add( " if hasattr(location, 'write') and " + "hasattr(location, 'flush'):" ); lineList.add( " ostrm = _JyOutputStream(location)" ); lineList.add( " name = getattr(location, 'name', None)" ); lineList.add( " handler = sto.getHandler(fmt, name)" ); lineList.add( " _check_multi_handler(handler)" ); lineList.add( " handler.writeStarTables(tseq, ostrm)" ); lineList.add( " else:" ); lineList.add( " if location is None:" ); lineList.add( " location = '-'" ); lineList.add( " handler = sto.getHandler(fmt, location)" ); lineList.add( " _check_multi_handler(handler)" ); lineList.add( " handler.writeStarTables(tseq, location, sto)" ); return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Generates python source defining the general table filter function. * * @param fname name of function * @return python source code lines */ private String[] defFilter( String fname ) { return new String[] { "def " + fname + "(table, cmd):", " '''Applies a filter operation to a table " + "and returns the result.", " In most cases, it's better to use one of the cmd_* functions.", " '''", " step = " + getImportName( StepFactory.class ) + ".getInstance().createStep(cmd)", " return import_star_table(step.wrap(table))", }; } /** * Generates python source defining a specific table filter function. * * @param fname name of function * @param filterNickName name under which the filter is known in the * filter ObjectFactory * @param isBound true for a bound method, false for a standalone function * @return python source code lines */ private String[] defCmd( String fname, String filterNickName, boolean isBound ) throws LoadException, SAXException { ProcessingFilter filter = (ProcessingFilter) StepFactory.getInstance() .getFilterFactory() .createObject( filterNickName ); String usage = filter.getUsage(); boolean hasUsage = usage != null && usage.trim().length() > 0; String tArgName = isBound ? "self" : "table"; List lineList = new ArrayList(); if ( hasUsage ) { lineList.add( "def " + fname + "(" + tArgName + ", *args):" ); } else { lineList.add( "def " + fname + "(" + tArgName + "):" ); } lineList.add( " '''\\" ); lineList.addAll( Arrays.asList( formatXml( filter .getDescription() ) ) ); lineList.add( "" ); lineList.add( "The filtered table is returned." ); if ( hasUsage ) { lineList.add( "" ); lineList.add( "args is a list with words as elements:" ); lineList.addAll( Arrays .asList( prefixLines( " ", filter.getUsage() ) ) ); } lineList.add( "'''" ); lineList.add( " pfilt = " + getImportName( StepFactory.class ) + ".getInstance()" + ".getFilterFactory()" + ".createObject(\"" + filterNickName + "\")" ); if ( hasUsage ) { lineList.add( " sargs = [str(a) for a in args]" ); } else { lineList.add( " sargs = []" ); } lineList.add( " argList = " + getImportName( ArrayList.class ) + "(sargs)" ); lineList.add( " step = pfilt.createStep(argList.iterator())" ); lineList.add( " return import_star_table(step.wrap(" + tArgName + "))" ); return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Generates python source defining an output mode function. * * @param fname name of function * @param modeNickName name under which the mode is known in the * mode ObjectFactory * @param isBound true for a bound method, false for a standalone function * @return python source code lines */ private String[] defMode( String fname, String modeNickName, boolean isBound ) throws LoadException, SAXException { ProcessingMode mode = (ProcessingMode) stilts_.getModeFactory() .createObject( modeNickName ); /* Assemble mandatory and optional parameters. */ Parameter[] params = mode.getAssociatedParameters(); List lineList = new ArrayList(); List mandArgList = new ArrayList(); List optArgList = new ArrayList(); for ( int ip = 0; ip < params.length; ip++ ) { Parameter param = params[ ip ]; String name = param.getName(); if ( paramAliasMap_.containsKey( name ) ) { param.setName( (String) paramAliasMap_.get( name ) ); } String pname = param.getName(); String sdflt = getDefaultString( param ); if ( sdflt == null ) { mandArgList.add( new Arg( param, pname ) ); } else { optArgList.add( new Arg( param, pname + "=" + sdflt ) ); } } /* Begin function definition. */ String tArgName = isBound ? "self" : "table"; List argList = new ArrayList(); argList.addAll( mandArgList ); argList.addAll( optArgList ); StringBuffer sbuf = new StringBuffer() .append( "def " ) .append( fname ) .append( "(" ) .append( tArgName ); for ( Iterator it = argList.iterator(); it.hasNext(); ) { Arg arg = (Arg) it.next(); sbuf.append( ", " ); sbuf.append( arg.formalArg_ ); } sbuf.append( "):" ); /* Add doc string. */ lineList.add( sbuf.toString() ); lineList.add( " '''\\" ); lineList.addAll( Arrays.asList( formatXml( mode.getDescription() ) ) ); lineList.addAll( Arrays.asList( getParamDocs( params ) ) ); lineList.add( "'''" ); /* Create and populate execution environment. */ lineList.add( " env = _JyEnvironment()" ); for ( Iterator it = argList.iterator(); it.hasNext(); ) { Arg arg = (Arg) it.next(); Parameter param = arg.param_; String name = param.getName(); lineList.add( " env.setValue('" + name + "', " + "_map_env_value(" + name + "))" ); } /* Create and invoke a suitable TableConsumer. */ lineList.add( " mode = _stilts" + ".getModeFactory()" + ".createObject('" + modeNickName + "')" ); lineList.add( " consumer = mode.createConsumer(env)" ); lineList.add( " _check_unused_args(env)" ); lineList.add( " consumer.consume(" + tArgName + ")" ); /* Return the source code lines. */ return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Generates python source defining a function for invoking a STILTS task. * * @param fname name of function * @param taskNickName name under which the task is known in the task * ObjectFactory * @return python source code lines */ private String[] defTask( String fname, String taskNickName ) throws LoadException, SAXException { Task task = (Task) stilts_.getTaskFactory().createObject( taskNickName ); boolean isConsumer = task instanceof ConsumerTask; boolean returnOutput = task instanceof Calc; List lineList = new ArrayList(); /* Get a list of the task parameters omitting those which we * don't want for jython purposes. */ List paramList = new ArrayList( Arrays.asList( task.getParameters() ) ); List shunnedList = new ArrayList(); for ( Iterator it = paramList.iterator(); it.hasNext(); ) { Parameter param = (Parameter) it.next(); if ( param instanceof AbstractInputTableParameter ) { shunnedList.add( ((AbstractInputTableParameter) param) .getStreamParameter() ); } if ( param instanceof InputTableParameter ) { param.setDescription( "<p>Input table.</p>" ); } else if ( param instanceof InputTablesParameter ) { param.setDescription( "<p>Array of input tables.</p>" ); } if ( param instanceof FilterParameter || param instanceof InputFormatParameter || param instanceof OutputFormatParameter || param instanceof OutputTableParameter || param instanceof OutputModeParameter ) { it.remove(); } } paramList.removeAll( shunnedList ); Parameter[] params = (Parameter[]) paramList.toArray( new Parameter[ 0 ] ); /* Get a list of mandatory and optional parameters which we will * declare as part of the python function definition. * Currently, we refrain from declaring most of the optional * arguments, preferring to use just a catch-all **kwargs. * This is because a few of the parameters declared by a Stilts * task are dummies of one kind or another, so declaring them * is problematic and/or confusing. * The ones we do declare are the positional arguments, which * tends to be just a few non-problematic an mandatory ones, * as well as any which have had their names aliased, so that * this is clear from the documentation. */ List mandArgList = new ArrayList(); List optArgList = new ArrayList(); int iPos = 0; for ( int ip = 0; ip < params.length; ip++ ) { Parameter param = params[ ip ]; String name = param.getName(); if ( paramAliasMap_.containsKey( name ) ) { param.setName( (String) paramAliasMap_.get( name ) ); } String pname = param.getName(); boolean byPos = false; int pos = param.getPosition(); if ( pos > 0 ) { iPos++; assert pos == iPos; byPos = true; } if ( byPos || paramAliasMap_.containsKey( name ) ) { String sdflt = getDefaultString( param ); if ( sdflt == null ) { mandArgList.add( new Arg( param, pname ) ); } else { optArgList.add( new Arg( param, pname + "=" + sdflt ) ); } } } /* Begin the function definition. */ List argList = new ArrayList(); argList.addAll( mandArgList ); argList.addAll( optArgList ); StringBuffer sbuf = new StringBuffer() .append( "def " ) .append( fname ) .append( "(" ); for ( Iterator it = argList.iterator(); it.hasNext(); ) { Arg arg = (Arg) it.next(); sbuf.append( arg.formalArg_ ) .append( ", " ); } sbuf.append( "**kwargs" ) .append( "):" ); lineList.add( sbuf.toString() ); /* Write the doc string. */ lineList.add( " '''\\" ); lineList.add( task.getPurpose() + "." ); if ( isConsumer ) { lineList.add( "" ); lineList.add( "The return value is the resulting table." ); } else if ( returnOutput ) { lineList.add( "" ); lineList.add( "The return value is the output string." ); } lineList.addAll( Arrays.asList( getParamDocs( params ) ) ); lineList.add( "'''" ); /* Create the task object. */ if ( isConsumer ) { /* If the task is a ConsumerTask, use an instance of a subclass * of the relevant Task class (the relevant classes all happen * to have suitable no-arg constructors). This is a hack to * permit access to the createProducer method, which has * protected access in the ConsumerTask interface (at least * in some stilts versions). */ Class taskClazz = task.getClass(); String taskClazzName = taskClazz.getName(); String taskSubName = "_" + fname + "_task"; lineList.add( " import " + taskClazzName ); lineList.add( " class " + taskSubName + "(" + taskClazzName + "):" ); lineList.add( " def __init__(self):" ); lineList.add( " " + taskClazzName + ".__init__(self)" ); lineList.add( " task = " + taskSubName + "()" ); } else { /* Do it the simple, and more respectable way, if the hack * is not required. */ lineList.add( " task = _stilts" + ".getTaskFactory()" + ".createObject('" + taskNickName + "')" ); } /* Rename parameters as required. */ lineList.add( " for param in task.getParameters():" ); lineList.add( " pname = param.getName()" ); lineList.add( " if pname in " + paramAliasDictName_ + ":" ); lineList.add( " param.setName(" + paramAliasDictName_ + "[pname])" ); /* Create the stilts execution environment. */ if ( returnOutput ) { lineList.add( " env = _JyEnvironment(grab_output=True)" ); } else { lineList.add( " env = _JyEnvironment()" ); } /* Populate the environment from the mandatory and optional arguments * of the python function. */ for ( Iterator it = mandArgList.iterator(); it.hasNext(); ) { Arg arg = (Arg) it.next(); Parameter param = arg.param_; String name = param.getName(); lineList.add( " env.setValue('" + name + "', " + "_map_env_value(" + name + "))" ); } lineList.add( " for kw in kwargs.iteritems():" ); lineList.add( " key = kw[0]" ); lineList.add( " value = kw[1]" ); lineList.add( " env.setValue(key, _map_env_value(value))" ); /* For a consumer task, create a result table and return it. */ if ( isConsumer ) { lineList.add( " table = task.createProducer(env).getTable()" ); lineList.add( " _check_unused_args(env)" ); lineList.add( " return import_star_table(table)" ); } /* Otherwise execute the task in the usual way. */ else { lineList.add( " exe = task.createExecutable(env)" ); lineList.add( " _check_unused_args(env)" ); lineList.add( " exe.execute()" ); /* If we're returning the output text, retrieve it from the * environment, tidy it up, and return it. Otherwise, the * return is None. */ if ( returnOutput ) { lineList.add( " txt = env.getOutputText()" ); lineList.add( " return str(txt.strip())" ); } } /* Return the source code lines. */ return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Returns the python-optional-argument-type default value string for * a parameter. May be null in the case that the argument must be * supplied. * * @param param STILTS parameter * @param default value, suitable for insertion into python source */ private String getDefaultString( Parameter param ) { String dflt = param.getDefault(); boolean isDfltNull = dflt == null || dflt.trim().length() == 0; boolean nullable = param.isNullPermitted(); if ( nullable || ! isDfltNull ) { if ( isDfltNull ) { return "None"; } else if ( param instanceof IntegerParameter || param instanceof DoubleParameter ) { return dflt; } else { return "'" + dflt + "'"; } } else { return null; } } /** * Formats XML text for output to python source, to be inserted * within string literal quotes. * * @param xml xml text * @return python source code lines for string literal content */ private String[] formatXml( String xml ) throws SAXException { /* Shorten the lines by csub characters, so they don't overrun when * formatted with indentation by python help. */ int csub = 8; String text = formatter_.formatXML( xml, csub ); List lineList = new ArrayList(); for ( Iterator lineIt = lineIterator( text ); lineIt.hasNext(); ) { String line = (String) lineIt.next(); if ( line.trim().length() == 0 ) { lineList.add( "" ); } else { assert " ".equals( line.substring( 0, csub ) ); lineList.add( line.substring( csub ) ); } } return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Returns documentation for an array of parameters suitable for * insertion into a python literal doc string. * * @param params parameters to document * @return lines of doc text */ private String[] getParamDocs( Parameter[] params ) throws SAXException { if ( params.length == 0 ) { return new String[ 0 ]; } List lineList = new ArrayList(); lineList.add( "" ); lineList.add( "Parameters:" ); StringBuffer sbuf = new StringBuffer(); sbuf.append( "<dl>" ); for ( int i = 0; i < params.length; i++ ) { sbuf.append( UsageWriter.xmlItem( params[ i ] ) ); } sbuf.append( "</dl>" ); lineList.addAll( Arrays.asList( formatXml( sbuf.toString() ) ) ); return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Add a fixed prefix to each line of an input string. * * @param prefix per-line prefix * @param text text block, with lines terminated by newline characters * @return python source code lines for string literal content */ private String[] prefixLines( String prefix, String text ) { List lineList = new ArrayList(); for ( Iterator lineIt = lineIterator( text ); lineIt.hasNext(); ) { lineList.add( prefix + (String) lineIt.next() ); } return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Adds a fixed prefix to each element of a string array. * * @param prefix per-line prefix * @param lines input line array * @return output line array */ private String[] prefixLines( String prefix, String[] lines ) { List lineList = new ArrayList(); for ( int i = 0; i < lines.length; i++ ) { lineList.add( prefix + lines[ i ] ); } return (String[]) lineList.toArray( new String[ 0 ] ); } /** * Outputs an array of lines through a writer. * * @param lines line array * @param writer destination stream */ private void writeLines( String[] lines, Writer writer ) throws IOException { BufferedWriter bw = new BufferedWriter( writer ); for ( int i = 0; i < lines.length; i++ ) { bw.write( lines[ i ] ); bw.newLine(); } bw.newLine(); bw.flush(); } /** * Outputs the python source code for the stilts module. * * @param writer destination stream */ public void writeModule( Writer writer ) throws IOException, LoadException, SAXException { writeLines( header(), writer ); writeLines( imports(), writer ); writeLines( defTableClass( "JyStarTable" ), writer ); writeLines( defUtils(), writer ); writeLines( defVersionCheck(), writer ); writeLines( defRead( "tread" ), writer ); writeLines( defReads( "treads" ), writer ); writeLines( defWrite( "twrite", false ), writer ); writeLines( defWrites( "twrites" ), writer ); writeLines( defFilter( "tfilter" ), writer ); /* Write task wrappers. */ ObjectFactory taskFactory = stilts_.getTaskFactory(); String[] taskNames = taskFactory.getNickNames(); for ( int i = 0; i < taskNames.length; i++ ) { String name = taskNames[ i ]; String[] taskLines = defTask( name, name ); writeLines( taskLines, writer ); } /* Write filter wrappers. */ ObjectFactory filterFactory = StepFactory.getInstance().getFilterFactory(); String[] filterNames = filterFactory.getNickNames(); for ( int i = 0; i < filterNames.length; i++ ) { String name = filterNames[ i ]; String[] filterLines = defCmd( "cmd_" + name, name, false ); writeLines( filterLines, writer ); } /* Write mode wrappers. */ ObjectFactory modeFactory = stilts_.getModeFactory(); String[] modeNames = modeFactory.getNickNames(); for ( int i = 0; i < modeNames.length; i++ ) { String name = modeNames[ i ]; String[] modeLines = defMode( "mode_" + name, name, false ); writeLines( modeLines, writer ); } } /** * Writes jython source code for a <code>stilts.py</code> module * to standard output. * No arguments. */ public static void main( String[] args ) throws IOException, LoadException, SAXException { new JyStilts( new Stilts() ) .writeModule( new OutputStreamWriter( new BufferedOutputStream( System.out ) ) ); } /** * Convenience class which aggregates a parameter and its string * representation in a python function definition formal parameter * list. */ private static class Arg { final Parameter param_; final String formalArg_; Arg( Parameter param, String formalArg ) { param_ = param; formalArg_ = formalArg; } } /** * Returns an iterator over newline-separated lines in a string. * Unlike using StringTokenizer, empty lines will be included in * the output. * * @param text input text * @return iterator over lines */ private static Iterator lineIterator( final String text ) { return new Iterator() { private int pos_; public boolean hasNext() { return pos_ < text.length(); } public Object next() { int nextPos = text.indexOf( '\n', pos_ ); if ( nextPos < 0 ) { nextPos = text.length(); } String line = text.substring( pos_, nextPos ); pos_ = nextPos + 1; return line; } public void remove() { throw new UnsupportedOperationException(); } }; } /** * Adapter to turn an OutputStream into a Writer. * Any attempt to write a non-ASCII character generates an IOException. */ private static class OutputStreamWriter extends Writer { private final OutputStream out_; /** * Constructor. * * @param out destination stream */ OutputStreamWriter( OutputStream out ) { out_ = out; } public void write( char[] cbuf, int off, int len ) throws IOException { byte[] buf = new byte[ len ]; for ( int i = 0; i < len; i++ ) { buf[ i ] = toByte( cbuf[ off + i ] ); } out_.write( buf, 0, len ); } public void write( int c ) throws IOException { out_.write( toByte( (char) c ) ); } public void flush() throws IOException { out_.flush(); } public void close() throws IOException { out_.close(); } /** * Turns a char into a byte, throwing an exception in case of * narrowing issues. * * @param c character * @return equivalent ASCII byte */ private byte toByte( char c ) throws IOException { if ( c >= 0 && c <= 127 ) { return (byte) c; } else { throw new IOException( "Non-ASCII character 0x" + Integer.toHexString( (int) c ) ); } } } }
true
true
private String[] defUtils() { List lineList = new ArrayList( Arrays.asList( new String[] { /* WrapperStarTable implementation which is a python container. */ "class RandomJyStarTable(JyStarTable):", " '''Extends the JyStarTable wrapper class for random access.", "", " Instances of this class can be subscripted.", " '''", " def __init__(self, base_table):", " JyStarTable.__init__(self, base_table)", " def __len__(self):", " return int(self.getRowCount())", " def __getitem__(self, key):", " if type(key) is type(slice(0)):", " return [self._create_row(self.getRow(irow))", " for irow in _slice_range(key, len(self))]", " elif key < 0:", " irow = self.getRowCount() + key", " return self._create_row(self.getRow(irow))", " else:", " return self._create_row(self.getRow(key))", " def __str__(self):", " return str(self.getName())" + " + '(' + str(self.getRowCount()) + 'x'" + " + str(self.getColumnCount()) + ')'", " def coldata(self, key):", " '''Returns a sequence of all the values" + " in a given column.'''", " icol = self._column_index(key)", " return _Coldata(self, icol)", "", "class _Coldata(object):", " def __init__(self, table, icol):", " self.table = table", " self.icol = icol", " self.nrow = len(table)", " def __iter__(self):", " rowseq = self.table.getRowSequence()", " while rowseq.next():", " yield rowseq.getCell(self.icol)", " def __len__(self):", " return self.nrow", " def __getitem__(self, key):", " if type(key) is type(slice(0)):", " return [self.table.getCell(irow, self.icol)", " for irow in _slice_range(key, self.nrow)]", " elif key < 0:", " irow = self.nrow + key", " return self.table.getCell(irow, self.icol)", " else:", " return self.table.getCell(key, self.icol)", "", /* Wrapper ColumnInfo implementation with some pythonic knobs on. */ "class _JyColumnInfo(" + getImportName( ColumnInfo.class ) + "):", " def __init__(self, base):", " " + getImportName( ColumnInfo.class ) + ".__init__(self, base)", " def __str__(self):", " return self.getName()", "", /* Wrapper row class. */ "class _JyRow(tuple):", " def __init__(self, array):", " tuple.__init__(self, array)", " def __getitem__(self, key):", " icol = self.table._column_index(key)", " return tuple.__getitem__(self, icol)", "", /* Execution environment implementation. */ "class _JyEnvironment(" + getImportName( MapEnvironment.class ) + "):", " def __init__(self, grab_output=False):", " " + getImportName( MapEnvironment.class ) + ".__init__(self)", " if grab_output:", " self._out = " + getImportName( MapEnvironment.class ) + ".getOutputStream(self)", " else:", " self._out = " + getImportName( System.class ) + ".out", " self._err = " + getImportName( System.class ) + ".err", " self._used = {}", " def getOutputStream(self):", " return self._out", " def getErrorStream(self):", " return self._err", " def acquireValue(self, param):", " " + getImportName( MapEnvironment.class ) + ".acquireValue(self, param)", " self._used[param.getName()] = True", " def getUnusedArgs(self):", " return filter(lambda n: n not in self._used," + " self.getNames())", "", /* Utility to raise an error if some args in the environment * were supplied but unused. */ "def _check_unused_args(env):", " names = env.getUnusedArgs()", " if (names):", " raise SyntaxError('Unused STILTS parameters %s' % " + "str(tuple([str(n) for n in names])))", "", /* Utility to raise an error if a handler can't write multiple * tables. */ "def _check_multi_handler(handler):", " if not " + getImportName( Class.class ) + ".forName('" + MultiStarTableWriter.class.getName() + "')" + ".isInstance(handler):", " raise TypeError('Handler %s cannot write multiple tables' " + "% handler.getFormatName())", "", /* Converts a slice into a range. */ "def _slice_range(slice, leng):", " start = slice.start", " stop = slice.stop", " step = slice.step", " if start is None:", " start = 0", " elif start < 0:", " start += leng", " if stop is None:", " stop = leng", " elif stop < 0:", " stop += leng", " if step is None:", " return xrange(start, stop)", " else:", " return xrange(start, stop, step)", "", /* OutputStream based on a python file. */ "class _JyOutputStream(" + getImportName( OutputStream.class ) + "):", " def __init__(self, file):", " self._file = file", " def write(self, *args):", " narg = len(args)", " if narg is 1:", " arg0 = args[0]", " if type(arg0) is type(1):", " pyarg = chr(arg0)", " else:", " pyarg = arg0", " elif narg is 3:", " buf, off, leng = args", " pyarg = buf[off:off + leng].tostring()", " else:", " raise SyntaxError('%d args?' % narg)", " self._file.write(pyarg)", " def close(self):", " self._file.close()", " def flush(self):", " self._file.flush()", "", /* TableSequence based on a python iterable. */ "class _JyTableSequence(" + getImportName( TableSequence.class ) + "):", " def __init__(self, seq):", " self._iter = iter(seq)", " self._advance()", " def _advance(self):", " try:", " self._nxt = self._iter.next()", " except StopIteration:", " self._nxt = None", " def hasNextTable(self):", " return self._nxt is not None", " def nextTable(self):", " nxt = self._nxt", " self._advance()", " return nxt", "", /* DataSource based on a python file. * This is not very efficient (it slurps up the whole file into * memory at construction time), but it's difficult to do it * correctly, at least without a lot of mucking about with * threads. */ "class _JyDataSource(" + getImportName( DataSource.class ) + "):", " def __init__(self, file):", " buf = file.read(-1)", " self._buffer = jarray.array(buf, 'b')", " if hasattr(file, 'name'):", " self.setName(file.name)", " def getRawInputStream(self):", " return " + getImportName( ByteArrayInputStream.class ) + "(self._buffer)", /* Returns a StarTable with suitable python decoration. */ "def import_star_table(table):", " '''Imports a StarTable instance for use with JyStilts.", "", " This factory function takes an instance of the Java class", " " + StarTable.class.getName(), " and returns an instance of a wrapper subclass which has some", " decorations useful in a python environment.", " This includes stilts cmd_* and mode_* methods, as well as", " python-friendly standard methods to make it behave as an", " iterable, and where possible a container, of data rows,", " and overloaded addition and multiplication operators", " with the semantics of concatenation.", " '''", " if table.isRandom():", " return RandomJyStarTable(table)", " else:", " return JyStarTable(table)", "", /* Takes a python value and returns a value suitable for passing * to a java Stilts execution environment. */ "def _map_env_value(pval):", " if pval is None:", " return None", " elif pval is True:", " return 'true'", " elif pval is False:", " return 'false'", " elif isinstance(pval, " + getImportName( StarTable.class ) + "):", " return pval", " elif _is_container(pval, " + getImportName( StarTable.class ) + "):", " return jarray.array(pval, " + getImportName( StarTable.class ) + ")", " else:", " return str(pval)", "", /* Utility method to determine if a python object can be treated * as a container. */ "def _is_container(value, type):", " try:", " for item in value:", " if not isinstance(item, type):", " return False", " return True", " except TypeError:", " return False", "", /* Stilts class instance. */ "_stilts = " + getImportName( Stilts.class ) + "()", "", /* Set up verbosity. */ getImportName( InvokeUtils.class ) + ".configureLogging(0, False)", "", } ) ); /* Creates and populates a dictionary mapping parameter names to * their aliases where appropriate. */ lineList.add( paramAliasDictName_ + " = {}" ); for ( Iterator it = paramAliasMap_.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); lineList.add( paramAliasDictName_ + "['" + entry.getKey() + "']='" + entry.getValue() + "'" ); } lineList.add( "" ); /* Return source line list array. */ return (String[]) lineList.toArray( new String[ 0 ] ); }
private String[] defUtils() { List lineList = new ArrayList( Arrays.asList( new String[] { /* WrapperStarTable implementation which is a python container. */ "class RandomJyStarTable(JyStarTable):", " '''Extends the JyStarTable wrapper class for random access.", "", " Instances of this class can be subscripted.", " '''", " def __init__(self, base_table):", " JyStarTable.__init__(self, base_table)", " def __len__(self):", " return int(self.getRowCount())", " def __getitem__(self, key):", " if type(key) is type(slice(0)):", " return [self._create_row(self.getRow(irow))", " for irow in _slice_range(key, len(self))]", " elif key < 0:", " irow = self.getRowCount() + key", " return self._create_row(self.getRow(irow))", " else:", " return self._create_row(self.getRow(key))", " def __str__(self):", " return str(self.getName())" + " + '(' + str(self.getRowCount()) + 'x'" + " + str(self.getColumnCount()) + ')'", " def coldata(self, key):", " '''Returns a sequence of all the values" + " in a given column.'''", " icol = self._column_index(key)", " return _Coldata(self, icol)", "", "class _Coldata(object):", " def __init__(self, table, icol):", " self.table = table", " self.icol = icol", " self.nrow = len(table)", " def __iter__(self):", " rowseq = self.table.getRowSequence()", " while rowseq.next():", " yield rowseq.getCell(self.icol)", " def __len__(self):", " return self.nrow", " def __getitem__(self, key):", " if type(key) is type(slice(0)):", " return [self.table.getCell(irow, self.icol)", " for irow in _slice_range(key, self.nrow)]", " elif key < 0:", " irow = self.nrow + key", " return self.table.getCell(irow, self.icol)", " else:", " return self.table.getCell(key, self.icol)", "", /* Wrapper ColumnInfo implementation with some pythonic knobs on. */ "class _JyColumnInfo(" + getImportName( ColumnInfo.class ) + "):", " def __init__(self, base):", " " + getImportName( ColumnInfo.class ) + ".__init__(self, base)", " def __str__(self):", " return self.getName()", "", /* Wrapper row class. */ "class _JyRow(tuple):", " def __init__(self, array):", " tuple.__init__(self, array)", " def __getitem__(self, key):", " icol = self.table._column_index(key)", " return tuple.__getitem__(self, icol)", "", /* Execution environment implementation. */ "class _JyEnvironment(" + getImportName( MapEnvironment.class ) + "):", " def __init__(self, grab_output=False):", " " + getImportName( MapEnvironment.class ) + ".__init__(self)", " if grab_output:", " self._out = " + getImportName( MapEnvironment.class ) + ".getOutputStream(self)", " else:", " self._out = " + getImportName( System.class ) + ".out", " self._err = " + getImportName( System.class ) + ".err", " self._used = {}", " def getOutputStream(self):", " return self._out", " def getErrorStream(self):", " return self._err", " def acquireValue(self, param):", " " + getImportName( MapEnvironment.class ) + ".acquireValue(self, param)", " self._used[param.getName()] = True", " def getUnusedArgs(self):", " return filter(lambda n: n not in self._used," + " self.getNames())", "", /* Utility to raise an error if some args in the environment * were supplied but unused. */ "def _check_unused_args(env):", " names = env.getUnusedArgs()", " if (names):", " raise SyntaxError('Unused STILTS parameters %s' % " + "str(tuple([str(n) for n in names])))", "", /* Utility to raise an error if a handler can't write multiple * tables. */ "def _check_multi_handler(handler):", " if not " + getImportName( Class.class ) + ".forName('" + MultiStarTableWriter.class.getName() + "')" + ".isInstance(handler):", " raise TypeError('Handler %s cannot write multiple tables' " + "% handler.getFormatName())", "", /* Converts a slice into a range. */ "def _slice_range(slice, leng):", " start = slice.start", " stop = slice.stop", " step = slice.step", " if start is None:", " start = 0", " elif start < 0:", " start += leng", " if stop is None:", " stop = leng", " elif stop < 0:", " stop += leng", " if step is None:", " return xrange(start, stop)", " else:", " return xrange(start, stop, step)", "", /* OutputStream based on a python file. */ "class _JyOutputStream(" + getImportName( OutputStream.class ) + "):", " def __init__(self, file):", " self._file = file", " def write(self, *args):", " narg = len(args)", " if narg is 1:", " arg0 = args[0]", " if type(arg0) is type(1):", " pyarg = chr(arg0)", " else:", " pyarg = arg0", " elif narg is 3:", " buf, off, leng = args", " pyarg = buf[off:off + leng].tostring()", " else:", " raise SyntaxError('%d args?' % narg)", " self._file.write(pyarg)", " def close(self):", " self._file.close()", " def flush(self):", " self._file.flush()", "", /* TableSequence based on a python iterable. */ "class _JyTableSequence(" + getImportName( TableSequence.class ) + "):", " def __init__(self, seq):", " self._iter = iter(seq)", " self._advance()", " def _advance(self):", " try:", " self._nxt = self._iter.next()", " except StopIteration:", " self._nxt = None", " def hasNextTable(self):", " return self._nxt is not None", " def nextTable(self):", " nxt = self._nxt", " self._advance()", " return nxt", "", /* DataSource based on a python file. * This is not very efficient (it slurps up the whole file into * memory at construction time), but it's difficult to do it * correctly, at least without a lot of mucking about with * threads. */ "class _JyDataSource(" + getImportName( DataSource.class ) + "):", " def __init__(self, file):", " buf = file.read(-1)", " self._buffer = jarray.array(buf, 'b')", " if hasattr(file, 'name'):", " self.setName(file.name)", " def getRawInputStream(self):", " return " + getImportName( ByteArrayInputStream.class ) + "(self._buffer)", /* Returns a StarTable with suitable python decoration. */ "def import_star_table(table):", " '''Imports a StarTable instance for use with JyStilts.", "", " This factory function takes an instance of the Java class", " " + StarTable.class.getName(), " and returns an instance of a wrapper subclass which has some", " decorations useful in a python environment.", " This includes stilts cmd_* and mode_* methods, as well as", " python-friendly standard methods to make it behave as an", " iterable, and where possible a container, of data rows,", " and overloaded addition and multiplication operators", " with the semantics of concatenation.", " '''", " if table.isRandom():", " return RandomJyStarTable(table)", " else:", " return JyStarTable(table)", "", /* Takes a python value and returns a value suitable for passing * to a java Stilts execution environment. */ "def _map_env_value(pval):", " if pval is None:", " return None", " elif pval is True:", " return 'true'", " elif pval is False:", " return 'false'", " elif isinstance(pval, " + getImportName( StarTable.class ) + "):", " return pval", " elif _is_container(pval, " + getImportName( StarTable.class ) + "):", " return jarray.array(pval, " + getImportName( StarTable.class ) + ")", " else:", " return str(pval)", "", /* Utility method to determine if a python object can be treated * as a container. */ "def _is_container(value, type):", " try:", " if len(value) > 0:", " for item in value:", " if not isinstance(item, type):", " return False", " return True", " else:", " return False", " except TypeError:", " return False", "", /* Stilts class instance. */ "_stilts = " + getImportName( Stilts.class ) + "()", "", /* Set up verbosity. */ getImportName( InvokeUtils.class ) + ".configureLogging(0, False)", "", } ) ); /* Creates and populates a dictionary mapping parameter names to * their aliases where appropriate. */ lineList.add( paramAliasDictName_ + " = {}" ); for ( Iterator it = paramAliasMap_.entrySet().iterator(); it.hasNext(); ) { Map.Entry entry = (Map.Entry) it.next(); lineList.add( paramAliasDictName_ + "['" + entry.getKey() + "']='" + entry.getValue() + "'" ); } lineList.add( "" ); /* Return source line list array. */ return (String[]) lineList.toArray( new String[ 0 ] ); }
diff --git a/src/main/java/com/feedme/activity/EditChildActivity.java b/src/main/java/com/feedme/activity/EditChildActivity.java index d22e2d2..556863e 100644 --- a/src/main/java/com/feedme/activity/EditChildActivity.java +++ b/src/main/java/com/feedme/activity/EditChildActivity.java @@ -1,217 +1,217 @@ package com.feedme.activity; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.*; import com.feedme.R; import com.feedme.dao.BabyDao; import com.feedme.model.Baby; import java.util.Calendar; import java.util.List; /** * User: dayel.ostraco * Date: 1/16/12 * Time: 12:27 PM */ public class EditChildActivity extends ChildActivity { private Button babyDob; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_child); final BabyDao babyDao = new BabyDao(getApplicationContext()); final Baby editBaby = (Baby) getIntent().getSerializableExtra("baby"); styleActivity(editBaby.getSex()); TextView addChild = (TextView) findViewById(R.id.addChild); addChild.setText("Edit Baby"); final EditText babyName = (EditText) findViewById(R.id.babyName); final Spinner babySex = (Spinner) findViewById(R.id.babySex); final EditText babyHeight = (EditText) findViewById(R.id.babyHeight); final EditText babyWeight = (EditText) findViewById(R.id.babyWeight); Button addChildButton = (Button) findViewById(R.id.addChildButton); Button takePicture = (Button) findViewById(R.id.takePicture); Button selectPicture = (Button) findViewById(R.id.pickPicture); babyName.setText(editBaby.getName()); babyHeight.setText(editBaby.getHeight()); babyWeight.setText(editBaby.getWeight()); babyDob = (Button) findViewById(R.id.babyDob); babyDob.setText(editBaby.getDob()); // add a click listener to the button babyDob.setOnClickListener(showDateDialog()); // get the current date final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); // display the current date //updateDateDisplay(); //populate male/female spinner ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.babySex, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner s = (Spinner) findViewById(R.id.babySex); s.setAdapter(adapter); //Set Spinner Value for Baby Sex if (editBaby.getSex().equals("Male")) { babySex.setSelection(0); } else { babySex.setSelection(1); } //Take Picture Button takePicture.setOnClickListener(takePictureListener(editBaby, EDIT_CHILD_ACTIVITY_ID)); //Select Picture Button selectPicture.setOnClickListener(selectPictureListener(editBaby, EDIT_CHILD_ACTIVITY_ID)); //declare alert dialog final AlertDialog alertDialog = new AlertDialog.Builder(this).create(); // button listener for add child button addChildButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //if name, weight, and height aren't filled out, throw an alert if (babyName.getText().toString().equals("") || babyHeight.getText().toString().equals("") || babyWeight.getText().toString().equals("")) { alertDialog.setTitle("Oops!"); alertDialog.setMessage("Please fill out the form completely."); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else { // else add child to database String picturePath = ""; if (getIntent().getExtras() != null && getIntent().getExtras().get("picturePath") != null) { - picturePath = getIntent().getExtras().getString("picturePath"); + editBaby.setPicturePath(getIntent().getExtras().getString("picturePath")); } Log.d("UPDATE: ", "Updating .."); Baby updateBaby = new Baby(editBaby.getID(), babyName.getText().toString(), babySex.getSelectedItem().toString(), babyHeight.getText().toString(), babyWeight.getText().toString(), babyDob.getText().toString(), - picturePath); + editBaby.getPicturePath()); babyDao.updateBaby(updateBaby, editBaby.getID()); Intent intent = new Intent(v.getContext(), ViewBabyActivity.class); Bundle b = new Bundle(); b.putSerializable("baby", updateBaby); intent.putExtras(b); startActivityForResult(intent, 3); } } }); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DATE_DIALOG_ID: return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null; } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.home: startActivity(new Intent(EditChildActivity.this, HomeActivity.class)); break; case R.id.settings: startActivity(new Intent(EditChildActivity.this, SettingsActivity.class)); break; case R.id.report: startActivity(new Intent(EditChildActivity.this, ReportBugActivity.class)); break; } return true; } // updates the date we display in the TextView private void updateDateDisplay() { babyDob.setText( new StringBuilder() // Month is 0 based so add 1 .append(mMonth + 1).append("-") .append(mDay).append("-") .append(mYear).append(" ")); } // the callback received when the user "sets" the date in the dialog private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year; mMonth = monthOfYear; mDay = dayOfMonth; updateDateDisplay(); } }; }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_child); final BabyDao babyDao = new BabyDao(getApplicationContext()); final Baby editBaby = (Baby) getIntent().getSerializableExtra("baby"); styleActivity(editBaby.getSex()); TextView addChild = (TextView) findViewById(R.id.addChild); addChild.setText("Edit Baby"); final EditText babyName = (EditText) findViewById(R.id.babyName); final Spinner babySex = (Spinner) findViewById(R.id.babySex); final EditText babyHeight = (EditText) findViewById(R.id.babyHeight); final EditText babyWeight = (EditText) findViewById(R.id.babyWeight); Button addChildButton = (Button) findViewById(R.id.addChildButton); Button takePicture = (Button) findViewById(R.id.takePicture); Button selectPicture = (Button) findViewById(R.id.pickPicture); babyName.setText(editBaby.getName()); babyHeight.setText(editBaby.getHeight()); babyWeight.setText(editBaby.getWeight()); babyDob = (Button) findViewById(R.id.babyDob); babyDob.setText(editBaby.getDob()); // add a click listener to the button babyDob.setOnClickListener(showDateDialog()); // get the current date final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); // display the current date //updateDateDisplay(); //populate male/female spinner ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.babySex, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner s = (Spinner) findViewById(R.id.babySex); s.setAdapter(adapter); //Set Spinner Value for Baby Sex if (editBaby.getSex().equals("Male")) { babySex.setSelection(0); } else { babySex.setSelection(1); } //Take Picture Button takePicture.setOnClickListener(takePictureListener(editBaby, EDIT_CHILD_ACTIVITY_ID)); //Select Picture Button selectPicture.setOnClickListener(selectPictureListener(editBaby, EDIT_CHILD_ACTIVITY_ID)); //declare alert dialog final AlertDialog alertDialog = new AlertDialog.Builder(this).create(); // button listener for add child button addChildButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //if name, weight, and height aren't filled out, throw an alert if (babyName.getText().toString().equals("") || babyHeight.getText().toString().equals("") || babyWeight.getText().toString().equals("")) { alertDialog.setTitle("Oops!"); alertDialog.setMessage("Please fill out the form completely."); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else { // else add child to database String picturePath = ""; if (getIntent().getExtras() != null && getIntent().getExtras().get("picturePath") != null) { picturePath = getIntent().getExtras().getString("picturePath"); } Log.d("UPDATE: ", "Updating .."); Baby updateBaby = new Baby(editBaby.getID(), babyName.getText().toString(), babySex.getSelectedItem().toString(), babyHeight.getText().toString(), babyWeight.getText().toString(), babyDob.getText().toString(), picturePath); babyDao.updateBaby(updateBaby, editBaby.getID()); Intent intent = new Intent(v.getContext(), ViewBabyActivity.class); Bundle b = new Bundle(); b.putSerializable("baby", updateBaby); intent.putExtras(b); startActivityForResult(intent, 3); } } }); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_child); final BabyDao babyDao = new BabyDao(getApplicationContext()); final Baby editBaby = (Baby) getIntent().getSerializableExtra("baby"); styleActivity(editBaby.getSex()); TextView addChild = (TextView) findViewById(R.id.addChild); addChild.setText("Edit Baby"); final EditText babyName = (EditText) findViewById(R.id.babyName); final Spinner babySex = (Spinner) findViewById(R.id.babySex); final EditText babyHeight = (EditText) findViewById(R.id.babyHeight); final EditText babyWeight = (EditText) findViewById(R.id.babyWeight); Button addChildButton = (Button) findViewById(R.id.addChildButton); Button takePicture = (Button) findViewById(R.id.takePicture); Button selectPicture = (Button) findViewById(R.id.pickPicture); babyName.setText(editBaby.getName()); babyHeight.setText(editBaby.getHeight()); babyWeight.setText(editBaby.getWeight()); babyDob = (Button) findViewById(R.id.babyDob); babyDob.setText(editBaby.getDob()); // add a click listener to the button babyDob.setOnClickListener(showDateDialog()); // get the current date final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); // display the current date //updateDateDisplay(); //populate male/female spinner ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.babySex, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); Spinner s = (Spinner) findViewById(R.id.babySex); s.setAdapter(adapter); //Set Spinner Value for Baby Sex if (editBaby.getSex().equals("Male")) { babySex.setSelection(0); } else { babySex.setSelection(1); } //Take Picture Button takePicture.setOnClickListener(takePictureListener(editBaby, EDIT_CHILD_ACTIVITY_ID)); //Select Picture Button selectPicture.setOnClickListener(selectPictureListener(editBaby, EDIT_CHILD_ACTIVITY_ID)); //declare alert dialog final AlertDialog alertDialog = new AlertDialog.Builder(this).create(); // button listener for add child button addChildButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { //if name, weight, and height aren't filled out, throw an alert if (babyName.getText().toString().equals("") || babyHeight.getText().toString().equals("") || babyWeight.getText().toString().equals("")) { alertDialog.setTitle("Oops!"); alertDialog.setMessage("Please fill out the form completely."); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); alertDialog.show(); } else { // else add child to database String picturePath = ""; if (getIntent().getExtras() != null && getIntent().getExtras().get("picturePath") != null) { editBaby.setPicturePath(getIntent().getExtras().getString("picturePath")); } Log.d("UPDATE: ", "Updating .."); Baby updateBaby = new Baby(editBaby.getID(), babyName.getText().toString(), babySex.getSelectedItem().toString(), babyHeight.getText().toString(), babyWeight.getText().toString(), babyDob.getText().toString(), editBaby.getPicturePath()); babyDao.updateBaby(updateBaby, editBaby.getID()); Intent intent = new Intent(v.getContext(), ViewBabyActivity.class); Bundle b = new Bundle(); b.putSerializable("baby", updateBaby); intent.putExtras(b); startActivityForResult(intent, 3); } } }); }
diff --git a/src/benchmarks/edu/brown/api/BenchmarkComponent.java b/src/benchmarks/edu/brown/api/BenchmarkComponent.java index 1f299d701..ce5818e96 100644 --- a/src/benchmarks/edu/brown/api/BenchmarkComponent.java +++ b/src/benchmarks/edu/brown/api/BenchmarkComponent.java @@ -1,1839 +1,1842 @@ /*************************************************************************** * Copyright (C) 2011 by H-Store Project * * Brown University * * Massachusetts Institute of Technology * * Yale University * * * * 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 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. * ***************************************************************************/ /* This file is part of VoltDB. * Copyright (C) 2008-2010 VoltDB L.L.C. * * 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 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 edu.brown.api; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.net.UnknownHostException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.collections15.map.ListOrderedMap; import org.apache.log4j.Logger; import org.voltdb.CatalogContext; import org.voltdb.ClientResponseImpl; import org.voltdb.VoltSystemProcedure; import org.voltdb.VoltTable; import org.voltdb.VoltTableRow; import org.voltdb.benchmark.BlockingClient; import org.voltdb.benchmark.Verification; import org.voltdb.benchmark.Verification.Expression; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.Database; import org.voltdb.catalog.Site; import org.voltdb.catalog.Table; import org.voltdb.client.Client; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientResponse; import org.voltdb.client.ProcCallException; import org.voltdb.client.StatsUploaderSettings; import org.voltdb.sysprocs.LoadMultipartitionTable; import org.voltdb.utils.Pair; import org.voltdb.utils.VoltSampler; import edu.brown.api.results.BenchmarkComponentResults; import edu.brown.api.results.ResponseEntries; import edu.brown.catalog.CatalogUtil; import edu.brown.designer.partitioners.plan.PartitionPlan; import edu.brown.hstore.HStoreConstants; import edu.brown.hstore.HStoreThreadManager; import edu.brown.hstore.Hstoreservice.Status; import edu.brown.hstore.conf.HStoreConf; import edu.brown.logging.LoggerUtil; import edu.brown.logging.LoggerUtil.LoggerBoolean; import edu.brown.profilers.ProfileMeasurement; import edu.brown.statistics.Histogram; import edu.brown.statistics.ObjectHistogram; import edu.brown.statistics.TableStatistics; import edu.brown.statistics.WorkloadStatistics; import edu.brown.utils.ArgumentsParser; import edu.brown.utils.FileUtil; import edu.brown.utils.StringUtil; /** * Base class for clients that will work with the multi-host multi-process * benchmark framework that is driven from stdin */ public abstract class BenchmarkComponent { private static final Logger LOG = Logger.getLogger(BenchmarkComponent.class); private static final LoggerBoolean debug = new LoggerBoolean(LOG.isDebugEnabled()); private static final LoggerBoolean trace = new LoggerBoolean(LOG.isTraceEnabled()); static { LoggerUtil.setupLogging(); LoggerUtil.attachObserver(LOG, debug, trace); } public static String CONTROL_MESSAGE_PREFIX = "{HSTORE}"; // ============================================================================ // SHARED STATIC MEMBERS // ============================================================================ private static Client globalClient; private static final ReentrantLock globalClientLock = new ReentrantLock(); private static CatalogContext globalCatalog; private static final ReentrantLock globalCatalogLock = new ReentrantLock(); private static PartitionPlan globalPartitionPlan; private static final ReentrantLock globalPartitionPlanLock = new ReentrantLock(); private static final Set<Client> globalHasConnections = new HashSet<Client>(); private static Client getClient(Catalog catalog, int messageSize, boolean heavyWeight, StatsUploaderSettings statsSettings, boolean shareConnection) { Client client = globalClient; if (shareConnection == false) { client = ClientFactory.createClient( messageSize, null, heavyWeight, statsSettings, catalog ); if (debug.val) LOG.debug("Created new Client handle"); } else if (client == null) { globalClientLock.lock(); try { if (globalClient == null) { client = ClientFactory.createClient( messageSize, null, heavyWeight, statsSettings, catalog ); if (debug.val) LOG.debug("Created new shared Client handle"); } } finally { globalClientLock.unlock(); } // SYNCH } return (client); } private static CatalogContext getCatalogContext(File catalogPath) { // Read back the catalog and populate catalog object if (globalCatalog == null) { globalCatalogLock.lock(); try { if (globalCatalog == null) { globalCatalog = CatalogUtil.loadCatalogContextFromJar(catalogPath); } } finally { globalCatalogLock.unlock(); } // SYNCH } return (globalCatalog); } private static void applyPartitionPlan(Database catalog_db, File partitionPlanPath) { if (globalPartitionPlan != null) return; globalPartitionPlanLock.lock(); try { if (globalPartitionPlan != null) return; if (debug.val) LOG.debug("Loading PartitionPlan '" + partitionPlanPath + "' and applying it to the catalog"); globalPartitionPlan = new PartitionPlan(); try { globalPartitionPlan.load(partitionPlanPath, catalog_db); globalPartitionPlan.apply(catalog_db); } catch (Exception ex) { throw new RuntimeException("Failed to load PartitionPlan '" + partitionPlanPath + "' and apply it to the catalog", ex); } } finally { globalPartitionPlanLock.unlock(); } // SYNCH return; } // ============================================================================ // INSTANCE MEMBERS // ============================================================================ /** * Client initialized here and made available for use in derived classes */ private Client m_voltClient; /** * Manage input and output to the framework */ private ControlPipe m_controlPipe; private boolean m_controlPipeAutoStart = false; /** * */ protected final ControlWorker worker = new ControlWorker(this); /** * State of this client */ protected volatile ControlState m_controlState = ControlState.PREPARING; /** * Username supplied to the Volt client */ private final String m_username; /** * Password supplied to the Volt client */ private final String m_password; /** * Rate at which transactions should be generated. If set to -1 the rate * will be controlled by the derived class. Rate is in transactions per * second */ final int m_txnRate; private final boolean m_blocking; /** * Number of transactions to generate for every millisecond of time that * passes */ final double m_txnsPerMillisecond; /** * Additional parameters (benchmark specific) */ protected final Map<String, String> m_extraParams = new HashMap<String, String>(); /** * Storage for error descriptions */ protected String m_reason = ""; /** * Display names for each transaction. */ private final String m_countDisplayNames[]; /** * Client Id */ private final int m_id; /** * Total # of Clients */ private final int m_numClients; /** * If set to true, don't try to make any connections to the cluster with this client * This is just used for testing */ private final boolean m_noConnections; /** * Total # of Partitions */ private final int m_numPartitions; /** * Path to catalog jar */ private final File m_catalogPath; private CatalogContext m_catalogContext; private final String m_projectName; final boolean m_exitOnCompletion; /** * Pause Lock */ protected final Semaphore m_pauseLock = new Semaphore(1); /** * Data verification. */ private final float m_checkTransaction; protected final boolean m_checkTables; private final Random m_checkGenerator = new Random(); private final LinkedHashMap<Pair<String, Integer>, Expression> m_constraints; private final List<String> m_tableCheckOrder = new LinkedList<String>(); protected VoltSampler m_sampler = null; protected final int m_tickInterval; protected final Thread m_tickThread; protected int m_tickCounter = 0; private final boolean m_noUploading; private final ReentrantLock m_loaderBlock = new ReentrantLock(); private final ClientResponse m_dummyResponse = new ClientResponseImpl(-1, -1, -1, Status.OK, HStoreConstants.EMPTY_RESULT, ""); /** * Keep track of the number of tuples loaded so that we can generate table statistics */ private final boolean m_tableStats; private final File m_tableStatsDir; private final ObjectHistogram<String> m_tableTuples = new ObjectHistogram<String>(); private final ObjectHistogram<String> m_tableBytes = new ObjectHistogram<String>(); private final Map<Table, TableStatistics> m_tableStatsData = new HashMap<Table, TableStatistics>(); protected final BenchmarkComponentResults m_txnStats = new BenchmarkComponentResults(); /** * ClientResponse Entries */ protected final ResponseEntries m_responseEntries; private boolean m_enableResponseEntries = false; private final Map<String, ProfileMeasurement> computeTime = new HashMap<String, ProfileMeasurement>(); /** * */ private BenchmarkClientFileUploader uploader = null; /** * Configuration */ private final HStoreConf m_hstoreConf; private final ObjectHistogram<String> m_txnWeights = new ObjectHistogram<String>(); private Integer m_txnWeightsDefault = null; private final boolean m_isLoader; private final String m_statsDatabaseURL; private final String m_statsDatabaseUser; private final String m_statsDatabasePass; private final String m_statsDatabaseJDBC; private final int m_statsPollerInterval; public BenchmarkComponent(final Client client) { m_voltClient = client; m_exitOnCompletion = false; m_password = ""; m_username = ""; m_txnRate = -1; m_isLoader = false; m_blocking = false; m_txnsPerMillisecond = 0; m_catalogPath = null; m_projectName = null; m_id = 0; m_numClients = 1; m_noConnections = false; m_numPartitions = 0; m_countDisplayNames = null; m_checkTransaction = 0; m_checkTables = false; m_constraints = new LinkedHashMap<Pair<String, Integer>, Expression>(); m_tickInterval = -1; m_tickThread = null; m_responseEntries = null; m_tableStats = false; m_tableStatsDir = null; m_noUploading = false; m_statsDatabaseURL = null; m_statsDatabaseUser = null; m_statsDatabasePass = null; m_statsDatabaseJDBC = null; m_statsPollerInterval = -1; // FIXME m_hstoreConf = null; } /** * Constructor that initializes the framework portions of the client. * Creates a Volt client and connects it to all the hosts provided on the * command line with the specified username and password * * @param args */ public BenchmarkComponent(String args[]) { if (debug.val) LOG.debug("Benchmark Component debugging"); // Initialize HStoreConf String hstore_conf_path = null; for (int i = 0; i < args.length; i++) { final String arg = args[i]; final String[] parts = arg.split("=", 2); if (parts.length > 1 && parts[1].startsWith("${") == false && parts[0].equalsIgnoreCase("CONF")) { hstore_conf_path = parts[1]; break; } } // FOR if (HStoreConf.isInitialized() == false) { assert(hstore_conf_path != null) : "Missing HStoreConf file"; File f = new File(hstore_conf_path); if (debug.val) LOG.debug("Initializing HStoreConf from '" + f.getName() + "' along with input parameters"); HStoreConf.init(f, args); } else { if (debug.val) LOG.debug("Initializing HStoreConf only with input parameters"); HStoreConf.singleton().loadFromArgs(args); } m_hstoreConf = HStoreConf.singleton(); if (trace.val) LOG.trace("HStore Conf\n" + m_hstoreConf.toString(true)); int transactionRate = m_hstoreConf.client.txnrate; boolean blocking = m_hstoreConf.client.blocking; boolean tableStats = m_hstoreConf.client.tablestats; String tableStatsDir = m_hstoreConf.client.tablestats_dir; int tickInterval = m_hstoreConf.client.tick_interval; // default values String username = "user"; String password = "password"; ControlState state = ControlState.PREPARING; // starting state String reason = ""; // and error string int id = 0; boolean isLoader = false; int num_clients = 0; int num_partitions = 0; boolean exitOnCompletion = true; float checkTransaction = 0; boolean checkTables = false; boolean noConnections = false; boolean noUploading = false; File catalogPath = null; String projectName = null; String partitionPlanPath = null; boolean partitionPlanIgnoreMissing = false; long startupWait = -1; boolean autoStart = false; String statsDatabaseURL = null; String statsDatabaseUser = null; String statsDatabasePass = null; String statsDatabaseJDBC = null; int statsPollInterval = 10000; // scan the inputs once to read everything but host names Map<String, Object> componentParams = new TreeMap<String, Object>(); for (int i = 0; i < args.length; i++) { final String arg = args[i]; final String[] parts = arg.split("=", 2); if (parts.length == 1) { state = ControlState.ERROR; reason = "Invalid parameter: " + arg; break; } else if (parts[1].startsWith("${")) { continue; } else if (parts[0].equalsIgnoreCase("CONF")) { continue; } if (debug.val) componentParams.put(parts[0], parts[1]); if (parts[0].equalsIgnoreCase("CATALOG")) { catalogPath = new File(parts[1]); assert(catalogPath.exists()) : "The catalog file '" + catalogPath.getAbsolutePath() + " does not exist"; if (debug.val) componentParams.put(parts[0], catalogPath); } else if (parts[0].equalsIgnoreCase("LOADER")) { isLoader = Boolean.parseBoolean(parts[1]); } else if (parts[0].equalsIgnoreCase("NAME")) { projectName = parts[1]; } else if (parts[0].equalsIgnoreCase("USER")) { username = parts[1]; } else if (parts[0].equalsIgnoreCase("PASSWORD")) { password = parts[1]; } else if (parts[0].equalsIgnoreCase("EXITONCOMPLETION")) { exitOnCompletion = Boolean.parseBoolean(parts[1]); } else if (parts[0].equalsIgnoreCase("ID")) { id = Integer.parseInt(parts[1]); } else if (parts[0].equalsIgnoreCase("NUMCLIENTS")) { num_clients = Integer.parseInt(parts[1]); } else if (parts[0].equalsIgnoreCase("NUMPARTITIONS")) { num_partitions = Integer.parseInt(parts[1]); } else if (parts[0].equalsIgnoreCase("CHECKTRANSACTION")) { checkTransaction = Float.parseFloat(parts[1]); } else if (parts[0].equalsIgnoreCase("CHECKTABLES")) { checkTables = Boolean.parseBoolean(parts[1]); } else if (parts[0].equalsIgnoreCase("NOCONNECTIONS")) { noConnections = Boolean.parseBoolean(parts[1]); } else if (parts[0].equalsIgnoreCase("NOUPLOADING")) { noUploading = Boolean.parseBoolean(parts[1]); } else if (parts[0].equalsIgnoreCase("WAIT")) { startupWait = Long.parseLong(parts[1]); } else if (parts[0].equalsIgnoreCase("AUTOSTART")) { autoStart = Boolean.parseBoolean(parts[1]); } // Procedure Stats Uploading Parameters else if (parts[0].equalsIgnoreCase("STATSDATABASEURL")) { statsDatabaseURL = parts[1]; } else if (parts[0].equalsIgnoreCase("STATSDATABASEUSER")) { if (parts[1].isEmpty() == false) statsDatabaseUser = parts[1]; } else if (parts[0].equalsIgnoreCase("STATSDATABASEPASS")) { if (parts[1].isEmpty() == false) statsDatabasePass = parts[1]; } else if (parts[0].equalsIgnoreCase("STATSDATABASEJDBC")) { if (parts[1].isEmpty() == false) statsDatabaseJDBC = parts[1]; } else if (parts[0].equalsIgnoreCase("STATSPOLLINTERVAL")) { statsPollInterval = Integer.parseInt(parts[1]); } else if (parts[0].equalsIgnoreCase(ArgumentsParser.PARAM_PARTITION_PLAN)) { partitionPlanPath = parts[1]; } else if (parts[0].equalsIgnoreCase(ArgumentsParser.PARAM_PARTITION_PLAN_IGNORE_MISSING)) { partitionPlanIgnoreMissing = Boolean.parseBoolean(parts[1]); } // If it starts with "benchmark.", then it always goes to the implementing class else if (parts[0].toLowerCase().startsWith(HStoreConstants.BENCHMARK_PARAM_PREFIX)) { if (debug.val) componentParams.remove(parts[0]); parts[0] = parts[0].substring(HStoreConstants.BENCHMARK_PARAM_PREFIX.length()); m_extraParams.put(parts[0].toUpperCase(), parts[1]); } } if (trace.val) { Map<String, Object> m = new ListOrderedMap<String, Object>(); m.put("BenchmarkComponent", componentParams); m.put("Extra Client", m_extraParams); LOG.debug("Input Parameters:\n" + StringUtil.formatMaps(m)); } // Thread.currentThread().setName(String.format("client-%02d", id)); m_catalogPath = catalogPath; m_projectName = projectName; m_id = id; m_isLoader = isLoader; m_numClients = num_clients; m_numPartitions = num_partitions; m_exitOnCompletion = exitOnCompletion; m_username = username; m_password = password; m_txnRate = (isLoader ? -1 : transactionRate); m_txnsPerMillisecond = (isLoader ? -1 : transactionRate / 1000.0); m_blocking = blocking; m_tickInterval = tickInterval; m_noUploading = noUploading; m_noConnections = noConnections || (isLoader && m_noUploading); m_tableStats = tableStats; m_tableStatsDir = (tableStatsDir.isEmpty() ? null : new File(tableStatsDir)); m_controlPipeAutoStart = autoStart; m_statsDatabaseURL = statsDatabaseURL; m_statsDatabaseUser = statsDatabaseUser; m_statsDatabasePass = statsDatabasePass; m_statsDatabaseJDBC = statsDatabaseJDBC; m_statsPollerInterval = statsPollInterval; // If we were told to sleep, do that here before we try to load in the catalog // This is an attempt to keep us from overloading a single node all at once if (startupWait > 0) { if (debug.val) LOG.debug(String.format("Delaying client start-up by %.2f sec", startupWait/1000d)); try { Thread.sleep(startupWait); } catch (InterruptedException ex) { throw new RuntimeException("Unexpected interruption", ex); } } // HACK: This will instantiate m_catalog for us... if (m_catalogPath != null) { this.getCatalog(); } // Parse workload transaction weights if (m_hstoreConf.client.weights != null && m_hstoreConf.client.weights.trim().isEmpty() == false) { for (String entry : m_hstoreConf.client.weights.split("(,|;)")) { String data[] = entry.split(":"); if (data.length != 2) { LOG.warn("Invalid transaction weight entry '" + entry + "'"); continue; } try { String txnName = data[0]; int txnWeight = Integer.parseInt(data[1]); assert(txnWeight >= 0); // '*' is the default value if (txnName.equals("*")) { this.m_txnWeightsDefault = txnWeight; if (debug.val) LOG.debug(String.format("Default Transaction Weight: %d", txnWeight)); } else { if (debug.val) LOG.debug(String.format("%s Transaction Weight: %d", txnName, txnWeight)); this.m_txnWeights.put(txnName.toUpperCase(), txnWeight); } // If the weight is 100, then we'll set the default weight to zero if (txnWeight == 100 && this.m_txnWeightsDefault == null) { this.m_txnWeightsDefault = 0; if (debug.val) LOG.debug(String.format("Default Transaction Weight: %d", this.m_txnWeightsDefault)); } } catch (Throwable ex) { LOG.warn("Invalid transaction weight entry '" + entry + "'", ex); continue; } } // FOR } if (partitionPlanPath != null) { boolean exists = FileUtil.exists(partitionPlanPath); if (partitionPlanIgnoreMissing == false) assert(exists) : "Invalid partition plan path '" + partitionPlanPath + "'"; if (exists) this.applyPartitionPlan(new File(partitionPlanPath)); } this.initializeConnection(); // report any errors that occurred before the client was instantiated if (state != ControlState.PREPARING) setState(state, reason); m_checkTransaction = checkTransaction; m_checkTables = checkTables; m_constraints = new LinkedHashMap<Pair<String, Integer>, Expression>(); m_countDisplayNames = getTransactionDisplayNames(); if (m_countDisplayNames != null) { Map<Integer, String> debugLabels = new TreeMap<Integer, String>(); m_enableResponseEntries = (m_hstoreConf.client.output_responses != null); m_responseEntries = new ResponseEntries(); for (int i = 0; i < m_countDisplayNames.length; i++) { m_txnStats.transactions.put(i, 0); m_txnStats.dtxns.put(i, 0); debugLabels.put(i, m_countDisplayNames[i]); } // FOR m_txnStats.transactions.setDebugLabels(debugLabels); m_txnStats.dtxns.setDebugLabels(debugLabels); m_txnStats.setEnableBasePartitions(m_hstoreConf.client.output_basepartitions); m_txnStats.setEnableResponsesStatuses(m_hstoreConf.client.output_status); } else { m_responseEntries = null; } // If we need to call tick more frequently than when POLL is called, // then we'll want to use a separate thread if (m_tickInterval > 0 && isLoader == false) { if (debug.val) LOG.debug(String.format("Creating local thread that will call BenchmarkComponent.tick() every %.1f seconds", (m_tickInterval / 1000.0))); Runnable r = new Runnable() { @Override public void run() { try { while (true) { BenchmarkComponent.this.invokeTickCallback(m_tickCounter++); Thread.sleep(m_tickInterval); } // WHILE } catch (InterruptedException ex) { LOG.warn("Tick thread was interrupted"); } } }; m_tickThread = new Thread(r); m_tickThread.setDaemon(true); } else { m_tickThread = null; } } // ---------------------------------------------------------------------------- // MAIN METHOD HOOKS // ---------------------------------------------------------------------------- /** * Derived classes implementing a main that will be invoked at the start of * the app should call this main to instantiate themselves * * @param clientClass * Derived class to instantiate * @param args * @param startImmediately * Whether to start the client thread immediately or not. */ public static BenchmarkComponent main(final Class<? extends BenchmarkComponent> clientClass, final String args[], final boolean startImmediately) { return main(clientClass, null, args, startImmediately); } protected static BenchmarkComponent main(final Class<? extends BenchmarkComponent> clientClass, final BenchmarkClientFileUploader uploader, final String args[], final boolean startImmediately) { BenchmarkComponent clientMain = null; try { final Constructor<? extends BenchmarkComponent> constructor = clientClass.getConstructor(new Class<?>[] { new String[0].getClass() }); clientMain = constructor.newInstance(new Object[] { args }); if (uploader != null) clientMain.uploader = uploader; if (startImmediately) { final ControlWorker worker = new ControlWorker(clientMain); worker.start(); // Wait for the worker to finish if (debug.val) LOG.debug(String.format("Started ControlWorker for client #%02d. Waiting until finished...", clientMain.getClientId())); worker.join(); clientMain.invokeStopCallback(); } else { // if (debug.val) LOG.debug(String.format("Deploying ControlWorker for client #%02d. Waiting for control signal...", clientMain.getClientId())); // clientMain.start(); } } catch (final Throwable e) { String name = (clientMain != null ? clientMain.getProjectName()+"." : "") + clientClass.getSimpleName(); LOG.error("Unexpected error while invoking " + name, e); throw new RuntimeException(e); } return (clientMain); } // ---------------------------------------------------------------------------- // CLUSTER CONNECTION SETUP // ---------------------------------------------------------------------------- protected void initializeConnection() { StatsUploaderSettings statsSettings = null; if (m_statsDatabaseURL != null && m_statsDatabaseURL.isEmpty() == false) { try { statsSettings = StatsUploaderSettings.singleton( m_statsDatabaseURL, m_statsDatabaseUser, m_statsDatabasePass, m_statsDatabaseJDBC, this.getProjectName(), (m_isLoader ? "LOADER" : "CLIENT"), m_statsPollerInterval, m_catalogContext.catalog); } catch (Throwable ex) { throw new RuntimeException("Failed to initialize StatsUploader", ex); } if (debug.val) LOG.debug("StatsUploaderSettings:\n" + statsSettings); } Client new_client = BenchmarkComponent.getClient( (m_hstoreConf.client.txn_hints ? this.getCatalog() : null), getExpectedOutgoingMessageSize(), useHeavyweightClient(), statsSettings, m_hstoreConf.client.shared_connection ); if (m_blocking) { // && isLoader == false) { if (debug.val) LOG.debug(String.format("Using BlockingClient [concurrent=%d]", m_hstoreConf.client.blocking_concurrent)); m_voltClient = new BlockingClient(new_client, m_hstoreConf.client.blocking_concurrent); } else { m_voltClient = new_client; } // scan the inputs again looking for host connections if (m_noConnections == false) { synchronized (BenchmarkComponent.class) { if (globalHasConnections.contains(new_client) == false) { this.setupConnections(); globalHasConnections.add(new_client); } } // SYNCH } } private void setupConnections() { boolean atLeastOneConnection = false; for (Site catalog_site : CatalogUtil.getAllSites(this.getCatalog())) { final int site_id = catalog_site.getId(); final String host = catalog_site.getHost().getIpaddr(); int port = catalog_site.getProc_port(); if (debug.val) LOG.debug(String.format("Creating connection to %s at %s:%d", HStoreThreadManager.formatSiteName(site_id), host, port)); try { this.createConnection(site_id, host, port); } catch (IOException ex) { String msg = String.format("Failed to connect to %s on %s:%d", HStoreThreadManager.formatSiteName(site_id), host, port); // LOG.error(msg, ex); // setState(ControlState.ERROR, msg + ": " + ex.getMessage()); // continue; throw new RuntimeException(msg, ex); } atLeastOneConnection = true; } // FOR if (!atLeastOneConnection) { setState(ControlState.ERROR, "No HOSTS specified on command line."); throw new RuntimeException("Failed to establish connections to H-Store cluster"); } } private void createConnection(final Integer site_id, final String hostname, final int port) throws UnknownHostException, IOException { if (debug.val) LOG.debug(String.format("Requesting connection to %s %s:%d", HStoreThreadManager.formatSiteName(site_id), hostname, port)); m_voltClient.createConnection(site_id, hostname, port, m_username, m_password); } // ---------------------------------------------------------------------------- // CONTROLLER COMMUNICATION METHODS // ---------------------------------------------------------------------------- protected void printControlMessage(ControlState state) { printControlMessage(state, null); } private void printControlMessage(ControlState state, String message) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%s %d,%d,%s", CONTROL_MESSAGE_PREFIX, this.getClientId(), System.currentTimeMillis(), state)); if (message != null && message.isEmpty() == false) { sb.append(",").append(message); } System.out.println(sb); } protected void answerWithError() { this.printControlMessage(m_controlState, m_reason); } protected void answerPoll() { BenchmarkComponentResults copy = this.m_txnStats.copy(); this.m_txnStats.clear(false); this.printControlMessage(m_controlState, copy.toJSONString()); } protected void answerDumpTxns() { ResponseEntries copy = new ResponseEntries(this.m_responseEntries); this.m_responseEntries.clear(); this.printControlMessage(ControlState.DUMPING, copy.toJSONString()); } protected void answerOk() { this.printControlMessage(m_controlState, "OK"); } /** * Implemented by derived classes. Loops indefinitely invoking stored * procedures. Method never returns and never receives any updates. */ @Deprecated abstract protected void runLoop() throws IOException; /** * Get the display names of the transactions that will be invoked by the * derived class. As a side effect this also retrieves the number of * transactions that can be invoked. * * @return */ abstract protected String[] getTransactionDisplayNames(); /** * Increment the internal transaction counter. This should be invoked * after the client has received a ClientResponse from the DBMS cluster * The txn_index is the offset of the transaction that was executed. This offset * is the same order as the array returned by getTransactionDisplayNames * @param cresponse - The ClientResponse returned from the server * @param txn_idx */ protected final void incrementTransactionCounter(final ClientResponse cresponse, final int txn_idx) { // Only include it if it wasn't rejected // This is actually handled in the Distributer, but it doesn't hurt to have this here Status status = cresponse.getStatus(); if (status == Status.OK || status == Status.ABORT_USER) { // TRANSACTION COUNTERS boolean is_specexec = cresponse.isSpeculative(); boolean is_dtxn = cresponse.isSinglePartition(); synchronized (m_txnStats.transactions) { m_txnStats.transactions.put(txn_idx); if (is_dtxn == false) m_txnStats.dtxns.put(txn_idx); if (is_specexec) m_txnStats.specexecs.put(txn_idx); } // SYNCH // LATENCIES COUNTERS // Ignore zero latencies... Not sure why this happens... int latency = cresponse.getClusterRoundtrip(); if (latency > 0) { Histogram<Integer> latencies = m_txnStats.latencies.get(txn_idx); if (latencies == null) { synchronized (m_txnStats.latencies) { latencies = m_txnStats.latencies.get(txn_idx); if (latencies == null) { latencies = new ObjectHistogram<Integer>(); m_txnStats.latencies.put(txn_idx, (ObjectHistogram<Integer>)latencies); } } // SYNCH } synchronized (latencies) { latencies.put(latency); } // SYNCH } // RESPONSE ENTRIES if (m_enableResponseEntries) { long timestamp = System.currentTimeMillis(); m_responseEntries.add(cresponse, m_id, txn_idx, timestamp); } // BASE PARTITIONS if (m_txnStats.isBasePartitionsEnabled()) { synchronized (m_txnStats.basePartitions) { m_txnStats.basePartitions.put(cresponse.getBasePartition()); } // SYNCH } } // else { // LOG.warn("Invalid " + m_countDisplayNames[txn_idx] + " response!\n" + cresponse); // if (cresponse.getException() != null) { // cresponse.getException().printStackTrace(); // } // if (cresponse.getStatusString() != null) { // LOG.warn(cresponse.getStatusString()); // } // // System.exit(-1); // } if (m_txnStats.isResponsesStatusesEnabled()) { synchronized (m_txnStats.responseStatuses) { m_txnStats.responseStatuses.put(status.ordinal()); } // SYNCH } } // ---------------------------------------------------------------------------- // PUBLIC UTILITY METHODS // ---------------------------------------------------------------------------- /** * Return the scale factor for this benchmark instance * @return */ public double getScaleFactor() { return (m_hstoreConf.client.scalefactor); } /** * This method will load a VoltTable into the database for the given tableName. * The database will automatically split the tuples and send to the correct partitions * The current thread will block until the the database cluster returns the result. * Can be overridden for testing purposes. * @param tableName * @param vt */ public ClientResponse loadVoltTable(String tableName, VoltTable vt) { assert(vt != null) : "Null VoltTable for '" + tableName + "'"; int rowCount = vt.getRowCount(); long rowTotal = m_tableTuples.get(tableName, 0); int byteCount = vt.getUnderlyingBufferSize(); long byteTotal = m_tableBytes.get(tableName, 0); if (trace.val) LOG.trace(String.format("%s: Loading %d new rows - TOTAL %d [bytes=%d/%d]", tableName.toUpperCase(), rowCount, rowTotal, byteCount, byteTotal)); // Load up this dirty mess... ClientResponse cr = null; if (m_noUploading == false) { boolean locked = m_hstoreConf.client.blocking_loader; if (locked) m_loaderBlock.lock(); try { int tries = 3; String procName = VoltSystemProcedure.procCallName(LoadMultipartitionTable.class); while (tries-- > 0) { try { cr = m_voltClient.callProcedure(procName, tableName, vt); } catch (ProcCallException ex) { // If this thing was rejected, then we'll allow us to try again. cr = ex.getClientResponse(); if (cr.getStatus() == Status.ABORT_REJECT && tries > 0) { if (debug.val) LOG.warn(String.format("Loading data for %s was rejected. Going to try again\n%s", tableName, cr.toString())); continue; } // Anything else needs to be thrown out of here throw ex; } break; } // WHILE } catch (Throwable ex) { throw new RuntimeException("Error when trying load data for '" + tableName + "'", ex); } finally { if (locked) m_loaderBlock.unlock(); } // SYNCH assert(cr != null); assert(cr.getStatus() == Status.OK); if (trace.val) LOG.trace(String.format("Load %s: txn #%d / %s / %d", tableName, cr.getTransactionId(), cr.getStatus(), cr.getClientHandle())); } else { cr = m_dummyResponse; } if (cr.getStatus() != Status.OK) { LOG.warn(String.format("Failed to load %d rows for '%s': %s", rowCount, tableName, cr.getStatusString()), cr.getException()); return (cr); } m_tableTuples.put(tableName, rowCount); m_tableBytes.put(tableName, byteCount); // Keep track of table stats if (m_tableStats && cr.getStatus() == Status.OK) { final CatalogContext catalogContext = this.getCatalogContext(); assert(catalogContext != null); final Table catalog_tbl = catalogContext.getTableByName(tableName); assert(catalog_tbl != null) : "Invalid table name '" + tableName + "'"; synchronized (m_tableStatsData) { TableStatistics stats = m_tableStatsData.get(catalog_tbl); if (stats == null) { stats = new TableStatistics(catalog_tbl); stats.preprocess(catalogContext.database); m_tableStatsData.put(catalog_tbl, stats); } vt.resetRowPosition(); while (vt.advanceRow()) { VoltTableRow row = vt.getRow(); stats.process(catalogContext.database, row); } // WHILE } // SYNCH } return (cr); } /** * Return an overridden transaction weight * @param txnName * @return */ protected final Integer getTransactionWeight(String txnName) { return (this.getTransactionWeight(txnName, null)); } /** * * @param txnName * @param weightIfNull * @return */ protected final Integer getTransactionWeight(String txnName, Integer weightIfNull) { Long val = this.m_txnWeights.get(txnName.toUpperCase()); if (val != null) { return (val.intValue()); } else if (m_txnWeightsDefault != null) { return (m_txnWeightsDefault); } return (weightIfNull); } /** * Get the number of tuples loaded into the given table thus far * @param tableName * @return */ public final long getTableTupleCount(String tableName) { return (m_tableTuples.get(tableName, 0)); } /** * Get a read-only histogram of the number of tuples loaded in all * of the tables * @return */ public final Histogram<String> getTableTupleCounts() { return (new ObjectHistogram<String>(m_tableTuples)); } /** * Get the number of bytes loaded into the given table thus far * @param tableName * @return */ public final long getTableBytes(String tableName) { return (m_tableBytes.get(tableName, 0)); } /** * Generate a WorkloadStatistics object based on the table stats that * were collected using loadVoltTable() * @return */ private final WorkloadStatistics generateWorkloadStatistics() { assert(m_tableStatsDir != null); final Catalog catalog = this.getCatalog(); assert(catalog != null); final Database catalog_db = CatalogUtil.getDatabase(catalog); // Make sure we call postprocess on all of our friends for (TableStatistics tableStats : m_tableStatsData.values()) { try { tableStats.postprocess(catalog_db); } catch (Exception ex) { String tableName = tableStats.getCatalogItem(catalog_db).getName(); throw new RuntimeException("Failed to process TableStatistics for '" + tableName + "'", ex); } } // FOR if (trace.val) LOG.trace(String.format("Creating WorkloadStatistics for %d tables [totalRows=%d, totalBytes=%d", m_tableStatsData.size(), m_tableTuples.getSampleCount(), m_tableBytes.getSampleCount())); WorkloadStatistics stats = new WorkloadStatistics(catalog_db); stats.apply(m_tableStatsData); return (stats); } /** * Queue a local file to be sent to the client with the given client id. * The file will be copied into the path specified by remote_file. * When the client is started it will be passed argument <parameter>=<remote_file> * @param client_id * @param parameter * @param local_file * @param remote_file */ public void sendFileToClient(int client_id, String parameter, File local_file, File remote_file) throws IOException { assert(uploader != null); this.uploader.sendFileToClient(client_id, parameter, local_file, remote_file); LOG.debug(String.format("Queuing local file '%s' to be sent to client %d as parameter '%s' to remote file '%s'", local_file, client_id, parameter, remote_file)); } /** * * @param client_id * @param parameter * @param local_file * @throws IOException */ public void sendFileToClient(int client_id, String parameter, File local_file) throws IOException { String suffix = FileUtil.getExtension(local_file); String prefix = String.format("%s-%02d-", local_file.getName().replace("." + suffix, ""), client_id); File remote_file = FileUtil.getTempFile(prefix, suffix, false); sendFileToClient(client_id, parameter, local_file, remote_file); } /** * Queue a local file to be sent to all clients * @param parameter * @param local_file * @throws IOException */ public void sendFileToAllClients(String parameter, File local_file) throws IOException { for (int i = 0, cnt = this.getNumClients(); i < cnt; i++) { sendFileToClient(i, parameter, local_file, local_file); // this.sendFileToClient(i, parameter, local_file); } // FOR } protected void setBenchmarkClientFileUploader(BenchmarkClientFileUploader uploader) { assert(this.uploader == null); this.uploader = uploader; } // ---------------------------------------------------------------------------- // CALLBACKS // ---------------------------------------------------------------------------- protected final void invokeInitCallback() { } protected final void invokeStartCallback() { this.startCallback(); } protected final void invokeStopCallback() { // If we were generating stats, then get the final WorkloadStatistics object // and write it out to a file for them to use if (m_tableStats) { WorkloadStatistics stats = this.generateWorkloadStatistics(); assert(stats != null); if (m_tableStatsDir.exists() == false) m_tableStatsDir.mkdirs(); File path = new File(m_tableStatsDir.getAbsolutePath() + "/" + this.getProjectName() + ".stats"); LOG.info("Writing table statistics data to '" + path + "'"); try { stats.save(path); } catch (IOException ex) { throw new RuntimeException("Failed to save table statistics to '" + path + "'", ex); } } this.stopCallback(); } protected final void invokeClearCallback() { m_txnStats.clear(true); m_responseEntries.clear(); this.clearCallback(); } /** * Internal callback for each POLL tick that we get from the BenchmarkController * This will invoke the tick() method that can be implemented benchmark clients * @param counter */ protected final void invokeTickCallback(int counter) { if (debug.val) LOG.debug("New Tick Update: " + counter); this.tickCallback(counter); if (debug.val) { if (this.computeTime.isEmpty() == false) { for (String txnName : this.computeTime.keySet()) { ProfileMeasurement pm = this.computeTime.get(txnName); if (pm.getInvocations() != 0) { LOG.debug(String.format("[%02d] - %s COMPUTE TIME: %s", counter, txnName, pm.debug())); pm.reset(); } } // FOR } LOG.debug("Client Queue Time: " + this.m_voltClient.getQueueTime().debug()); this.m_voltClient.getQueueTime().reset(); } } /** * Optional callback for when this BenchmarkComponent has been told to start */ public void startCallback() { // Default is to do nothing } /** * Optional callback for when this BenchmarkComponent has been told to stop * This is not a reliable callback and should only be used for testing */ public void stopCallback() { // Default is to do nothing } /** * Optional callback for when this BenchmarkComponent has been told to clear its * internal counters. */ public void clearCallback() { // Default is to do nothing } /** * Internal callback for each POLL tick that we get from the BenchmarkController * @param counter The number of times we have called this callback in the past */ public void tickCallback(int counter) { // Default is to do nothing! } // ---------------------------------------------------------------------------- // PROFILING METHODS // ---------------------------------------------------------------------------- protected synchronized void startComputeTime(String txnName) { ProfileMeasurement pm = this.computeTime.get(txnName); if (pm == null) { pm = new ProfileMeasurement(txnName); this.computeTime.put(txnName, pm); } pm.start(); } protected synchronized void stopComputeTime(String txnName) { ProfileMeasurement pm = this.computeTime.get(txnName); assert(pm != null) : "Unexpected " + txnName; pm.stop(); } protected ProfileMeasurement getComputeTime(String txnName) { return (this.computeTime.get(txnName)); } protected boolean useHeavyweightClient() { return false; } /** * Implemented by derived classes. Invoke a single procedure without running * the network. This allows BenchmarkComponent to control the rate at which * transactions are generated. * * @return True if an invocation was queued and false otherwise */ protected boolean runOnce() throws IOException { throw new UnsupportedOperationException(); } /** * Hint used when constructing the Client to control the size of buffers * allocated for message serialization * * @return */ protected int getExpectedOutgoingMessageSize() { return 128; } public ControlPipe createControlPipe(InputStream in) { m_controlPipe = new ControlPipe(this, in, m_controlPipeAutoStart); return (m_controlPipe); } /** * Return the number of partitions in the cluster for this benchmark invocation * @return */ public final int getNumPartitions() { return (m_numPartitions); } /** * Return the DBMS client handle * This Client will already be connected to the database cluster * @return */ public final Client getClientHandle() { return (m_voltClient); } /** * Special hook for setting the DBMS client handle * This should only be invoked for RegressionSuite test cases * @param client */ protected void setClientHandle(Client client) { m_voltClient = client; } /** * Return the unique client id for this invocation of BenchmarkComponent * @return */ public final int getClientId() { return (m_id); } /** * Return the total number of clients for this benchmark invocation * @return */ public final int getNumClients() { return (m_numClients); } /** * Returns true if this BenchmarkComponent is not going to make any * client connections to an H-Store cluster. This is used for testing */ protected final boolean noClientConnections() { return (m_noConnections); } /** * Return the file path to the catalog that was loaded for this benchmark invocation * @return */ public File getCatalogPath() { return (m_catalogPath); } /** * Return the project name of this benchmark * @return */ public final String getProjectName() { return (m_projectName); } public final int getCurrentTickCounter() { return (m_tickCounter); } /** * Return the catalog used for this benchmark. * @return * @throws Exception */ @Deprecated public Catalog getCatalog() { return (this.getCatalogContext().catalog); } /** * Return the CatalogContext used for this benchmark * @return */ public CatalogContext getCatalogContext() { // Read back the catalog and populate catalog object if (m_catalogContext == null) { m_catalogContext = getCatalogContext(m_catalogPath); } return (m_catalogContext); } public void setCatalogContext(CatalogContext catalogContext) { m_catalogContext = catalogContext; } public void applyPartitionPlan(File partitionPlanPath) { CatalogContext catalogContext = this.getCatalogContext(); BenchmarkComponent.applyPartitionPlan(catalogContext.database, partitionPlanPath); } /** * Get the HStoreConf handle * @return */ public HStoreConf getHStoreConf() { return (m_hstoreConf); } public void setState(final ControlState state, final String reason) { m_controlState = state; if (m_reason.equals("") == false) m_reason += (" " + reason); else m_reason = reason; } private boolean checkConstraints(String procName, ClientResponse response) { boolean isSatisfied = true; int orig_position = -1; // Check if all the tables in the result set satisfy the constraints. for (int i = 0; isSatisfied && i < response.getResults().length; i++) { Pair<String, Integer> key = Pair.of(procName, i); if (!m_constraints.containsKey(key)) continue; VoltTable table = response.getResults()[i]; orig_position = table.getActiveRowIndex(); table.resetRowPosition(); // Iterate through all rows and check if they satisfy the // constraints. while (isSatisfied && table.advanceRow()) { isSatisfied = Verification.checkRow(m_constraints.get(key), table); } // Have to reset the position to its original position. if (orig_position < 0) table.resetRowPosition(); else table.advanceToRow(orig_position); } if (!isSatisfied) LOG.error("Transaction " + procName + " failed check"); return isSatisfied; } /** * Performs constraint checking on the result set in clientResponse. It does * simple sanity checks like if the response code is SUCCESS. If the check * transaction flag is set to true by calling setCheckTransaction(), then it * will check the result set against constraints. * * @param procName * The name of the procedure * @param clientResponse * The client response * @param errorExpected * true if the response is expected to be an error. * @return true if it passes all tests, false otherwise */ protected boolean checkTransaction(String procName, ClientResponse clientResponse, boolean abortExpected, boolean errorExpected) { final Status status = clientResponse.getStatus(); if (status != Status.OK) { if (errorExpected) return true; if (abortExpected && status == Status.ABORT_USER) return true; if (status == Status.ABORT_CONNECTION_LOST) { return false; } + if (status == Status.ABORT_REJECT) { + return false; + } if (clientResponse.getException() != null) { clientResponse.getException().printStackTrace(); } if (clientResponse.getStatusString() != null) { LOG.warn(clientResponse.getStatusString()); } throw new RuntimeException("Invalid " + procName + " response!\n" + clientResponse); } if (m_checkGenerator.nextFloat() >= m_checkTransaction) return true; return checkConstraints(procName, clientResponse); } /** * Sets the given constraint for the table identified by the tableId of * procedure 'name'. If there is already a constraint assigned to the table, * it is updated to the new one. * * @param name * The name of the constraint. For transaction check, this should * usually be the procedure name. * @param tableId * The index of the table in the result set. * @param constraint * The constraint to use. */ protected void addConstraint(String name, int tableId, Expression constraint) { m_constraints.put(Pair.of(name, tableId), constraint); } protected void addTableConstraint(String name, Expression constraint) { addConstraint(name, 0, constraint); m_tableCheckOrder.add(name); } /** * Removes the constraint on the table identified by tableId of procedure * 'name'. Nothing happens if there is no constraint assigned to this table. * * @param name * The name of the constraint. * @param tableId * The index of the table in the result set. */ protected void removeConstraint(String name, int tableId) { m_constraints.remove(Pair.of(name, tableId)); } /** * Takes a snapshot of all the tables in the database now and check all the * rows in each table to see if they satisfy the constraints. The * constraints should be added with the table name and table id 0. * * Since the snapshot files reside on the servers, we have to copy them over * to the client in order to check. This might be an overkill, but the * alternative is to ask the user to write stored procedure for each table * and execute them on all nodes. That's not significantly better, either. * * This function blocks. Should only be run at the end. * * @return true if all tables passed the test, false otherwise. */ protected boolean checkTables() { return (true); // // String dir = "/tmp"; // String nonce = "data_verification"; // Client client = ClientFactory.createClient(getExpectedOutgoingMessageSize(), null, // false, null); // // Host ID to IP mappings // LinkedHashMap<Integer, String> hostMappings = new LinkedHashMap<Integer, String>(); // /* // * The key is the table name. the first one in the pair is the hostname, // * the second one is file name // */ // LinkedHashMap<String, Pair<String, String>> snapshotMappings = // new LinkedHashMap<String, Pair<String, String>>(); // boolean isSatisfied = true; // // // Load the native library for loading table from snapshot file // org.voltdb.EELibraryLoader.loadExecutionEngineLibrary(true); // // try { // boolean keepTrying = true; // VoltTable[] response = null; // // client.createConnection(m_host, m_username, m_password); // // Only initiate the snapshot if it's the first client // while (m_id == 0) { // // Take a snapshot of the database. This call is blocking. // response = client.callProcedure("@SnapshotSave", dir, nonce, 1).getResults(); // if (response.length != 1 || !response[0].advanceRow() // || !response[0].getString("RESULT").equals("SUCCESS")) { // if (keepTrying // && response[0].getString("ERR_MSG").contains("ALREADY EXISTS")) { // client.callProcedure("@SnapshotDelete", // new String[] { dir }, // new String[] { nonce }); // keepTrying = false; // continue; // } // // System.err.println("Failed to take snapshot"); // return false; // } // // break; // } // // // Clients other than the one that initiated the snapshot // // have to check if the snapshot has completed // if (m_id > 0) { // int maxTry = 10; // // while (maxTry-- > 0) { // boolean found = false; // response = client.callProcedure("@SnapshotStatus").getResults(); // if (response.length != 2) { // System.err.println("Failed to get snapshot status"); // return false; // } // while (response[0].advanceRow()) { // if (response[0].getString("NONCE").equals(nonce)) { // found = true; // break; // } // } // // if (found) { // // This probably means the snapshot is done // if (response[0].getLong("END_TIME") > 0) // break; // } // // try { // Thread.sleep(500); // } catch (InterruptedException e) { // return false; // } // } // } // // // Get host ID to hostname mappings // response = client.callProcedure("@SystemInformation").getResults(); // if (response.length != 1) { // System.err.println("Failed to get host ID to IP address mapping"); // return false; // } // while (response[0].advanceRow()) { // if (!response[0].getString("key").equals("hostname")) // continue; // hostMappings.put((Integer) response[0].get("node_id", VoltType.INTEGER), // response[0].getString("value")); // } // // // Do a scan to get all the file names and table names // response = client.callProcedure("@SnapshotScan", dir).getResults(); // if (response.length != 3) { // System.err.println("Failed to get snapshot filenames"); // return false; // } // // // Only copy the snapshot files we just created // while (response[0].advanceRow()) { // if (!response[0].getString("NONCE").equals(nonce)) // continue; // // String[] tables = response[0].getString("TABLES_REQUIRED").split(","); // for (String t : tables) // snapshotMappings.put(t, null); // break; // } // // while (response[2].advanceRow()) { // int id = Integer.parseInt(response[2].getString("HOST_ID")); // String tableName = response[2].getString("TABLE"); // // if (!snapshotMappings.containsKey(tableName) || !hostMappings.containsKey(id)) // continue; // // snapshotMappings.put(tableName, Pair.of(hostMappings.get(id), // response[2].getString("NAME"))); // } // } catch (NoConnectionsException e) { // e.printStackTrace(); // return false; // } catch (ProcCallException e) { // e.printStackTrace(); // return false; // } catch (UnknownHostException e) { // e.printStackTrace(); // return false; // } catch (IOException e) { // e.printStackTrace(); // return false; // } // // // Iterate through all the tables // for (String tableName : m_tableCheckOrder) { // Pair<String, String> value = snapshotMappings.get(tableName); // if (value == null) // continue; // // String hostName = value.getFirst(); // File file = new File(dir, value.getSecond()); // FileInputStream inputStream = null; // TableSaveFile saveFile = null; // long rowCount = 0; // // Pair<String, Integer> key = Pair.of(tableName, 0); // if (!m_constraints.containsKey(key) || hostName == null) // continue; // // System.err.println("Checking table " + tableName); // // // Copy the file over // String localhostName = null; // try { // localhostName = InetAddress.getLocalHost().getHostName(); // } catch (UnknownHostException e1) { // localhostName = "localhost"; // } // if (!hostName.equals("localhost") && !hostName.equals(localhostName)) { // if (!SSHTools.copyFromRemote(file, m_username, hostName, file.getPath())) { // System.err.println("Failed to copy the snapshot file " + file.getPath() // + " from host " // + hostName); // return false; // } // } // // if (!file.exists()) { // System.err.println("Snapshot file " + file.getPath() // + " cannot be copied from " // + hostName // + " to localhost"); // return false; // } // // try { // try { // inputStream = new FileInputStream(file); // saveFile = new TableSaveFile(inputStream.getChannel(), 3, null); // // // Get chunks from table // while (isSatisfied && saveFile.hasMoreChunks()) { // final BBContainer chunk = saveFile.getNextChunk(); // VoltTable table = null; // // // This probably should not happen // if (chunk == null) // continue; // // table = PrivateVoltTableFactory.createVoltTableFromBuffer(chunk.b, true); // // Now, check each row // while (isSatisfied && table.advanceRow()) { // isSatisfied = Verification.checkRow(m_constraints.get(key), // table); // rowCount++; // } // // Release the memory of the chunk we just examined, be good // chunk.discard(); // } // } finally { // if (saveFile != null) { // saveFile.close(); // } // if (inputStream != null) // inputStream.close(); // if (!hostName.equals("localhost") && !hostName.equals(localhostName) // && !file.delete()) // System.err.println("Failed to delete snapshot file " + file.getPath()); // } // } catch (FileNotFoundException e) { // e.printStackTrace(); // return false; // } catch (IOException e) { // e.printStackTrace(); // return false; // } // // if (isSatisfied) { // System.err.println("Table " + tableName // + " with " // + rowCount // + " rows passed check"); // } else { // System.err.println("Table " + tableName + " failed check"); // break; // } // } // // // Clean up the snapshot we made // try { // if (m_id == 0) { // client.callProcedure("@SnapshotDelete", // new String[] { dir }, // new String[] { nonce }).getResults(); // } // } catch (IOException e) { // e.printStackTrace(); // } catch (ProcCallException e) { // e.printStackTrace(); // } // // System.err.println("Table checking finished " // + (isSatisfied ? "successfully" : "with failures")); // // return isSatisfied; } }
true
true
protected void initializeConnection() { StatsUploaderSettings statsSettings = null; if (m_statsDatabaseURL != null && m_statsDatabaseURL.isEmpty() == false) { try { statsSettings = StatsUploaderSettings.singleton( m_statsDatabaseURL, m_statsDatabaseUser, m_statsDatabasePass, m_statsDatabaseJDBC, this.getProjectName(), (m_isLoader ? "LOADER" : "CLIENT"), m_statsPollerInterval, m_catalogContext.catalog); } catch (Throwable ex) { throw new RuntimeException("Failed to initialize StatsUploader", ex); } if (debug.val) LOG.debug("StatsUploaderSettings:\n" + statsSettings); } Client new_client = BenchmarkComponent.getClient( (m_hstoreConf.client.txn_hints ? this.getCatalog() : null), getExpectedOutgoingMessageSize(), useHeavyweightClient(), statsSettings, m_hstoreConf.client.shared_connection ); if (m_blocking) { // && isLoader == false) { if (debug.val) LOG.debug(String.format("Using BlockingClient [concurrent=%d]", m_hstoreConf.client.blocking_concurrent)); m_voltClient = new BlockingClient(new_client, m_hstoreConf.client.blocking_concurrent); } else { m_voltClient = new_client; } // scan the inputs again looking for host connections if (m_noConnections == false) { synchronized (BenchmarkComponent.class) { if (globalHasConnections.contains(new_client) == false) { this.setupConnections(); globalHasConnections.add(new_client); } } // SYNCH } } private void setupConnections() { boolean atLeastOneConnection = false; for (Site catalog_site : CatalogUtil.getAllSites(this.getCatalog())) { final int site_id = catalog_site.getId(); final String host = catalog_site.getHost().getIpaddr(); int port = catalog_site.getProc_port(); if (debug.val) LOG.debug(String.format("Creating connection to %s at %s:%d", HStoreThreadManager.formatSiteName(site_id), host, port)); try { this.createConnection(site_id, host, port); } catch (IOException ex) { String msg = String.format("Failed to connect to %s on %s:%d", HStoreThreadManager.formatSiteName(site_id), host, port); // LOG.error(msg, ex); // setState(ControlState.ERROR, msg + ": " + ex.getMessage()); // continue; throw new RuntimeException(msg, ex); } atLeastOneConnection = true; } // FOR if (!atLeastOneConnection) { setState(ControlState.ERROR, "No HOSTS specified on command line."); throw new RuntimeException("Failed to establish connections to H-Store cluster"); } } private void createConnection(final Integer site_id, final String hostname, final int port) throws UnknownHostException, IOException { if (debug.val) LOG.debug(String.format("Requesting connection to %s %s:%d", HStoreThreadManager.formatSiteName(site_id), hostname, port)); m_voltClient.createConnection(site_id, hostname, port, m_username, m_password); } // ---------------------------------------------------------------------------- // CONTROLLER COMMUNICATION METHODS // ---------------------------------------------------------------------------- protected void printControlMessage(ControlState state) { printControlMessage(state, null); } private void printControlMessage(ControlState state, String message) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%s %d,%d,%s", CONTROL_MESSAGE_PREFIX, this.getClientId(), System.currentTimeMillis(), state)); if (message != null && message.isEmpty() == false) { sb.append(",").append(message); } System.out.println(sb); } protected void answerWithError() { this.printControlMessage(m_controlState, m_reason); } protected void answerPoll() { BenchmarkComponentResults copy = this.m_txnStats.copy(); this.m_txnStats.clear(false); this.printControlMessage(m_controlState, copy.toJSONString()); } protected void answerDumpTxns() { ResponseEntries copy = new ResponseEntries(this.m_responseEntries); this.m_responseEntries.clear(); this.printControlMessage(ControlState.DUMPING, copy.toJSONString()); } protected void answerOk() { this.printControlMessage(m_controlState, "OK"); } /** * Implemented by derived classes. Loops indefinitely invoking stored * procedures. Method never returns and never receives any updates. */ @Deprecated abstract protected void runLoop() throws IOException; /** * Get the display names of the transactions that will be invoked by the * derived class. As a side effect this also retrieves the number of * transactions that can be invoked. * * @return */ abstract protected String[] getTransactionDisplayNames(); /** * Increment the internal transaction counter. This should be invoked * after the client has received a ClientResponse from the DBMS cluster * The txn_index is the offset of the transaction that was executed. This offset * is the same order as the array returned by getTransactionDisplayNames * @param cresponse - The ClientResponse returned from the server * @param txn_idx */ protected final void incrementTransactionCounter(final ClientResponse cresponse, final int txn_idx) { // Only include it if it wasn't rejected // This is actually handled in the Distributer, but it doesn't hurt to have this here Status status = cresponse.getStatus(); if (status == Status.OK || status == Status.ABORT_USER) { // TRANSACTION COUNTERS boolean is_specexec = cresponse.isSpeculative(); boolean is_dtxn = cresponse.isSinglePartition(); synchronized (m_txnStats.transactions) { m_txnStats.transactions.put(txn_idx); if (is_dtxn == false) m_txnStats.dtxns.put(txn_idx); if (is_specexec) m_txnStats.specexecs.put(txn_idx); } // SYNCH // LATENCIES COUNTERS // Ignore zero latencies... Not sure why this happens... int latency = cresponse.getClusterRoundtrip(); if (latency > 0) { Histogram<Integer> latencies = m_txnStats.latencies.get(txn_idx); if (latencies == null) { synchronized (m_txnStats.latencies) { latencies = m_txnStats.latencies.get(txn_idx); if (latencies == null) { latencies = new ObjectHistogram<Integer>(); m_txnStats.latencies.put(txn_idx, (ObjectHistogram<Integer>)latencies); } } // SYNCH } synchronized (latencies) { latencies.put(latency); } // SYNCH } // RESPONSE ENTRIES if (m_enableResponseEntries) { long timestamp = System.currentTimeMillis(); m_responseEntries.add(cresponse, m_id, txn_idx, timestamp); } // BASE PARTITIONS if (m_txnStats.isBasePartitionsEnabled()) { synchronized (m_txnStats.basePartitions) { m_txnStats.basePartitions.put(cresponse.getBasePartition()); } // SYNCH } } // else { // LOG.warn("Invalid " + m_countDisplayNames[txn_idx] + " response!\n" + cresponse); // if (cresponse.getException() != null) { // cresponse.getException().printStackTrace(); // } // if (cresponse.getStatusString() != null) { // LOG.warn(cresponse.getStatusString()); // } // // System.exit(-1); // } if (m_txnStats.isResponsesStatusesEnabled()) { synchronized (m_txnStats.responseStatuses) { m_txnStats.responseStatuses.put(status.ordinal()); } // SYNCH } } // ---------------------------------------------------------------------------- // PUBLIC UTILITY METHODS // ---------------------------------------------------------------------------- /** * Return the scale factor for this benchmark instance * @return */ public double getScaleFactor() { return (m_hstoreConf.client.scalefactor); } /** * This method will load a VoltTable into the database for the given tableName. * The database will automatically split the tuples and send to the correct partitions * The current thread will block until the the database cluster returns the result. * Can be overridden for testing purposes. * @param tableName * @param vt */ public ClientResponse loadVoltTable(String tableName, VoltTable vt) { assert(vt != null) : "Null VoltTable for '" + tableName + "'"; int rowCount = vt.getRowCount(); long rowTotal = m_tableTuples.get(tableName, 0); int byteCount = vt.getUnderlyingBufferSize(); long byteTotal = m_tableBytes.get(tableName, 0); if (trace.val) LOG.trace(String.format("%s: Loading %d new rows - TOTAL %d [bytes=%d/%d]", tableName.toUpperCase(), rowCount, rowTotal, byteCount, byteTotal)); // Load up this dirty mess... ClientResponse cr = null; if (m_noUploading == false) { boolean locked = m_hstoreConf.client.blocking_loader; if (locked) m_loaderBlock.lock(); try { int tries = 3; String procName = VoltSystemProcedure.procCallName(LoadMultipartitionTable.class); while (tries-- > 0) { try { cr = m_voltClient.callProcedure(procName, tableName, vt); } catch (ProcCallException ex) { // If this thing was rejected, then we'll allow us to try again. cr = ex.getClientResponse(); if (cr.getStatus() == Status.ABORT_REJECT && tries > 0) { if (debug.val) LOG.warn(String.format("Loading data for %s was rejected. Going to try again\n%s", tableName, cr.toString())); continue; } // Anything else needs to be thrown out of here throw ex; } break; } // WHILE } catch (Throwable ex) { throw new RuntimeException("Error when trying load data for '" + tableName + "'", ex); } finally { if (locked) m_loaderBlock.unlock(); } // SYNCH assert(cr != null); assert(cr.getStatus() == Status.OK); if (trace.val) LOG.trace(String.format("Load %s: txn #%d / %s / %d", tableName, cr.getTransactionId(), cr.getStatus(), cr.getClientHandle())); } else { cr = m_dummyResponse; } if (cr.getStatus() != Status.OK) { LOG.warn(String.format("Failed to load %d rows for '%s': %s", rowCount, tableName, cr.getStatusString()), cr.getException()); return (cr); } m_tableTuples.put(tableName, rowCount); m_tableBytes.put(tableName, byteCount); // Keep track of table stats if (m_tableStats && cr.getStatus() == Status.OK) { final CatalogContext catalogContext = this.getCatalogContext(); assert(catalogContext != null); final Table catalog_tbl = catalogContext.getTableByName(tableName); assert(catalog_tbl != null) : "Invalid table name '" + tableName + "'"; synchronized (m_tableStatsData) { TableStatistics stats = m_tableStatsData.get(catalog_tbl); if (stats == null) { stats = new TableStatistics(catalog_tbl); stats.preprocess(catalogContext.database); m_tableStatsData.put(catalog_tbl, stats); } vt.resetRowPosition(); while (vt.advanceRow()) { VoltTableRow row = vt.getRow(); stats.process(catalogContext.database, row); } // WHILE } // SYNCH } return (cr); } /** * Return an overridden transaction weight * @param txnName * @return */ protected final Integer getTransactionWeight(String txnName) { return (this.getTransactionWeight(txnName, null)); } /** * * @param txnName * @param weightIfNull * @return */ protected final Integer getTransactionWeight(String txnName, Integer weightIfNull) { Long val = this.m_txnWeights.get(txnName.toUpperCase()); if (val != null) { return (val.intValue()); } else if (m_txnWeightsDefault != null) { return (m_txnWeightsDefault); } return (weightIfNull); } /** * Get the number of tuples loaded into the given table thus far * @param tableName * @return */ public final long getTableTupleCount(String tableName) { return (m_tableTuples.get(tableName, 0)); } /** * Get a read-only histogram of the number of tuples loaded in all * of the tables * @return */ public final Histogram<String> getTableTupleCounts() { return (new ObjectHistogram<String>(m_tableTuples)); } /** * Get the number of bytes loaded into the given table thus far * @param tableName * @return */ public final long getTableBytes(String tableName) { return (m_tableBytes.get(tableName, 0)); } /** * Generate a WorkloadStatistics object based on the table stats that * were collected using loadVoltTable() * @return */ private final WorkloadStatistics generateWorkloadStatistics() { assert(m_tableStatsDir != null); final Catalog catalog = this.getCatalog(); assert(catalog != null); final Database catalog_db = CatalogUtil.getDatabase(catalog); // Make sure we call postprocess on all of our friends for (TableStatistics tableStats : m_tableStatsData.values()) { try { tableStats.postprocess(catalog_db); } catch (Exception ex) { String tableName = tableStats.getCatalogItem(catalog_db).getName(); throw new RuntimeException("Failed to process TableStatistics for '" + tableName + "'", ex); } } // FOR if (trace.val) LOG.trace(String.format("Creating WorkloadStatistics for %d tables [totalRows=%d, totalBytes=%d", m_tableStatsData.size(), m_tableTuples.getSampleCount(), m_tableBytes.getSampleCount())); WorkloadStatistics stats = new WorkloadStatistics(catalog_db); stats.apply(m_tableStatsData); return (stats); } /** * Queue a local file to be sent to the client with the given client id. * The file will be copied into the path specified by remote_file. * When the client is started it will be passed argument <parameter>=<remote_file> * @param client_id * @param parameter * @param local_file * @param remote_file */ public void sendFileToClient(int client_id, String parameter, File local_file, File remote_file) throws IOException { assert(uploader != null); this.uploader.sendFileToClient(client_id, parameter, local_file, remote_file); LOG.debug(String.format("Queuing local file '%s' to be sent to client %d as parameter '%s' to remote file '%s'", local_file, client_id, parameter, remote_file)); } /** * * @param client_id * @param parameter * @param local_file * @throws IOException */ public void sendFileToClient(int client_id, String parameter, File local_file) throws IOException { String suffix = FileUtil.getExtension(local_file); String prefix = String.format("%s-%02d-", local_file.getName().replace("." + suffix, ""), client_id); File remote_file = FileUtil.getTempFile(prefix, suffix, false); sendFileToClient(client_id, parameter, local_file, remote_file); } /** * Queue a local file to be sent to all clients * @param parameter * @param local_file * @throws IOException */ public void sendFileToAllClients(String parameter, File local_file) throws IOException { for (int i = 0, cnt = this.getNumClients(); i < cnt; i++) { sendFileToClient(i, parameter, local_file, local_file); // this.sendFileToClient(i, parameter, local_file); } // FOR } protected void setBenchmarkClientFileUploader(BenchmarkClientFileUploader uploader) { assert(this.uploader == null); this.uploader = uploader; } // ---------------------------------------------------------------------------- // CALLBACKS // ---------------------------------------------------------------------------- protected final void invokeInitCallback() { } protected final void invokeStartCallback() { this.startCallback(); } protected final void invokeStopCallback() { // If we were generating stats, then get the final WorkloadStatistics object // and write it out to a file for them to use if (m_tableStats) { WorkloadStatistics stats = this.generateWorkloadStatistics(); assert(stats != null); if (m_tableStatsDir.exists() == false) m_tableStatsDir.mkdirs(); File path = new File(m_tableStatsDir.getAbsolutePath() + "/" + this.getProjectName() + ".stats"); LOG.info("Writing table statistics data to '" + path + "'"); try { stats.save(path); } catch (IOException ex) { throw new RuntimeException("Failed to save table statistics to '" + path + "'", ex); } } this.stopCallback(); } protected final void invokeClearCallback() { m_txnStats.clear(true); m_responseEntries.clear(); this.clearCallback(); } /** * Internal callback for each POLL tick that we get from the BenchmarkController * This will invoke the tick() method that can be implemented benchmark clients * @param counter */ protected final void invokeTickCallback(int counter) { if (debug.val) LOG.debug("New Tick Update: " + counter); this.tickCallback(counter); if (debug.val) { if (this.computeTime.isEmpty() == false) { for (String txnName : this.computeTime.keySet()) { ProfileMeasurement pm = this.computeTime.get(txnName); if (pm.getInvocations() != 0) { LOG.debug(String.format("[%02d] - %s COMPUTE TIME: %s", counter, txnName, pm.debug())); pm.reset(); } } // FOR } LOG.debug("Client Queue Time: " + this.m_voltClient.getQueueTime().debug()); this.m_voltClient.getQueueTime().reset(); } } /** * Optional callback for when this BenchmarkComponent has been told to start */ public void startCallback() { // Default is to do nothing } /** * Optional callback for when this BenchmarkComponent has been told to stop * This is not a reliable callback and should only be used for testing */ public void stopCallback() { // Default is to do nothing } /** * Optional callback for when this BenchmarkComponent has been told to clear its * internal counters. */ public void clearCallback() { // Default is to do nothing } /** * Internal callback for each POLL tick that we get from the BenchmarkController * @param counter The number of times we have called this callback in the past */ public void tickCallback(int counter) { // Default is to do nothing! } // ---------------------------------------------------------------------------- // PROFILING METHODS // ---------------------------------------------------------------------------- protected synchronized void startComputeTime(String txnName) { ProfileMeasurement pm = this.computeTime.get(txnName); if (pm == null) { pm = new ProfileMeasurement(txnName); this.computeTime.put(txnName, pm); } pm.start(); } protected synchronized void stopComputeTime(String txnName) { ProfileMeasurement pm = this.computeTime.get(txnName); assert(pm != null) : "Unexpected " + txnName; pm.stop(); } protected ProfileMeasurement getComputeTime(String txnName) { return (this.computeTime.get(txnName)); } protected boolean useHeavyweightClient() { return false; } /** * Implemented by derived classes. Invoke a single procedure without running * the network. This allows BenchmarkComponent to control the rate at which * transactions are generated. * * @return True if an invocation was queued and false otherwise */ protected boolean runOnce() throws IOException { throw new UnsupportedOperationException(); } /** * Hint used when constructing the Client to control the size of buffers * allocated for message serialization * * @return */ protected int getExpectedOutgoingMessageSize() { return 128; } public ControlPipe createControlPipe(InputStream in) { m_controlPipe = new ControlPipe(this, in, m_controlPipeAutoStart); return (m_controlPipe); } /** * Return the number of partitions in the cluster for this benchmark invocation * @return */ public final int getNumPartitions() { return (m_numPartitions); } /** * Return the DBMS client handle * This Client will already be connected to the database cluster * @return */ public final Client getClientHandle() { return (m_voltClient); } /** * Special hook for setting the DBMS client handle * This should only be invoked for RegressionSuite test cases * @param client */ protected void setClientHandle(Client client) { m_voltClient = client; } /** * Return the unique client id for this invocation of BenchmarkComponent * @return */ public final int getClientId() { return (m_id); } /** * Return the total number of clients for this benchmark invocation * @return */ public final int getNumClients() { return (m_numClients); } /** * Returns true if this BenchmarkComponent is not going to make any * client connections to an H-Store cluster. This is used for testing */ protected final boolean noClientConnections() { return (m_noConnections); } /** * Return the file path to the catalog that was loaded for this benchmark invocation * @return */ public File getCatalogPath() { return (m_catalogPath); } /** * Return the project name of this benchmark * @return */ public final String getProjectName() { return (m_projectName); } public final int getCurrentTickCounter() { return (m_tickCounter); } /** * Return the catalog used for this benchmark. * @return * @throws Exception */ @Deprecated public Catalog getCatalog() { return (this.getCatalogContext().catalog); } /** * Return the CatalogContext used for this benchmark * @return */ public CatalogContext getCatalogContext() { // Read back the catalog and populate catalog object if (m_catalogContext == null) { m_catalogContext = getCatalogContext(m_catalogPath); } return (m_catalogContext); } public void setCatalogContext(CatalogContext catalogContext) { m_catalogContext = catalogContext; } public void applyPartitionPlan(File partitionPlanPath) { CatalogContext catalogContext = this.getCatalogContext(); BenchmarkComponent.applyPartitionPlan(catalogContext.database, partitionPlanPath); } /** * Get the HStoreConf handle * @return */ public HStoreConf getHStoreConf() { return (m_hstoreConf); } public void setState(final ControlState state, final String reason) { m_controlState = state; if (m_reason.equals("") == false) m_reason += (" " + reason); else m_reason = reason; } private boolean checkConstraints(String procName, ClientResponse response) { boolean isSatisfied = true; int orig_position = -1; // Check if all the tables in the result set satisfy the constraints. for (int i = 0; isSatisfied && i < response.getResults().length; i++) { Pair<String, Integer> key = Pair.of(procName, i); if (!m_constraints.containsKey(key)) continue; VoltTable table = response.getResults()[i]; orig_position = table.getActiveRowIndex(); table.resetRowPosition(); // Iterate through all rows and check if they satisfy the // constraints. while (isSatisfied && table.advanceRow()) { isSatisfied = Verification.checkRow(m_constraints.get(key), table); } // Have to reset the position to its original position. if (orig_position < 0) table.resetRowPosition(); else table.advanceToRow(orig_position); } if (!isSatisfied) LOG.error("Transaction " + procName + " failed check"); return isSatisfied; } /** * Performs constraint checking on the result set in clientResponse. It does * simple sanity checks like if the response code is SUCCESS. If the check * transaction flag is set to true by calling setCheckTransaction(), then it * will check the result set against constraints. * * @param procName * The name of the procedure * @param clientResponse * The client response * @param errorExpected * true if the response is expected to be an error. * @return true if it passes all tests, false otherwise */ protected boolean checkTransaction(String procName, ClientResponse clientResponse, boolean abortExpected, boolean errorExpected) { final Status status = clientResponse.getStatus(); if (status != Status.OK) { if (errorExpected) return true; if (abortExpected && status == Status.ABORT_USER) return true; if (status == Status.ABORT_CONNECTION_LOST) { return false; } if (clientResponse.getException() != null) { clientResponse.getException().printStackTrace(); } if (clientResponse.getStatusString() != null) { LOG.warn(clientResponse.getStatusString()); } throw new RuntimeException("Invalid " + procName + " response!\n" + clientResponse); } if (m_checkGenerator.nextFloat() >= m_checkTransaction) return true; return checkConstraints(procName, clientResponse); } /** * Sets the given constraint for the table identified by the tableId of * procedure 'name'. If there is already a constraint assigned to the table, * it is updated to the new one. * * @param name * The name of the constraint. For transaction check, this should * usually be the procedure name. * @param tableId * The index of the table in the result set. * @param constraint * The constraint to use. */ protected void addConstraint(String name, int tableId, Expression constraint) { m_constraints.put(Pair.of(name, tableId), constraint); } protected void addTableConstraint(String name, Expression constraint) { addConstraint(name, 0, constraint); m_tableCheckOrder.add(name); } /** * Removes the constraint on the table identified by tableId of procedure * 'name'. Nothing happens if there is no constraint assigned to this table. * * @param name * The name of the constraint. * @param tableId * The index of the table in the result set. */ protected void removeConstraint(String name, int tableId) { m_constraints.remove(Pair.of(name, tableId)); } /** * Takes a snapshot of all the tables in the database now and check all the * rows in each table to see if they satisfy the constraints. The * constraints should be added with the table name and table id 0. * * Since the snapshot files reside on the servers, we have to copy them over * to the client in order to check. This might be an overkill, but the * alternative is to ask the user to write stored procedure for each table * and execute them on all nodes. That's not significantly better, either. * * This function blocks. Should only be run at the end. * * @return true if all tables passed the test, false otherwise. */ protected boolean checkTables() { return (true); // // String dir = "/tmp"; // String nonce = "data_verification"; // Client client = ClientFactory.createClient(getExpectedOutgoingMessageSize(), null, // false, null); // // Host ID to IP mappings // LinkedHashMap<Integer, String> hostMappings = new LinkedHashMap<Integer, String>(); // /* // * The key is the table name. the first one in the pair is the hostname, // * the second one is file name // */ // LinkedHashMap<String, Pair<String, String>> snapshotMappings = // new LinkedHashMap<String, Pair<String, String>>(); // boolean isSatisfied = true; // // // Load the native library for loading table from snapshot file // org.voltdb.EELibraryLoader.loadExecutionEngineLibrary(true); // // try { // boolean keepTrying = true; // VoltTable[] response = null; // // client.createConnection(m_host, m_username, m_password); // // Only initiate the snapshot if it's the first client // while (m_id == 0) { // // Take a snapshot of the database. This call is blocking. // response = client.callProcedure("@SnapshotSave", dir, nonce, 1).getResults(); // if (response.length != 1 || !response[0].advanceRow() // || !response[0].getString("RESULT").equals("SUCCESS")) { // if (keepTrying // && response[0].getString("ERR_MSG").contains("ALREADY EXISTS")) { // client.callProcedure("@SnapshotDelete", // new String[] { dir }, // new String[] { nonce }); // keepTrying = false; // continue; // } // // System.err.println("Failed to take snapshot"); // return false; // } // // break; // } // // // Clients other than the one that initiated the snapshot // // have to check if the snapshot has completed // if (m_id > 0) { // int maxTry = 10; // // while (maxTry-- > 0) { // boolean found = false; // response = client.callProcedure("@SnapshotStatus").getResults(); // if (response.length != 2) { // System.err.println("Failed to get snapshot status"); // return false; // } // while (response[0].advanceRow()) { // if (response[0].getString("NONCE").equals(nonce)) { // found = true; // break; // } // } // // if (found) { // // This probably means the snapshot is done // if (response[0].getLong("END_TIME") > 0) // break; // } // // try { // Thread.sleep(500); // } catch (InterruptedException e) { // return false; // } // } // } // // // Get host ID to hostname mappings // response = client.callProcedure("@SystemInformation").getResults(); // if (response.length != 1) { // System.err.println("Failed to get host ID to IP address mapping"); // return false; // } // while (response[0].advanceRow()) { // if (!response[0].getString("key").equals("hostname")) // continue; // hostMappings.put((Integer) response[0].get("node_id", VoltType.INTEGER), // response[0].getString("value")); // } // // // Do a scan to get all the file names and table names // response = client.callProcedure("@SnapshotScan", dir).getResults(); // if (response.length != 3) { // System.err.println("Failed to get snapshot filenames"); // return false; // } // // // Only copy the snapshot files we just created // while (response[0].advanceRow()) { // if (!response[0].getString("NONCE").equals(nonce)) // continue; // // String[] tables = response[0].getString("TABLES_REQUIRED").split(","); // for (String t : tables) // snapshotMappings.put(t, null); // break; // } // // while (response[2].advanceRow()) { // int id = Integer.parseInt(response[2].getString("HOST_ID")); // String tableName = response[2].getString("TABLE"); // // if (!snapshotMappings.containsKey(tableName) || !hostMappings.containsKey(id)) // continue; // // snapshotMappings.put(tableName, Pair.of(hostMappings.get(id), // response[2].getString("NAME"))); // } // } catch (NoConnectionsException e) { // e.printStackTrace(); // return false; // } catch (ProcCallException e) { // e.printStackTrace(); // return false; // } catch (UnknownHostException e) { // e.printStackTrace(); // return false; // } catch (IOException e) { // e.printStackTrace(); // return false; // } // // // Iterate through all the tables // for (String tableName : m_tableCheckOrder) { // Pair<String, String> value = snapshotMappings.get(tableName); // if (value == null) // continue; // // String hostName = value.getFirst(); // File file = new File(dir, value.getSecond()); // FileInputStream inputStream = null; // TableSaveFile saveFile = null; // long rowCount = 0; // // Pair<String, Integer> key = Pair.of(tableName, 0); // if (!m_constraints.containsKey(key) || hostName == null) // continue; // // System.err.println("Checking table " + tableName); // // // Copy the file over // String localhostName = null; // try { // localhostName = InetAddress.getLocalHost().getHostName(); // } catch (UnknownHostException e1) { // localhostName = "localhost"; // } // if (!hostName.equals("localhost") && !hostName.equals(localhostName)) { // if (!SSHTools.copyFromRemote(file, m_username, hostName, file.getPath())) { // System.err.println("Failed to copy the snapshot file " + file.getPath() // + " from host " // + hostName); // return false; // } // } // // if (!file.exists()) { // System.err.println("Snapshot file " + file.getPath() // + " cannot be copied from " // + hostName // + " to localhost"); // return false; // } // // try { // try { // inputStream = new FileInputStream(file); // saveFile = new TableSaveFile(inputStream.getChannel(), 3, null); // // // Get chunks from table // while (isSatisfied && saveFile.hasMoreChunks()) { // final BBContainer chunk = saveFile.getNextChunk(); // VoltTable table = null; // // // This probably should not happen // if (chunk == null) // continue; // // table = PrivateVoltTableFactory.createVoltTableFromBuffer(chunk.b, true); // // Now, check each row // while (isSatisfied && table.advanceRow()) { // isSatisfied = Verification.checkRow(m_constraints.get(key), // table); // rowCount++; // } // // Release the memory of the chunk we just examined, be good // chunk.discard(); // } // } finally { // if (saveFile != null) { // saveFile.close(); // } // if (inputStream != null) // inputStream.close(); // if (!hostName.equals("localhost") && !hostName.equals(localhostName) // && !file.delete()) // System.err.println("Failed to delete snapshot file " + file.getPath()); // } // } catch (FileNotFoundException e) { // e.printStackTrace(); // return false; // } catch (IOException e) { // e.printStackTrace(); // return false; // } // // if (isSatisfied) { // System.err.println("Table " + tableName // + " with " // + rowCount // + " rows passed check"); // } else { // System.err.println("Table " + tableName + " failed check"); // break; // } // } // // // Clean up the snapshot we made // try { // if (m_id == 0) { // client.callProcedure("@SnapshotDelete", // new String[] { dir }, // new String[] { nonce }).getResults(); // } // } catch (IOException e) { // e.printStackTrace(); // } catch (ProcCallException e) { // e.printStackTrace(); // } // // System.err.println("Table checking finished " // + (isSatisfied ? "successfully" : "with failures")); // // return isSatisfied; } }
protected void initializeConnection() { StatsUploaderSettings statsSettings = null; if (m_statsDatabaseURL != null && m_statsDatabaseURL.isEmpty() == false) { try { statsSettings = StatsUploaderSettings.singleton( m_statsDatabaseURL, m_statsDatabaseUser, m_statsDatabasePass, m_statsDatabaseJDBC, this.getProjectName(), (m_isLoader ? "LOADER" : "CLIENT"), m_statsPollerInterval, m_catalogContext.catalog); } catch (Throwable ex) { throw new RuntimeException("Failed to initialize StatsUploader", ex); } if (debug.val) LOG.debug("StatsUploaderSettings:\n" + statsSettings); } Client new_client = BenchmarkComponent.getClient( (m_hstoreConf.client.txn_hints ? this.getCatalog() : null), getExpectedOutgoingMessageSize(), useHeavyweightClient(), statsSettings, m_hstoreConf.client.shared_connection ); if (m_blocking) { // && isLoader == false) { if (debug.val) LOG.debug(String.format("Using BlockingClient [concurrent=%d]", m_hstoreConf.client.blocking_concurrent)); m_voltClient = new BlockingClient(new_client, m_hstoreConf.client.blocking_concurrent); } else { m_voltClient = new_client; } // scan the inputs again looking for host connections if (m_noConnections == false) { synchronized (BenchmarkComponent.class) { if (globalHasConnections.contains(new_client) == false) { this.setupConnections(); globalHasConnections.add(new_client); } } // SYNCH } } private void setupConnections() { boolean atLeastOneConnection = false; for (Site catalog_site : CatalogUtil.getAllSites(this.getCatalog())) { final int site_id = catalog_site.getId(); final String host = catalog_site.getHost().getIpaddr(); int port = catalog_site.getProc_port(); if (debug.val) LOG.debug(String.format("Creating connection to %s at %s:%d", HStoreThreadManager.formatSiteName(site_id), host, port)); try { this.createConnection(site_id, host, port); } catch (IOException ex) { String msg = String.format("Failed to connect to %s on %s:%d", HStoreThreadManager.formatSiteName(site_id), host, port); // LOG.error(msg, ex); // setState(ControlState.ERROR, msg + ": " + ex.getMessage()); // continue; throw new RuntimeException(msg, ex); } atLeastOneConnection = true; } // FOR if (!atLeastOneConnection) { setState(ControlState.ERROR, "No HOSTS specified on command line."); throw new RuntimeException("Failed to establish connections to H-Store cluster"); } } private void createConnection(final Integer site_id, final String hostname, final int port) throws UnknownHostException, IOException { if (debug.val) LOG.debug(String.format("Requesting connection to %s %s:%d", HStoreThreadManager.formatSiteName(site_id), hostname, port)); m_voltClient.createConnection(site_id, hostname, port, m_username, m_password); } // ---------------------------------------------------------------------------- // CONTROLLER COMMUNICATION METHODS // ---------------------------------------------------------------------------- protected void printControlMessage(ControlState state) { printControlMessage(state, null); } private void printControlMessage(ControlState state, String message) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%s %d,%d,%s", CONTROL_MESSAGE_PREFIX, this.getClientId(), System.currentTimeMillis(), state)); if (message != null && message.isEmpty() == false) { sb.append(",").append(message); } System.out.println(sb); } protected void answerWithError() { this.printControlMessage(m_controlState, m_reason); } protected void answerPoll() { BenchmarkComponentResults copy = this.m_txnStats.copy(); this.m_txnStats.clear(false); this.printControlMessage(m_controlState, copy.toJSONString()); } protected void answerDumpTxns() { ResponseEntries copy = new ResponseEntries(this.m_responseEntries); this.m_responseEntries.clear(); this.printControlMessage(ControlState.DUMPING, copy.toJSONString()); } protected void answerOk() { this.printControlMessage(m_controlState, "OK"); } /** * Implemented by derived classes. Loops indefinitely invoking stored * procedures. Method never returns and never receives any updates. */ @Deprecated abstract protected void runLoop() throws IOException; /** * Get the display names of the transactions that will be invoked by the * derived class. As a side effect this also retrieves the number of * transactions that can be invoked. * * @return */ abstract protected String[] getTransactionDisplayNames(); /** * Increment the internal transaction counter. This should be invoked * after the client has received a ClientResponse from the DBMS cluster * The txn_index is the offset of the transaction that was executed. This offset * is the same order as the array returned by getTransactionDisplayNames * @param cresponse - The ClientResponse returned from the server * @param txn_idx */ protected final void incrementTransactionCounter(final ClientResponse cresponse, final int txn_idx) { // Only include it if it wasn't rejected // This is actually handled in the Distributer, but it doesn't hurt to have this here Status status = cresponse.getStatus(); if (status == Status.OK || status == Status.ABORT_USER) { // TRANSACTION COUNTERS boolean is_specexec = cresponse.isSpeculative(); boolean is_dtxn = cresponse.isSinglePartition(); synchronized (m_txnStats.transactions) { m_txnStats.transactions.put(txn_idx); if (is_dtxn == false) m_txnStats.dtxns.put(txn_idx); if (is_specexec) m_txnStats.specexecs.put(txn_idx); } // SYNCH // LATENCIES COUNTERS // Ignore zero latencies... Not sure why this happens... int latency = cresponse.getClusterRoundtrip(); if (latency > 0) { Histogram<Integer> latencies = m_txnStats.latencies.get(txn_idx); if (latencies == null) { synchronized (m_txnStats.latencies) { latencies = m_txnStats.latencies.get(txn_idx); if (latencies == null) { latencies = new ObjectHistogram<Integer>(); m_txnStats.latencies.put(txn_idx, (ObjectHistogram<Integer>)latencies); } } // SYNCH } synchronized (latencies) { latencies.put(latency); } // SYNCH } // RESPONSE ENTRIES if (m_enableResponseEntries) { long timestamp = System.currentTimeMillis(); m_responseEntries.add(cresponse, m_id, txn_idx, timestamp); } // BASE PARTITIONS if (m_txnStats.isBasePartitionsEnabled()) { synchronized (m_txnStats.basePartitions) { m_txnStats.basePartitions.put(cresponse.getBasePartition()); } // SYNCH } } // else { // LOG.warn("Invalid " + m_countDisplayNames[txn_idx] + " response!\n" + cresponse); // if (cresponse.getException() != null) { // cresponse.getException().printStackTrace(); // } // if (cresponse.getStatusString() != null) { // LOG.warn(cresponse.getStatusString()); // } // // System.exit(-1); // } if (m_txnStats.isResponsesStatusesEnabled()) { synchronized (m_txnStats.responseStatuses) { m_txnStats.responseStatuses.put(status.ordinal()); } // SYNCH } } // ---------------------------------------------------------------------------- // PUBLIC UTILITY METHODS // ---------------------------------------------------------------------------- /** * Return the scale factor for this benchmark instance * @return */ public double getScaleFactor() { return (m_hstoreConf.client.scalefactor); } /** * This method will load a VoltTable into the database for the given tableName. * The database will automatically split the tuples and send to the correct partitions * The current thread will block until the the database cluster returns the result. * Can be overridden for testing purposes. * @param tableName * @param vt */ public ClientResponse loadVoltTable(String tableName, VoltTable vt) { assert(vt != null) : "Null VoltTable for '" + tableName + "'"; int rowCount = vt.getRowCount(); long rowTotal = m_tableTuples.get(tableName, 0); int byteCount = vt.getUnderlyingBufferSize(); long byteTotal = m_tableBytes.get(tableName, 0); if (trace.val) LOG.trace(String.format("%s: Loading %d new rows - TOTAL %d [bytes=%d/%d]", tableName.toUpperCase(), rowCount, rowTotal, byteCount, byteTotal)); // Load up this dirty mess... ClientResponse cr = null; if (m_noUploading == false) { boolean locked = m_hstoreConf.client.blocking_loader; if (locked) m_loaderBlock.lock(); try { int tries = 3; String procName = VoltSystemProcedure.procCallName(LoadMultipartitionTable.class); while (tries-- > 0) { try { cr = m_voltClient.callProcedure(procName, tableName, vt); } catch (ProcCallException ex) { // If this thing was rejected, then we'll allow us to try again. cr = ex.getClientResponse(); if (cr.getStatus() == Status.ABORT_REJECT && tries > 0) { if (debug.val) LOG.warn(String.format("Loading data for %s was rejected. Going to try again\n%s", tableName, cr.toString())); continue; } // Anything else needs to be thrown out of here throw ex; } break; } // WHILE } catch (Throwable ex) { throw new RuntimeException("Error when trying load data for '" + tableName + "'", ex); } finally { if (locked) m_loaderBlock.unlock(); } // SYNCH assert(cr != null); assert(cr.getStatus() == Status.OK); if (trace.val) LOG.trace(String.format("Load %s: txn #%d / %s / %d", tableName, cr.getTransactionId(), cr.getStatus(), cr.getClientHandle())); } else { cr = m_dummyResponse; } if (cr.getStatus() != Status.OK) { LOG.warn(String.format("Failed to load %d rows for '%s': %s", rowCount, tableName, cr.getStatusString()), cr.getException()); return (cr); } m_tableTuples.put(tableName, rowCount); m_tableBytes.put(tableName, byteCount); // Keep track of table stats if (m_tableStats && cr.getStatus() == Status.OK) { final CatalogContext catalogContext = this.getCatalogContext(); assert(catalogContext != null); final Table catalog_tbl = catalogContext.getTableByName(tableName); assert(catalog_tbl != null) : "Invalid table name '" + tableName + "'"; synchronized (m_tableStatsData) { TableStatistics stats = m_tableStatsData.get(catalog_tbl); if (stats == null) { stats = new TableStatistics(catalog_tbl); stats.preprocess(catalogContext.database); m_tableStatsData.put(catalog_tbl, stats); } vt.resetRowPosition(); while (vt.advanceRow()) { VoltTableRow row = vt.getRow(); stats.process(catalogContext.database, row); } // WHILE } // SYNCH } return (cr); } /** * Return an overridden transaction weight * @param txnName * @return */ protected final Integer getTransactionWeight(String txnName) { return (this.getTransactionWeight(txnName, null)); } /** * * @param txnName * @param weightIfNull * @return */ protected final Integer getTransactionWeight(String txnName, Integer weightIfNull) { Long val = this.m_txnWeights.get(txnName.toUpperCase()); if (val != null) { return (val.intValue()); } else if (m_txnWeightsDefault != null) { return (m_txnWeightsDefault); } return (weightIfNull); } /** * Get the number of tuples loaded into the given table thus far * @param tableName * @return */ public final long getTableTupleCount(String tableName) { return (m_tableTuples.get(tableName, 0)); } /** * Get a read-only histogram of the number of tuples loaded in all * of the tables * @return */ public final Histogram<String> getTableTupleCounts() { return (new ObjectHistogram<String>(m_tableTuples)); } /** * Get the number of bytes loaded into the given table thus far * @param tableName * @return */ public final long getTableBytes(String tableName) { return (m_tableBytes.get(tableName, 0)); } /** * Generate a WorkloadStatistics object based on the table stats that * were collected using loadVoltTable() * @return */ private final WorkloadStatistics generateWorkloadStatistics() { assert(m_tableStatsDir != null); final Catalog catalog = this.getCatalog(); assert(catalog != null); final Database catalog_db = CatalogUtil.getDatabase(catalog); // Make sure we call postprocess on all of our friends for (TableStatistics tableStats : m_tableStatsData.values()) { try { tableStats.postprocess(catalog_db); } catch (Exception ex) { String tableName = tableStats.getCatalogItem(catalog_db).getName(); throw new RuntimeException("Failed to process TableStatistics for '" + tableName + "'", ex); } } // FOR if (trace.val) LOG.trace(String.format("Creating WorkloadStatistics for %d tables [totalRows=%d, totalBytes=%d", m_tableStatsData.size(), m_tableTuples.getSampleCount(), m_tableBytes.getSampleCount())); WorkloadStatistics stats = new WorkloadStatistics(catalog_db); stats.apply(m_tableStatsData); return (stats); } /** * Queue a local file to be sent to the client with the given client id. * The file will be copied into the path specified by remote_file. * When the client is started it will be passed argument <parameter>=<remote_file> * @param client_id * @param parameter * @param local_file * @param remote_file */ public void sendFileToClient(int client_id, String parameter, File local_file, File remote_file) throws IOException { assert(uploader != null); this.uploader.sendFileToClient(client_id, parameter, local_file, remote_file); LOG.debug(String.format("Queuing local file '%s' to be sent to client %d as parameter '%s' to remote file '%s'", local_file, client_id, parameter, remote_file)); } /** * * @param client_id * @param parameter * @param local_file * @throws IOException */ public void sendFileToClient(int client_id, String parameter, File local_file) throws IOException { String suffix = FileUtil.getExtension(local_file); String prefix = String.format("%s-%02d-", local_file.getName().replace("." + suffix, ""), client_id); File remote_file = FileUtil.getTempFile(prefix, suffix, false); sendFileToClient(client_id, parameter, local_file, remote_file); } /** * Queue a local file to be sent to all clients * @param parameter * @param local_file * @throws IOException */ public void sendFileToAllClients(String parameter, File local_file) throws IOException { for (int i = 0, cnt = this.getNumClients(); i < cnt; i++) { sendFileToClient(i, parameter, local_file, local_file); // this.sendFileToClient(i, parameter, local_file); } // FOR } protected void setBenchmarkClientFileUploader(BenchmarkClientFileUploader uploader) { assert(this.uploader == null); this.uploader = uploader; } // ---------------------------------------------------------------------------- // CALLBACKS // ---------------------------------------------------------------------------- protected final void invokeInitCallback() { } protected final void invokeStartCallback() { this.startCallback(); } protected final void invokeStopCallback() { // If we were generating stats, then get the final WorkloadStatistics object // and write it out to a file for them to use if (m_tableStats) { WorkloadStatistics stats = this.generateWorkloadStatistics(); assert(stats != null); if (m_tableStatsDir.exists() == false) m_tableStatsDir.mkdirs(); File path = new File(m_tableStatsDir.getAbsolutePath() + "/" + this.getProjectName() + ".stats"); LOG.info("Writing table statistics data to '" + path + "'"); try { stats.save(path); } catch (IOException ex) { throw new RuntimeException("Failed to save table statistics to '" + path + "'", ex); } } this.stopCallback(); } protected final void invokeClearCallback() { m_txnStats.clear(true); m_responseEntries.clear(); this.clearCallback(); } /** * Internal callback for each POLL tick that we get from the BenchmarkController * This will invoke the tick() method that can be implemented benchmark clients * @param counter */ protected final void invokeTickCallback(int counter) { if (debug.val) LOG.debug("New Tick Update: " + counter); this.tickCallback(counter); if (debug.val) { if (this.computeTime.isEmpty() == false) { for (String txnName : this.computeTime.keySet()) { ProfileMeasurement pm = this.computeTime.get(txnName); if (pm.getInvocations() != 0) { LOG.debug(String.format("[%02d] - %s COMPUTE TIME: %s", counter, txnName, pm.debug())); pm.reset(); } } // FOR } LOG.debug("Client Queue Time: " + this.m_voltClient.getQueueTime().debug()); this.m_voltClient.getQueueTime().reset(); } } /** * Optional callback for when this BenchmarkComponent has been told to start */ public void startCallback() { // Default is to do nothing } /** * Optional callback for when this BenchmarkComponent has been told to stop * This is not a reliable callback and should only be used for testing */ public void stopCallback() { // Default is to do nothing } /** * Optional callback for when this BenchmarkComponent has been told to clear its * internal counters. */ public void clearCallback() { // Default is to do nothing } /** * Internal callback for each POLL tick that we get from the BenchmarkController * @param counter The number of times we have called this callback in the past */ public void tickCallback(int counter) { // Default is to do nothing! } // ---------------------------------------------------------------------------- // PROFILING METHODS // ---------------------------------------------------------------------------- protected synchronized void startComputeTime(String txnName) { ProfileMeasurement pm = this.computeTime.get(txnName); if (pm == null) { pm = new ProfileMeasurement(txnName); this.computeTime.put(txnName, pm); } pm.start(); } protected synchronized void stopComputeTime(String txnName) { ProfileMeasurement pm = this.computeTime.get(txnName); assert(pm != null) : "Unexpected " + txnName; pm.stop(); } protected ProfileMeasurement getComputeTime(String txnName) { return (this.computeTime.get(txnName)); } protected boolean useHeavyweightClient() { return false; } /** * Implemented by derived classes. Invoke a single procedure without running * the network. This allows BenchmarkComponent to control the rate at which * transactions are generated. * * @return True if an invocation was queued and false otherwise */ protected boolean runOnce() throws IOException { throw new UnsupportedOperationException(); } /** * Hint used when constructing the Client to control the size of buffers * allocated for message serialization * * @return */ protected int getExpectedOutgoingMessageSize() { return 128; } public ControlPipe createControlPipe(InputStream in) { m_controlPipe = new ControlPipe(this, in, m_controlPipeAutoStart); return (m_controlPipe); } /** * Return the number of partitions in the cluster for this benchmark invocation * @return */ public final int getNumPartitions() { return (m_numPartitions); } /** * Return the DBMS client handle * This Client will already be connected to the database cluster * @return */ public final Client getClientHandle() { return (m_voltClient); } /** * Special hook for setting the DBMS client handle * This should only be invoked for RegressionSuite test cases * @param client */ protected void setClientHandle(Client client) { m_voltClient = client; } /** * Return the unique client id for this invocation of BenchmarkComponent * @return */ public final int getClientId() { return (m_id); } /** * Return the total number of clients for this benchmark invocation * @return */ public final int getNumClients() { return (m_numClients); } /** * Returns true if this BenchmarkComponent is not going to make any * client connections to an H-Store cluster. This is used for testing */ protected final boolean noClientConnections() { return (m_noConnections); } /** * Return the file path to the catalog that was loaded for this benchmark invocation * @return */ public File getCatalogPath() { return (m_catalogPath); } /** * Return the project name of this benchmark * @return */ public final String getProjectName() { return (m_projectName); } public final int getCurrentTickCounter() { return (m_tickCounter); } /** * Return the catalog used for this benchmark. * @return * @throws Exception */ @Deprecated public Catalog getCatalog() { return (this.getCatalogContext().catalog); } /** * Return the CatalogContext used for this benchmark * @return */ public CatalogContext getCatalogContext() { // Read back the catalog and populate catalog object if (m_catalogContext == null) { m_catalogContext = getCatalogContext(m_catalogPath); } return (m_catalogContext); } public void setCatalogContext(CatalogContext catalogContext) { m_catalogContext = catalogContext; } public void applyPartitionPlan(File partitionPlanPath) { CatalogContext catalogContext = this.getCatalogContext(); BenchmarkComponent.applyPartitionPlan(catalogContext.database, partitionPlanPath); } /** * Get the HStoreConf handle * @return */ public HStoreConf getHStoreConf() { return (m_hstoreConf); } public void setState(final ControlState state, final String reason) { m_controlState = state; if (m_reason.equals("") == false) m_reason += (" " + reason); else m_reason = reason; } private boolean checkConstraints(String procName, ClientResponse response) { boolean isSatisfied = true; int orig_position = -1; // Check if all the tables in the result set satisfy the constraints. for (int i = 0; isSatisfied && i < response.getResults().length; i++) { Pair<String, Integer> key = Pair.of(procName, i); if (!m_constraints.containsKey(key)) continue; VoltTable table = response.getResults()[i]; orig_position = table.getActiveRowIndex(); table.resetRowPosition(); // Iterate through all rows and check if they satisfy the // constraints. while (isSatisfied && table.advanceRow()) { isSatisfied = Verification.checkRow(m_constraints.get(key), table); } // Have to reset the position to its original position. if (orig_position < 0) table.resetRowPosition(); else table.advanceToRow(orig_position); } if (!isSatisfied) LOG.error("Transaction " + procName + " failed check"); return isSatisfied; } /** * Performs constraint checking on the result set in clientResponse. It does * simple sanity checks like if the response code is SUCCESS. If the check * transaction flag is set to true by calling setCheckTransaction(), then it * will check the result set against constraints. * * @param procName * The name of the procedure * @param clientResponse * The client response * @param errorExpected * true if the response is expected to be an error. * @return true if it passes all tests, false otherwise */ protected boolean checkTransaction(String procName, ClientResponse clientResponse, boolean abortExpected, boolean errorExpected) { final Status status = clientResponse.getStatus(); if (status != Status.OK) { if (errorExpected) return true; if (abortExpected && status == Status.ABORT_USER) return true; if (status == Status.ABORT_CONNECTION_LOST) { return false; } if (status == Status.ABORT_REJECT) { return false; } if (clientResponse.getException() != null) { clientResponse.getException().printStackTrace(); } if (clientResponse.getStatusString() != null) { LOG.warn(clientResponse.getStatusString()); } throw new RuntimeException("Invalid " + procName + " response!\n" + clientResponse); } if (m_checkGenerator.nextFloat() >= m_checkTransaction) return true; return checkConstraints(procName, clientResponse); } /** * Sets the given constraint for the table identified by the tableId of * procedure 'name'. If there is already a constraint assigned to the table, * it is updated to the new one. * * @param name * The name of the constraint. For transaction check, this should * usually be the procedure name. * @param tableId * The index of the table in the result set. * @param constraint * The constraint to use. */ protected void addConstraint(String name, int tableId, Expression constraint) { m_constraints.put(Pair.of(name, tableId), constraint); } protected void addTableConstraint(String name, Expression constraint) { addConstraint(name, 0, constraint); m_tableCheckOrder.add(name); } /** * Removes the constraint on the table identified by tableId of procedure * 'name'. Nothing happens if there is no constraint assigned to this table. * * @param name * The name of the constraint. * @param tableId * The index of the table in the result set. */ protected void removeConstraint(String name, int tableId) { m_constraints.remove(Pair.of(name, tableId)); } /** * Takes a snapshot of all the tables in the database now and check all the * rows in each table to see if they satisfy the constraints. The * constraints should be added with the table name and table id 0. * * Since the snapshot files reside on the servers, we have to copy them over * to the client in order to check. This might be an overkill, but the * alternative is to ask the user to write stored procedure for each table * and execute them on all nodes. That's not significantly better, either. * * This function blocks. Should only be run at the end. * * @return true if all tables passed the test, false otherwise. */ protected boolean checkTables() { return (true); // // String dir = "/tmp"; // String nonce = "data_verification"; // Client client = ClientFactory.createClient(getExpectedOutgoingMessageSize(), null, // false, null); // // Host ID to IP mappings // LinkedHashMap<Integer, String> hostMappings = new LinkedHashMap<Integer, String>(); // /* // * The key is the table name. the first one in the pair is the hostname, // * the second one is file name // */ // LinkedHashMap<String, Pair<String, String>> snapshotMappings = // new LinkedHashMap<String, Pair<String, String>>(); // boolean isSatisfied = true; // // // Load the native library for loading table from snapshot file // org.voltdb.EELibraryLoader.loadExecutionEngineLibrary(true); // // try { // boolean keepTrying = true; // VoltTable[] response = null; // // client.createConnection(m_host, m_username, m_password); // // Only initiate the snapshot if it's the first client // while (m_id == 0) { // // Take a snapshot of the database. This call is blocking. // response = client.callProcedure("@SnapshotSave", dir, nonce, 1).getResults(); // if (response.length != 1 || !response[0].advanceRow() // || !response[0].getString("RESULT").equals("SUCCESS")) { // if (keepTrying // && response[0].getString("ERR_MSG").contains("ALREADY EXISTS")) { // client.callProcedure("@SnapshotDelete", // new String[] { dir }, // new String[] { nonce }); // keepTrying = false; // continue; // } // // System.err.println("Failed to take snapshot"); // return false; // } // // break; // } // // // Clients other than the one that initiated the snapshot // // have to check if the snapshot has completed // if (m_id > 0) { // int maxTry = 10; // // while (maxTry-- > 0) { // boolean found = false; // response = client.callProcedure("@SnapshotStatus").getResults(); // if (response.length != 2) { // System.err.println("Failed to get snapshot status"); // return false; // } // while (response[0].advanceRow()) { // if (response[0].getString("NONCE").equals(nonce)) { // found = true; // break; // } // } // // if (found) { // // This probably means the snapshot is done // if (response[0].getLong("END_TIME") > 0) // break; // } // // try { // Thread.sleep(500); // } catch (InterruptedException e) { // return false; // } // } // } // // // Get host ID to hostname mappings // response = client.callProcedure("@SystemInformation").getResults(); // if (response.length != 1) { // System.err.println("Failed to get host ID to IP address mapping"); // return false; // } // while (response[0].advanceRow()) { // if (!response[0].getString("key").equals("hostname")) // continue; // hostMappings.put((Integer) response[0].get("node_id", VoltType.INTEGER), // response[0].getString("value")); // } // // // Do a scan to get all the file names and table names // response = client.callProcedure("@SnapshotScan", dir).getResults(); // if (response.length != 3) { // System.err.println("Failed to get snapshot filenames"); // return false; // } // // // Only copy the snapshot files we just created // while (response[0].advanceRow()) { // if (!response[0].getString("NONCE").equals(nonce)) // continue; // // String[] tables = response[0].getString("TABLES_REQUIRED").split(","); // for (String t : tables) // snapshotMappings.put(t, null); // break; // } // // while (response[2].advanceRow()) { // int id = Integer.parseInt(response[2].getString("HOST_ID")); // String tableName = response[2].getString("TABLE"); // // if (!snapshotMappings.containsKey(tableName) || !hostMappings.containsKey(id)) // continue; // // snapshotMappings.put(tableName, Pair.of(hostMappings.get(id), // response[2].getString("NAME"))); // } // } catch (NoConnectionsException e) { // e.printStackTrace(); // return false; // } catch (ProcCallException e) { // e.printStackTrace(); // return false; // } catch (UnknownHostException e) { // e.printStackTrace(); // return false; // } catch (IOException e) { // e.printStackTrace(); // return false; // } // // // Iterate through all the tables // for (String tableName : m_tableCheckOrder) { // Pair<String, String> value = snapshotMappings.get(tableName); // if (value == null) // continue; // // String hostName = value.getFirst(); // File file = new File(dir, value.getSecond()); // FileInputStream inputStream = null; // TableSaveFile saveFile = null; // long rowCount = 0; // // Pair<String, Integer> key = Pair.of(tableName, 0); // if (!m_constraints.containsKey(key) || hostName == null) // continue; // // System.err.println("Checking table " + tableName); // // // Copy the file over // String localhostName = null; // try { // localhostName = InetAddress.getLocalHost().getHostName(); // } catch (UnknownHostException e1) { // localhostName = "localhost"; // } // if (!hostName.equals("localhost") && !hostName.equals(localhostName)) { // if (!SSHTools.copyFromRemote(file, m_username, hostName, file.getPath())) { // System.err.println("Failed to copy the snapshot file " + file.getPath() // + " from host " // + hostName); // return false; // } // } // // if (!file.exists()) { // System.err.println("Snapshot file " + file.getPath() // + " cannot be copied from " // + hostName // + " to localhost"); // return false; // } // // try { // try { // inputStream = new FileInputStream(file); // saveFile = new TableSaveFile(inputStream.getChannel(), 3, null); // // // Get chunks from table // while (isSatisfied && saveFile.hasMoreChunks()) { // final BBContainer chunk = saveFile.getNextChunk(); // VoltTable table = null; // // // This probably should not happen // if (chunk == null) // continue; // // table = PrivateVoltTableFactory.createVoltTableFromBuffer(chunk.b, true); // // Now, check each row // while (isSatisfied && table.advanceRow()) { // isSatisfied = Verification.checkRow(m_constraints.get(key), // table); // rowCount++; // } // // Release the memory of the chunk we just examined, be good // chunk.discard(); // } // } finally { // if (saveFile != null) { // saveFile.close(); // } // if (inputStream != null) // inputStream.close(); // if (!hostName.equals("localhost") && !hostName.equals(localhostName) // && !file.delete()) // System.err.println("Failed to delete snapshot file " + file.getPath()); // } // } catch (FileNotFoundException e) { // e.printStackTrace(); // return false; // } catch (IOException e) { // e.printStackTrace(); // return false; // } // // if (isSatisfied) { // System.err.println("Table " + tableName // + " with " // + rowCount // + " rows passed check"); // } else { // System.err.println("Table " + tableName + " failed check"); // break; // } // } // // // Clean up the snapshot we made // try { // if (m_id == 0) { // client.callProcedure("@SnapshotDelete", // new String[] { dir }, // new String[] { nonce }).getResults(); // } // } catch (IOException e) { // e.printStackTrace(); // } catch (ProcCallException e) { // e.printStackTrace(); // } // // System.err.println("Table checking finished " // + (isSatisfied ? "successfully" : "with failures")); // // return isSatisfied; } }
diff --git a/src/ru/spbau/bioinf/tagfinder/TexTableGenerator.java b/src/ru/spbau/bioinf/tagfinder/TexTableGenerator.java index 69ed1dd..2820c64 100644 --- a/src/ru/spbau/bioinf/tagfinder/TexTableGenerator.java +++ b/src/ru/spbau/bioinf/tagfinder/TexTableGenerator.java @@ -1,253 +1,253 @@ package ru.spbau.bioinf.tagfinder; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import ru.spbau.bioinf.tagfinder.util.ReaderUtil; public class TexTableGenerator { public static int tableId = 0; public static void main(String[] args) throws Exception { tableOneTwo(); tablesNineTen(); tableThirteen(); } public static void tableOneTwo() throws Exception { createTexTable("bar_exp_annotated_correct_none", "bar_virt_annotated_correct_zero", "Average percentage of correct $\\ell$-tags (basic spectrum graphs)", "correct $\\ell$-tags"); createTexTable("bar_exp_annotated_proper_none", "bar_virt_annotated_proper_zero", "Average percentage of proper $\\ell$-tags (basic spectrum graphs)", "proper $\\ell$-tags"); } public static void tablesNineTen() throws Exception { createTexTable("bar_exp_annotated_correct_none_add", "Average percentage of correct $\\ell$-tags (error-correcting spectrum graphs)", "correct $\\ell$-tags"); createTexTable("bar_exp_annotated_correct_more", "Average percentage of correct $\\ell$-tags (combined spectrum graphs)", "correct $\\ell$-tags"); } public static void tableThirteen() throws Exception { createTexTable("bar_virt_annotated_correct_none", "Average percentage of correct mono-$\\ell$-tags w.r.t. all mono-$\\ell$-tags", "correct mono-$\\ell$-tags"); } private static void createTexTable(String fileFirst, String fileSecond, String caption, String header) throws Exception { System.out.println("% 6-rows table for " + fileFirst + " and " + fileSecond); double[][] data = new double[6][]; for (int gap = 1; gap <= 3; gap++) { data[gap - 1] = ReaderUtil.getLastString(new File("res", "share_" + fileFirst + "_" + gap + ".txt")); data[gap + 2] = ReaderUtil.getLastString(new File("res", "share_" + fileSecond + "_" + gap + ".txt")); } createSixRowsTable(data, caption, header, 0); } public static void createSixRowsTable(double[][] data, String caption, String header, int columnHeaderDelta) throws Exception { int maxLen = 0; for (int i = 0; i < data.length; i++) { maxLen = Math.max(maxLen, data[i].length); } prepareEps(data, header + " (%)", 6, columnHeaderDelta); int width = 20; if (maxLen > width) { width = (maxLen + 1) / 2; } System.out.print("\\begin{landscape}\n"); for (int start = 1; start <= maxLen; start += width) { int end = Math.min(start + width - 1, maxLen); System.out.print("\\begin{table}[h]\\tiny\n" + "\\vspace{3mm}\n" + "{\\centering\n" + "\\begin{center}\n" + "\\begin{tabular}{|c|l|"); for (int i = start; i <= end; i++) { System.out.print("c|"); } System.out.print("}\n" + " \\hline\n" + - " \\multicolumn{2}{|c|}{ } & \\multicolumn{ " + (end - start + 1 + columnHeaderDelta) + " }{|c|}{ " + header + " (\\%)} \\\\\n" + + " \\multicolumn{2}{|c|}{ } & \\multicolumn{ " + (end - start + 1) + " }{|c|}{ " + header + " (\\%)} \\\\\n" + " \\cline{3- " + (end - start + 3) + "}\n" + " \\multicolumn{2}{|c|}{ } "); //"& 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 & 20 & 21 & 22 & 23 & 24 for (int i = start; i <= end; i++) { - System.out.print(" & " + i); + System.out.print(" & " + (i + columnHeaderDelta)); } System.out.print("\\\\\n" + " \\hline\n" + " \\multirow{3}{*}{exp}\n"); for (int row = 0; row < 3; row++) { printRows(data, row, start, end, true); } System.out.print(" \\hline\n \\multirow{3}{*}{virt} \n"); for (int row = 3; row < 6; row++) { printRows(data, row, start, end, true); } System.out.print(" \\hline\n" + "\\end{tabular}\n" + "\\end{center}\n" + "\\par}\n" + "\\centering\n"); if (end == maxLen) { System.out.print("\\caption{ " + caption + ".}\n" + "\\label{table:table" + tableId + "}\n"); } System.out.print("\\vspace{3mm}\n" + "\\end{table}\n\n"); } System.out.print("\\end{landscape}"); System.out.println(); System.out.println("\n\\begin{figure}\n" + " \\begin{center}"); System.out.println("\\includegraphics{plots/" + tableId + ".eps}\n"); System.out.println("\\end{center}\n" + "\\caption{" + caption + "}\n" + " \\label{fig:LABEL}\n" + "\\end{figure}\n"); } private static void prepareEps(double[][] data, String header, int rows, int columnHeaderDelta) throws IOException { tableId++; PrintWriter dataFile = ReaderUtil.createOutputFile(new File("plots", tableId + ".dat")); for (int i = 0; i < 14; i++) { dataFile.print((i + 1 + columnHeaderDelta) + " "); for (int col = 0; col < rows; col++) { dataFile.print(data[col][i] + " "); } dataFile.println(); } dataFile.close(); PrintWriter gplFile = ReaderUtil.createOutputFile(new File("plots", tableId + ".gpl")); gplFile.print("set terminal postscript eps color \n" + "set out \"plots/" + tableId + ".eps\"\n" + "set ylabel \"" + header.replaceAll("\\$\\\\ell\\$", "l") + "\"\n" + "set xlabel \"Tag length\"\n" + "plot"); for (int i = 1; i <= rows; i++) { int gap = i; if (gap > 3) { gap = gap - 3; } String titlePrefix = ""; if (rows > 3) { titlePrefix = i > 3 ? "virt" : " exp"; } gplFile.print("\"plots/" + tableId + ".dat\" using 1:" + (i + 1) + " title '" + titlePrefix + " " + gap + "-aa' with linespoints"); if (i < rows) { gplFile.println(", \\"); } } gplFile.close(); } private static void createTexTable(String fileFirst, String caption, String header) throws Exception { System.out.println("% 3-rows table for " + fileFirst); double[][] data = new double[3][]; for (int gap = 1; gap <= 3; gap++) { data[gap - 1] = ReaderUtil.getLastString(new File("res", "share_" + fileFirst + "_" + gap + ".txt")); } createThreeRowsTable(data, caption, header); } public static void createThreeRowsTable(double[][] data, String caption, String header) throws Exception { int maxLen = 0; for (int i = 0; i < data.length; i++) { maxLen = Math.max(maxLen, data[i].length); } prepareEps(data, header + " (%)", 3, 0); int width = 20; if (maxLen > width) { width = (maxLen + 1) / 2; if (width > 20) { width = (maxLen + 1) / 3; if (width < 18) { width = 18; } } } System.out.println("\\begin{landscape}\n"); for (int start = 1; start <= maxLen; start += width) { int end = Math.min(start + width - 1, maxLen); System.out.print("\\begin{table}[h]\\tiny\n" + "\\vspace{3mm}\n" + "{\\centering\n" + "\\begin{center}\n" + "\\begin{tabular}{|l|c|"); for (int i = start; i <= end; i++) { System.out.print("c|"); } System.out.print("}\n" + " \\hline\n" + " & \\multicolumn{ " + (end - start + 1) + " }{|c|}{" + header + "(\\%)} \\\\\n" + " \\cline{2- " + (end - start + 2) + "}\n" + " "); //"& 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 & 20 & 21 & 22 & 23 & 24 for (int i = start; i <= end; i++) { System.out.print(" & " + i); } System.out.print("\\\\\n" + " \\hline\n"); for (int row = 0; row < 3; row++) { printRows(data, row, start, end, false); } System.out.println(" \\hline\n" + "\\end{tabular}\n" + "\\end{center}\n" + "\\par}\n" + "\\centering\n"); if (end == maxLen) { System.out.println("\\caption{ " + caption + ".}\n" + "\\label{table:table" + tableId + "}\n"); } System.out.println("\\vspace{3mm}\n" + "\\end{table}"); } System.out.println("\\end{landscape}"); System.out.println("\n\\begin{figure}\n" + " \\begin{center}"); System.out.println("\\includegraphics{plots/" + tableId + ".eps}\n"); System.out.println("\\end{center}\n" + "\\caption{" + caption + "}\n" + " \\label{fig:LABEL}\n" + "\\end{figure}\n"); } private static void printRows(double[][] data, int row, int start, int end, boolean needAmp) { if (needAmp) { System.out.print("& "); } System.out.print((row % 3 + 1) + "-aa "); for (int i = start; i <= end; i++) { System.out.print(" & "); if (data[row].length >= i) { System.out.print(ValidTags.df.format(data[row][i - 1])); } } System.out.println("\\\\"); } }
false
true
public static void createSixRowsTable(double[][] data, String caption, String header, int columnHeaderDelta) throws Exception { int maxLen = 0; for (int i = 0; i < data.length; i++) { maxLen = Math.max(maxLen, data[i].length); } prepareEps(data, header + " (%)", 6, columnHeaderDelta); int width = 20; if (maxLen > width) { width = (maxLen + 1) / 2; } System.out.print("\\begin{landscape}\n"); for (int start = 1; start <= maxLen; start += width) { int end = Math.min(start + width - 1, maxLen); System.out.print("\\begin{table}[h]\\tiny\n" + "\\vspace{3mm}\n" + "{\\centering\n" + "\\begin{center}\n" + "\\begin{tabular}{|c|l|"); for (int i = start; i <= end; i++) { System.out.print("c|"); } System.out.print("}\n" + " \\hline\n" + " \\multicolumn{2}{|c|}{ } & \\multicolumn{ " + (end - start + 1 + columnHeaderDelta) + " }{|c|}{ " + header + " (\\%)} \\\\\n" + " \\cline{3- " + (end - start + 3) + "}\n" + " \\multicolumn{2}{|c|}{ } "); //"& 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 & 20 & 21 & 22 & 23 & 24 for (int i = start; i <= end; i++) { System.out.print(" & " + i); } System.out.print("\\\\\n" + " \\hline\n" + " \\multirow{3}{*}{exp}\n"); for (int row = 0; row < 3; row++) { printRows(data, row, start, end, true); } System.out.print(" \\hline\n \\multirow{3}{*}{virt} \n"); for (int row = 3; row < 6; row++) { printRows(data, row, start, end, true); } System.out.print(" \\hline\n" + "\\end{tabular}\n" + "\\end{center}\n" + "\\par}\n" + "\\centering\n"); if (end == maxLen) { System.out.print("\\caption{ " + caption + ".}\n" + "\\label{table:table" + tableId + "}\n"); } System.out.print("\\vspace{3mm}\n" + "\\end{table}\n\n"); } System.out.print("\\end{landscape}"); System.out.println(); System.out.println("\n\\begin{figure}\n" + " \\begin{center}"); System.out.println("\\includegraphics{plots/" + tableId + ".eps}\n"); System.out.println("\\end{center}\n" + "\\caption{" + caption + "}\n" + " \\label{fig:LABEL}\n" + "\\end{figure}\n"); }
public static void createSixRowsTable(double[][] data, String caption, String header, int columnHeaderDelta) throws Exception { int maxLen = 0; for (int i = 0; i < data.length; i++) { maxLen = Math.max(maxLen, data[i].length); } prepareEps(data, header + " (%)", 6, columnHeaderDelta); int width = 20; if (maxLen > width) { width = (maxLen + 1) / 2; } System.out.print("\\begin{landscape}\n"); for (int start = 1; start <= maxLen; start += width) { int end = Math.min(start + width - 1, maxLen); System.out.print("\\begin{table}[h]\\tiny\n" + "\\vspace{3mm}\n" + "{\\centering\n" + "\\begin{center}\n" + "\\begin{tabular}{|c|l|"); for (int i = start; i <= end; i++) { System.out.print("c|"); } System.out.print("}\n" + " \\hline\n" + " \\multicolumn{2}{|c|}{ } & \\multicolumn{ " + (end - start + 1) + " }{|c|}{ " + header + " (\\%)} \\\\\n" + " \\cline{3- " + (end - start + 3) + "}\n" + " \\multicolumn{2}{|c|}{ } "); //"& 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 & 12 & 13 & 14 & 15 & 16 & 17 & 18 & 19 & 20 & 21 & 22 & 23 & 24 for (int i = start; i <= end; i++) { System.out.print(" & " + (i + columnHeaderDelta)); } System.out.print("\\\\\n" + " \\hline\n" + " \\multirow{3}{*}{exp}\n"); for (int row = 0; row < 3; row++) { printRows(data, row, start, end, true); } System.out.print(" \\hline\n \\multirow{3}{*}{virt} \n"); for (int row = 3; row < 6; row++) { printRows(data, row, start, end, true); } System.out.print(" \\hline\n" + "\\end{tabular}\n" + "\\end{center}\n" + "\\par}\n" + "\\centering\n"); if (end == maxLen) { System.out.print("\\caption{ " + caption + ".}\n" + "\\label{table:table" + tableId + "}\n"); } System.out.print("\\vspace{3mm}\n" + "\\end{table}\n\n"); } System.out.print("\\end{landscape}"); System.out.println(); System.out.println("\n\\begin{figure}\n" + " \\begin{center}"); System.out.println("\\includegraphics{plots/" + tableId + ".eps}\n"); System.out.println("\\end{center}\n" + "\\caption{" + caption + "}\n" + " \\label{fig:LABEL}\n" + "\\end{figure}\n"); }
diff --git a/src/jp/gr/java_conf/neko_daisuki/httpsync/MainActivity.java b/src/jp/gr/java_conf/neko_daisuki/httpsync/MainActivity.java index 4f4201c..941ef83 100644 --- a/src/jp/gr/java_conf/neko_daisuki/httpsync/MainActivity.java +++ b/src/jp/gr/java_conf/neko_daisuki/httpsync/MainActivity.java @@ -1,574 +1,574 @@ package jp.gr.java_conf.neko_daisuki.httpsync; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.os.AsyncTask; import android.os.Bundle; import android.provider.BaseColumns; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends Activity { private class DeleteDialogOnClickListener implements DialogInterface.OnClickListener { private int mPosition; public DeleteDialogOnClickListener(int position) { mPosition = position; } public void onClick(DialogInterface _, int __) { deleteJob(mJobs[mPosition]); } } private abstract class ListButtonOnClickListener implements View.OnClickListener { protected int mPosition; public ListButtonOnClickListener(int position) { mPosition = position; } public abstract void onClick(View _); } private class DeleteButtonOnClickListener extends ListButtonOnClickListener { public DeleteButtonOnClickListener(int position) { super(position); } public void onClick(View _) { showConfirmDialogToDelete(mPosition); } } private class EditButtonOnClickListener extends ListButtonOnClickListener { public EditButtonOnClickListener(int position) { super(position); } public void onClick(View _) { startEditActivity(mJobs[mPosition], REQUEST_EDIT); } } private class JobAdapter extends ArrayAdapter<Job> { private class Holder { public TextView url; public TextView directory; public Button editButton; public Button deleteButton; } private LayoutInflater mInflater; public JobAdapter(Context context, Job[] objects) { super(context, 0, objects); String name = Context.LAYOUT_INFLATER_SERVICE; mInflater = (LayoutInflater)context.getSystemService(name); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { return getView(position, makeView(parent), parent); } Holder holder = (Holder)convertView.getTag(); Job job = getItem(position); holder.url.setText(job.url); holder.directory.setText(job.directory); holder.editButton.setOnClickListener(new EditButtonOnClickListener(position)); holder.deleteButton.setOnClickListener(new DeleteButtonOnClickListener(position)); return convertView; } private TextView findTextView(View view, int id) { return (TextView)view.findViewById(id); } private Button findButton(View view, int id) { return (Button)view.findViewById(id); } private View makeView(ViewGroup parent) { int layout = R.layout.list_row; View convertView = mInflater.inflate(layout, parent, false); Holder holder = new Holder(); holder.url = findTextView(convertView, R.id.url_text); holder.directory = findTextView(convertView, R.id.directory_text); holder.editButton = findButton(convertView, R.id.edit_button); holder.deleteButton = findButton(convertView, R.id.delete_button); convertView.setTag(holder); return convertView; } } private abstract class RequestProcedure { public abstract void run(Job job); } private class EditRequestProcedure extends RequestProcedure { public void run(Job job) { updateJob(job); } } private class AddRequestProcedure extends RequestProcedure { public void run(Job job) { addJob(job); } } private static class DatabaseHelper extends SQLiteOpenHelper { public interface Columns extends BaseColumns { public static final String URL = "url"; public static final String DIRECTORY = "directory"; public static final String OVERWRITE = "overwrite"; } public static final String TABLE_NAME = "jobs"; private static final String DATABASE_NAME = "jobs.db"; private static final int DATABASE_VERSION = 1; public DatabaseHelper(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String fmt = "create table %s (%s integer primary key autoincrement" + ", %s text not null, %s text not null, %s integer not null);"; String sql = String.format( fmt, TABLE_NAME, Columns._ID, Columns.URL, Columns.DIRECTORY, Columns.OVERWRITE); db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(String.format("drop table if exists %s", TABLE_NAME)); onCreate(db); } } private static class MalformedHtmlException extends Exception { } private class SynchronizeTask extends AsyncTask<Job[], Void, Void> { public Void doInBackground(Job[]... jobs) { Log.i(LOG_TAG, "Synchronizing started."); run(jobs[0]); Log.i(LOG_TAG, "Synchronizing ended."); return null; } private HttpURLConnection connect(String url) { URL loc; try { loc = new URL(url); } catch (MalformedURLException e) { String fmt = "Malformed URL: %s: %s"; Log.e(LOG_TAG, String.format(fmt, url, e.getMessage())); return null; } HttpURLConnection conn; try { conn = (HttpURLConnection)loc.openConnection(); conn.connect(); } catch (IOException e) { String fmt = "Cannot connect to %s: %s"; Log.e(LOG_TAG, String.format(fmt, url, e.getMessage())); return null; } return conn; } private String readHtml(String url) { HttpURLConnection conn = connect(url); if (conn == null) { return null; } InputStream in; try { in = conn.getInputStream(); } catch (IOException e) { String fmt = "HttpURLConnection.getInputStream() failed: %s"; - Log.e(LOG_TAG, fmt.format(e.getMessage())); + Log.e(LOG_TAG, String.format(fmt, e.getMessage())); return null; } InputStreamReader reader; String encoding = "UTF-8"; try { reader = new InputStreamReader(in, encoding); } catch (UnsupportedEncodingException e) { String fmt = "Cannot handle encoding %s: %s"; Log.e(LOG_TAG, String.format(fmt, encoding, e.getMessage())); return null; } String html = ""; BufferedReader bufferedReader = new BufferedReader(reader); try { try { String line; while ((line = bufferedReader.readLine()) != null) { html += line; } } finally { bufferedReader.close(); } } catch (IOException e) { String fmt = "Cannot read html: %s"; Log.e(LOG_TAG, String.format(fmt, e.getMessage())); return null; } return html; } private List<String> extractLinks(String html) throws MalformedHtmlException { List<String> list = new ArrayList<String>(); int end = 0; int begin; String startMark = "href=\""; while ((begin = html.indexOf(startMark, end)) != -1) { int pos = begin + startMark.length(); end = html.indexOf("\"", pos); if (end == -1) { throw new MalformedHtmlException(); } list.add(html.substring(pos, end)); end += 1; } return list; } private List<String> listOfLink(String link) { String[] extensions = new String[] { ".mp3", ".mp4", ".apk", ".tar", ".xz", ".bz2", ".gzip", ".zip" }; boolean isTarget = false; for (int i = 0; (i < extensions.length) && !isTarget; i++) { isTarget = link.endsWith(extensions[i]); } return isTarget ? Arrays.asList(link) : new ArrayList<String>(); } private String[] selectFiles(List<String> links) { List<String> list = new ArrayList<String>(); for (String link: links) { list.addAll(listOfLink(link)); } return list.toArray(new String[0]); } private void download(String base, String link, String dir) { String url = String.format("%s/%s", base, link); HttpURLConnection conn = connect(url); if (conn == null) { return; } String name = new File(link).getName(); String path = String.format("%s%s%s", dir, File.separator, name); if (new File(path).exists()) { String fmt = "Skip: source=%s, destination=%s"; Log.i(LOG_TAG, String.format(fmt, url, path)); return; } String fmt = "Downloading: source=%s, destination=%s"; Log.i(LOG_TAG, String.format(fmt, url, path)); try { InputStream in = conn.getInputStream(); try { FileOutputStream out = new FileOutputStream(path); try { byte[] buffer = new byte[4096]; int nBytes; while ((nBytes = in.read(buffer)) != -1) { out.write(buffer, 0, nBytes); } } finally { out.close(); } } finally { in.close(); } } catch (IOException e) { fmt = "Cannot copy. Destination file %s is removed: %s"; Log.e(LOG_TAG, String.format(fmt, path, e.getMessage())); new File(path).delete(); } fmt = "Downloaded: source=%s, destination=%s"; Log.i(LOG_TAG, String.format(fmt, url, path)); } private void synchronize(Job job) { // TODO: Must show the error to a user. String url = job.url; String html = readHtml(url); if (html == null) { return; } String[] links; try { links = selectFiles(extractLinks(html)); } catch (MalformedHtmlException _) { Log.e(LOG_TAG, "Html is malformed. Skip."); return; } for (String link: links) { download(url, link, job.directory); } } private void run(Job[] jobs) { for (Job job: jobs) { synchronize(job); } } } private class AddButtonOnClickListener implements View.OnClickListener { public void onClick(View _) { startEditActivity(new Job(), REQUEST_ADD); } } private class RunButtonOnClickListener implements View.OnClickListener { public void onClick(View _) { new SynchronizeTask().execute(mJobs); } } private static final String LOG_TAG = "httpsync"; private static final int REQUEST_ADD = 1; private static final int REQUEST_EDIT = 2; private Job[] mJobs; private ListView mJobList; private SparseArray<RequestProcedure> mRequestProcedures; private DatabaseHelper mDatabase; @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } Job job = (Job)data.getSerializableExtra(EditActivity.EXTRA_KEY_JOB); mRequestProcedures.get(requestCode).run(job); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mJobList = (ListView)findViewById(R.id.job_list); Button addButton = (Button)findViewById(R.id.add_button); addButton.setOnClickListener(new AddButtonOnClickListener()); Button runButton = (Button)findViewById(R.id.run_button); runButton.setOnClickListener(new RunButtonOnClickListener()); mRequestProcedures = new SparseArray<RequestProcedure>(); mRequestProcedures.put(REQUEST_ADD, new AddRequestProcedure()); mRequestProcedures.put(REQUEST_EDIT, new EditRequestProcedure()); mDatabase = new DatabaseHelper(this); updateJobs(); } private void updateList() { ListAdapter adapter = new JobAdapter(this, mJobs); mJobList.setAdapter(adapter); } private void updateJobs() { mJobs = queryJobs(); updateList(); } private Job[] queryJobs() { List<Job> jobs = new ArrayList<Job>(); try { SQLiteDatabase db = mDatabase.getReadableDatabase(); String[] columns = new String[] { DatabaseHelper.Columns._ID, DatabaseHelper.Columns.URL, DatabaseHelper.Columns.DIRECTORY, DatabaseHelper.Columns.OVERWRITE }; Cursor cursor = db.query( DatabaseHelper.TABLE_NAME, columns, null, // selection null, // selection args null, // group by null, // having null); // order by try { while (cursor.moveToNext()) { Job job = new Job(); job.id = cursor.getLong(0); job.url = cursor.getString(1); job.directory = cursor.getString(2); job.overwrite = cursor.getLong(3) == 1; Log.i(LOG_TAG, job.toString()); jobs.add(job); } } finally { cursor.close(); } } finally { mDatabase.close(); } return jobs.toArray(new Job[0]); } private void startEditActivity(Job job, int requestCode) { Intent i = new Intent(this, EditActivity.class); i.putExtra(EditActivity.EXTRA_KEY_JOB, job); startActivityForResult(i, requestCode); } private ContentValues makeContentValuesOfJob(Job job) { ContentValues values = new ContentValues(); values.put(DatabaseHelper.Columns.URL, job.url); values.put(DatabaseHelper.Columns.DIRECTORY, job.directory); values.put(DatabaseHelper.Columns.OVERWRITE, job.overwrite); return values; } private void addJob(Job job) { SQLiteDatabase db = mDatabase.getWritableDatabase(); ContentValues values = makeContentValuesOfJob(job); db.insertOrThrow(DatabaseHelper.TABLE_NAME, null, values); updateJobs(); } private void updateJob(Job job) { SQLiteDatabase db = mDatabase.getWritableDatabase(); ContentValues values = makeContentValuesOfJob(job); String where = String.format("%s=?", DatabaseHelper.Columns._ID); String[] args = new String[] { Long.toString(job.id) }; db.update(DatabaseHelper.TABLE_NAME, values, where, args); updateJobs(); } private void deleteJob(Job job) { SQLiteDatabase db = mDatabase.getWritableDatabase(); String where = String.format("%s=?", DatabaseHelper.Columns._ID); String[] args = new String[] { Long.toString(job.id) }; db.delete(DatabaseHelper.TABLE_NAME, where, args); updateJobs(); } private void showConfirmDialogToDelete(int position) { Job job = mJobs[position]; String url = job.url; String directory = job.directory; Resources res = getResources(); String fmt = res.getString(R.string.delete_confirm_format); String positive = res.getString(R.string.positive); String negative = res.getString(R.string.negative); String msg = String.format(fmt, url, directory, positive, negative); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.delete_dialog_title); builder.setMessage(msg); builder.setPositiveButton(R.string.positive, new DeleteDialogOnClickListener(position)); builder.setNegativeButton(R.string.negative, null); builder.create().show(); } } /** * vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4 */
true
true
private String readHtml(String url) { HttpURLConnection conn = connect(url); if (conn == null) { return null; } InputStream in; try { in = conn.getInputStream(); } catch (IOException e) { String fmt = "HttpURLConnection.getInputStream() failed: %s"; Log.e(LOG_TAG, fmt.format(e.getMessage())); return null; } InputStreamReader reader; String encoding = "UTF-8"; try { reader = new InputStreamReader(in, encoding); } catch (UnsupportedEncodingException e) { String fmt = "Cannot handle encoding %s: %s"; Log.e(LOG_TAG, String.format(fmt, encoding, e.getMessage())); return null; } String html = ""; BufferedReader bufferedReader = new BufferedReader(reader); try { try { String line; while ((line = bufferedReader.readLine()) != null) { html += line; } } finally { bufferedReader.close(); } } catch (IOException e) { String fmt = "Cannot read html: %s"; Log.e(LOG_TAG, String.format(fmt, e.getMessage())); return null; } return html; }
private String readHtml(String url) { HttpURLConnection conn = connect(url); if (conn == null) { return null; } InputStream in; try { in = conn.getInputStream(); } catch (IOException e) { String fmt = "HttpURLConnection.getInputStream() failed: %s"; Log.e(LOG_TAG, String.format(fmt, e.getMessage())); return null; } InputStreamReader reader; String encoding = "UTF-8"; try { reader = new InputStreamReader(in, encoding); } catch (UnsupportedEncodingException e) { String fmt = "Cannot handle encoding %s: %s"; Log.e(LOG_TAG, String.format(fmt, encoding, e.getMessage())); return null; } String html = ""; BufferedReader bufferedReader = new BufferedReader(reader); try { try { String line; while ((line = bufferedReader.readLine()) != null) { html += line; } } finally { bufferedReader.close(); } } catch (IOException e) { String fmt = "Cannot read html: %s"; Log.e(LOG_TAG, String.format(fmt, e.getMessage())); return null; } return html; }
diff --git a/tools/etfw/org.eclipse.ptp.etfw.launch/src/org/eclipse/ptp/etfw/launch/ETFWParentLaunchConfigurationTab.java b/tools/etfw/org.eclipse.ptp.etfw.launch/src/org/eclipse/ptp/etfw/launch/ETFWParentLaunchConfigurationTab.java index 63c42d6c2..9f47fcfc3 100644 --- a/tools/etfw/org.eclipse.ptp.etfw.launch/src/org/eclipse/ptp/etfw/launch/ETFWParentLaunchConfigurationTab.java +++ b/tools/etfw/org.eclipse.ptp.etfw.launch/src/org/eclipse/ptp/etfw/launch/ETFWParentLaunchConfigurationTab.java @@ -1,186 +1,190 @@ /******************************************************************************* * Copyright (c) 2012 University of Illinois 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: * Chris Navarro (Illinois/NCSA) - Design and implementation *******************************************************************************/ package org.eclipse.ptp.etfw.launch; import java.util.Iterator; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.eclipse.ptp.etfw.launch.ui.util.ETFWToolTabBuilder; import org.eclipse.ptp.internal.rm.jaxb.control.ui.launch.IJAXBLaunchConfigurationTab; import org.eclipse.ptp.launch.ui.extensions.JAXBControllerLaunchConfigurationTab; import org.eclipse.ptp.launch.ui.extensions.RMLaunchValidation; import org.eclipse.ptp.rm.jaxb.control.core.ILaunchController; import org.eclipse.ptp.rm.jaxb.control.ui.IUpdateModel; import org.eclipse.ptp.rm.jaxb.core.IVariableMap; import org.eclipse.ptp.rm.jaxb.core.data.AttributeType; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.TabFolder; import org.eclipse.swt.widgets.TabItem; /** * Extends JAXBControllerLaunchConfigurationTab with specific changes for ETFw. The LC Map needs to be initialized from the * workflow's variable map, not the resource managers. * * @author Chris Navarro * */ public class ETFWParentLaunchConfigurationTab extends JAXBControllerLaunchConfigurationTab { private final IVariableMap variableMap; private List<IJAXBLaunchConfigurationTab> tabControllers; public ETFWParentLaunchConfigurationTab(ILaunchController control, IProgressMonitor monitor, IVariableMap variableMap) throws Throwable { super(control, monitor); this.variableMap = variableMap; } @Override public void createControl(Composite parent, String id) throws CoreException { control = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); control.setLayout(layout); tabFolder = new TabFolder(control, SWT.NONE); tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); ETFWToolTabBuilder.initialize(); for (IJAXBLaunchConfigurationTab tabControl : tabControllers) { ETFWToolTabBuilder builder = new ETFWToolTabBuilder(tabControl, this.variableMap); TabItem tabItem = new TabItem(tabFolder, SWT.NONE); Control control = null; final ScrolledComposite scroller = new ScrolledComposite(tabFolder, SWT.V_SCROLL | SWT.H_SCROLL); try { control = builder.build(scroller); ((Composite) control).layout(); tabItem.setText(tabControl.getController().getTitle()); String tooltip = tabControl.getController().getTooltip(); if (tooltip != null) { tabItem.setToolTipText(tooltip); scroller.setToolTipText(tooltip); } scroller.setContent(control); scroller.setExpandHorizontal(true); scroller.setExpandVertical(true); scroller.setMinSize(control.computeSize(SWT.DEFAULT, SWT.DEFAULT)); tabItem.setControl(scroller); } catch (Throwable t) { t.printStackTrace(); } } this.controlId = id; control.layout(true, true); } @Override public RMLaunchValidation initializeFrom(ILaunchConfiguration configuration) { try { // This lets us differentiate keys from the old ETFW so they can work from one Profiling Tab getVariableMap().initialize(variableMap, getJobControl().getControlId()); getUpdateHandler().clear(); getVariableMap().updateFromConfiguration(configuration); } catch (Throwable t) { t.printStackTrace(); } return null; } public void addDynamicContent(List<IJAXBLaunchConfigurationTab> tabs) { this.tabControllers = tabs; } @Override public RMLaunchValidation performApply(ILaunchConfigurationWorkingCopy configuration) { RMLaunchValidation validation = super.performApply(configuration); // TODO the above performApply should update the attribute map, but it doesn't right now so it is handled below Iterator<String> iterator = getVariableMap().getAttributes().keySet().iterator(); while (iterator.hasNext()) { String attribute = iterator.next(); String name = attribute; if (name.startsWith(controlId)) { name = name.substring(controlId.length() + 1, attribute.length()); // Check to see if the variable is part of ETFw AttributeType temp = variableMap.getAttributes().get(name); if (temp != null) { if (isWidgetEnabled(temp.getName()) && temp.isVisible()) { String attType = temp.getType(); // If boolean is translated to a string, insert the string into the launch configuration String translateBoolean = variableMap.getAttributes().get(name).getTranslateBooleanAs(); Object value = getVariableMap().getValue(name); if (attType.equals("boolean")) { //$NON-NLS-1$ if (translateBoolean != null) { configuration.setAttribute(attribute, value.toString()); } else { boolean val = new Boolean(value.toString()); configuration.setAttribute(attribute, val); } } else if (attType.equals("string")) { //$NON-NLS-1$ configuration.setAttribute(attribute, value.toString()); } else if (attType.equals("integer")) { //$NON-NLS-1$ - int val = new Integer(value.toString()); - configuration.setAttribute(attribute, val); + if (value.toString().length() > 0) { + int val = new Integer(value.toString()); + configuration.setAttribute(attribute, val); + } else { + configuration.setAttribute(attribute, value.toString()); + } } else { configuration.setAttribute(attribute, value.toString()); } } } } } return validation; } /** * Determines if the UI widget is enabled and should be included in the launch configuration. It prevents attributes that are * not enabled from getting included in the launch configuration * * @param attributeName * Name of the attribute associated with the widget * @return enabled state of widget */ public boolean isWidgetEnabled(String attributeName) { for (IJAXBLaunchConfigurationTab tabControl : tabControllers) { for (IUpdateModel m : tabControl.getLocalWidgets().values()) { if (m.getName() != null) { if (m.getName().equals(attributeName)) { return ((Control) m.getControl()).isEnabled(); } } else { // Do nothing, the model has no attribute associated with it } } } // Handles the case where attributes are not associated with UI models return true; } @Override public void relink() { // Some of the jaxb classes need to be re-worked for this to be implemented because their are target configuration specifics // in this call hierarchy } }
true
true
public RMLaunchValidation performApply(ILaunchConfigurationWorkingCopy configuration) { RMLaunchValidation validation = super.performApply(configuration); // TODO the above performApply should update the attribute map, but it doesn't right now so it is handled below Iterator<String> iterator = getVariableMap().getAttributes().keySet().iterator(); while (iterator.hasNext()) { String attribute = iterator.next(); String name = attribute; if (name.startsWith(controlId)) { name = name.substring(controlId.length() + 1, attribute.length()); // Check to see if the variable is part of ETFw AttributeType temp = variableMap.getAttributes().get(name); if (temp != null) { if (isWidgetEnabled(temp.getName()) && temp.isVisible()) { String attType = temp.getType(); // If boolean is translated to a string, insert the string into the launch configuration String translateBoolean = variableMap.getAttributes().get(name).getTranslateBooleanAs(); Object value = getVariableMap().getValue(name); if (attType.equals("boolean")) { //$NON-NLS-1$ if (translateBoolean != null) { configuration.setAttribute(attribute, value.toString()); } else { boolean val = new Boolean(value.toString()); configuration.setAttribute(attribute, val); } } else if (attType.equals("string")) { //$NON-NLS-1$ configuration.setAttribute(attribute, value.toString()); } else if (attType.equals("integer")) { //$NON-NLS-1$ int val = new Integer(value.toString()); configuration.setAttribute(attribute, val); } else { configuration.setAttribute(attribute, value.toString()); } } } } } return validation; }
public RMLaunchValidation performApply(ILaunchConfigurationWorkingCopy configuration) { RMLaunchValidation validation = super.performApply(configuration); // TODO the above performApply should update the attribute map, but it doesn't right now so it is handled below Iterator<String> iterator = getVariableMap().getAttributes().keySet().iterator(); while (iterator.hasNext()) { String attribute = iterator.next(); String name = attribute; if (name.startsWith(controlId)) { name = name.substring(controlId.length() + 1, attribute.length()); // Check to see if the variable is part of ETFw AttributeType temp = variableMap.getAttributes().get(name); if (temp != null) { if (isWidgetEnabled(temp.getName()) && temp.isVisible()) { String attType = temp.getType(); // If boolean is translated to a string, insert the string into the launch configuration String translateBoolean = variableMap.getAttributes().get(name).getTranslateBooleanAs(); Object value = getVariableMap().getValue(name); if (attType.equals("boolean")) { //$NON-NLS-1$ if (translateBoolean != null) { configuration.setAttribute(attribute, value.toString()); } else { boolean val = new Boolean(value.toString()); configuration.setAttribute(attribute, val); } } else if (attType.equals("string")) { //$NON-NLS-1$ configuration.setAttribute(attribute, value.toString()); } else if (attType.equals("integer")) { //$NON-NLS-1$ if (value.toString().length() > 0) { int val = new Integer(value.toString()); configuration.setAttribute(attribute, val); } else { configuration.setAttribute(attribute, value.toString()); } } else { configuration.setAttribute(attribute, value.toString()); } } } } } return validation; }
diff --git a/src/org/supercsv/cellprocessor/constraint/DMinMax.java b/src/org/supercsv/cellprocessor/constraint/DMinMax.java index a321428..6cf2555 100644 --- a/src/org/supercsv/cellprocessor/constraint/DMinMax.java +++ b/src/org/supercsv/cellprocessor/constraint/DMinMax.java @@ -1,65 +1,65 @@ package org.supercsv.cellprocessor.constraint; import org.supercsv.cellprocessor.CellProcessorAdaptor; import org.supercsv.cellprocessor.ift.DoubleCellProcessor; import org.supercsv.exception.SuperCSVException; import org.supercsv.util.CSVContext; /** * Converts the input data to a long and ensure that number is within a specified numeric range. If the data has no * upper bound (or lower bound), you should use either of <code>MIN</code> or <code>MAX</code> constants provided in * the class. * * @author Kasper B. Graversen */ public class DMinMax extends CellProcessorAdaptor { public static final double MAXD = Double.MAX_VALUE; public static final double MIND = Double.MIN_VALUE; public static final double MAXS = Short.MAX_VALUE; public static final double MINS = Short.MIN_VALUE; public static final double MAXC = Character.MAX_VALUE; public static final double MINC = Character.MIN_VALUE; public static final double MAX8bit = 255; public static final double MIN8bit = -128; protected double min, max; public DMinMax(final double min, final double max) { super(); init(min, max); } public DMinMax(final double min, final double max, final DoubleCellProcessor next) { super(next); init(min, max); } /** * {@inheritDoc} */ @Override - public Object execute(final Object value, final CSVContext context) throws NumberFormatException { + public Object execute(final Object value, final CSVContext context) throws SuperCSVException { final Double result; if(value instanceof Double) { result = (Double) value; } else { result = Double.parseDouble(value.toString()); } if(!(result >= min && result <= max)) { throw new SuperCSVException("Entry \"" + value + "\" on line " + context.lineNumber + " column " + context.columnNumber + " is not within the numerical range " + min + "-" + max, context); } return next.execute(result, context); } private void init(final double min, final double max) { if(max < min) { throw new SuperCSVException("max < min in the arguments " + min + " " + max); } this.min = min; this.max = max; } }
true
true
public Object execute(final Object value, final CSVContext context) throws NumberFormatException { final Double result; if(value instanceof Double) { result = (Double) value; } else { result = Double.parseDouble(value.toString()); } if(!(result >= min && result <= max)) { throw new SuperCSVException("Entry \"" + value + "\" on line " + context.lineNumber + " column " + context.columnNumber + " is not within the numerical range " + min + "-" + max, context); } return next.execute(result, context); }
public Object execute(final Object value, final CSVContext context) throws SuperCSVException { final Double result; if(value instanceof Double) { result = (Double) value; } else { result = Double.parseDouble(value.toString()); } if(!(result >= min && result <= max)) { throw new SuperCSVException("Entry \"" + value + "\" on line " + context.lineNumber + " column " + context.columnNumber + " is not within the numerical range " + min + "-" + max, context); } return next.execute(result, context); }
diff --git a/src/plugins/org.drftpd.commands.zipscript.zip.links/src/org/drftpd/commands/zipscript/zip/links/hooks/LinksZipPostHook.java b/src/plugins/org.drftpd.commands.zipscript.zip.links/src/org/drftpd/commands/zipscript/zip/links/hooks/LinksZipPostHook.java index 7e65eba6..77cd79e4 100644 --- a/src/plugins/org.drftpd.commands.zipscript.zip.links/src/org/drftpd/commands/zipscript/zip/links/hooks/LinksZipPostHook.java +++ b/src/plugins/org.drftpd.commands.zipscript.zip.links/src/org/drftpd/commands/zipscript/zip/links/hooks/LinksZipPostHook.java @@ -1,162 +1,162 @@ /* * This file is part of DrFTPD, Distributed FTP Daemon. * * DrFTPD 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) any later version. * * DrFTPD 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 DrFTPD; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.drftpd.commands.zipscript.zip.links.hooks; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ResourceBundle; import org.drftpd.commandmanager.CommandRequest; import org.drftpd.commandmanager.CommandResponse; import org.drftpd.commandmanager.PostHookInterface; import org.drftpd.commandmanager.StandardCommandManager; import org.drftpd.commands.zipscript.links.LinkUtils; import org.drftpd.commands.zipscript.vfs.ZipscriptVFSDataSFV; import org.drftpd.commands.zipscript.zip.DizStatus; import org.drftpd.commands.zipscript.zip.vfs.ZipscriptVFSDataZip; import org.drftpd.exceptions.NoAvailableSlaveException; import org.drftpd.exceptions.SlaveUnavailableException; import org.drftpd.vfs.DirectoryHandle; import org.drftpd.vfs.VirtualFileSystem; /** * @author CyBeR * @version $Id: LinksZipPostHook.java 2076 2010-09-19 18:31:19Z djb61 $ */ public class LinksZipPostHook implements PostHookInterface { private ResourceBundle _bundle; public void initialize(StandardCommandManager cManager) { _bundle = cManager.getResourceBundle(); } public void doLinksZipSTORIncompleteHook(CommandRequest request, CommandResponse response) { if (response.getCode() != 226) { // STOR failed, abort link return; } ZipscriptVFSDataZip zipData = new ZipscriptVFSDataZip(request.getCurrentDirectory()); try { DizStatus dizStatus = zipData.getDizStatus(); if (dizStatus.isFinished()) { // dir is complete, remove link LinkUtils.processLink(request, "delete", _bundle); } else { LinkUtils.processLink(request, "create", _bundle); } } catch (NoAvailableSlaveException e) { // Slave holding zip is unavailable } catch (FileNotFoundException e) { // No zip in dir } catch (IOException e) { // zip not readable } return; } public void doLinksZipDELECleanupHook(CommandRequest request, CommandResponse response) { if (response.getCode() != 250) { // DELE failed, abort cleanup return; } ZipscriptVFSDataZip zipData = new ZipscriptVFSDataZip(request.getCurrentDirectory()); try { DizStatus dizStatus = zipData.getDizStatus(); if (!dizStatus.isFinished()) { // dir is now incomplete, add link LinkUtils.processLink(request, "create", _bundle); } } catch (NoAvailableSlaveException e) { // Slave holding zip is unavailable } catch (FileNotFoundException e) { // No zip in dir // We have to make sure there is a .sfv in this dir before deleting try { ZipscriptVFSDataSFV sfvData = new ZipscriptVFSDataSFV(request.getCurrentDirectory()); sfvData.getSFVStatus(); } catch (NoAvailableSlaveException e1) { // Slave holding sfv is unavailable } catch (FileNotFoundException e1) { // No SFV in dir - now we can delete link LinkUtils.processLink(request, "delete", _bundle); } catch (IOException e1) { // SFV not readable } catch (SlaveUnavailableException e1) { // No Slave with SFV available } } catch (IOException e) { // zip not readable } return; } public void doLinksZipWIPECleanupHook(CommandRequest request, CommandResponse response) { if (response.getCode() != 200) { // WIPE failed, abort cleanup return; } String arg = request.getArgument(); if (arg.startsWith("-r ")) { arg = arg.substring(3); } if (arg.endsWith(VirtualFileSystem.separator)) { - arg.substring(0,arg.length()-1); + arg = arg.substring(0,arg.length()-1); } DirectoryHandle wipeDir = request.getCurrentDirectory().getNonExistentDirectoryHandle(arg).getParent(); if (!wipeDir.exists()) { return; } DirectoryHandle oldrequestdir = request.getCurrentDirectory(); ZipscriptVFSDataZip zipData = new ZipscriptVFSDataZip(wipeDir); try { DizStatus dizStatus = zipData.getDizStatus(); if (!dizStatus.isFinished()) { // dir is now incomplete, add link request.setCurrentDirectory(wipeDir); LinkUtils.processLink(request, "create", _bundle); request.setCurrentDirectory(oldrequestdir); } } catch (NoAvailableSlaveException e) { // Slave holding zip is unavailable } catch (FileNotFoundException e) { // No zip in dir // We have to make sure there is a .sfv in this dir before deleting try { ZipscriptVFSDataSFV sfvData = new ZipscriptVFSDataSFV(wipeDir); sfvData.getSFVStatus(); } catch (NoAvailableSlaveException e1) { // Slave holding sfv is unavailable } catch (FileNotFoundException e1) { // No SFV in dir - now we can delete link request.setCurrentDirectory(wipeDir); LinkUtils.processLink(request, "delete", _bundle); request.setCurrentDirectory(oldrequestdir); } catch (IOException e1) { // SFV not readable } catch (SlaveUnavailableException e1) { // No Slave with SFV available } } catch (IOException e) { // zip not readable } } }
true
true
public void doLinksZipWIPECleanupHook(CommandRequest request, CommandResponse response) { if (response.getCode() != 200) { // WIPE failed, abort cleanup return; } String arg = request.getArgument(); if (arg.startsWith("-r ")) { arg = arg.substring(3); } if (arg.endsWith(VirtualFileSystem.separator)) { arg.substring(0,arg.length()-1); } DirectoryHandle wipeDir = request.getCurrentDirectory().getNonExistentDirectoryHandle(arg).getParent(); if (!wipeDir.exists()) { return; } DirectoryHandle oldrequestdir = request.getCurrentDirectory(); ZipscriptVFSDataZip zipData = new ZipscriptVFSDataZip(wipeDir); try { DizStatus dizStatus = zipData.getDizStatus(); if (!dizStatus.isFinished()) { // dir is now incomplete, add link request.setCurrentDirectory(wipeDir); LinkUtils.processLink(request, "create", _bundle); request.setCurrentDirectory(oldrequestdir); } } catch (NoAvailableSlaveException e) { // Slave holding zip is unavailable } catch (FileNotFoundException e) { // No zip in dir // We have to make sure there is a .sfv in this dir before deleting try { ZipscriptVFSDataSFV sfvData = new ZipscriptVFSDataSFV(wipeDir); sfvData.getSFVStatus(); } catch (NoAvailableSlaveException e1) { // Slave holding sfv is unavailable } catch (FileNotFoundException e1) { // No SFV in dir - now we can delete link request.setCurrentDirectory(wipeDir); LinkUtils.processLink(request, "delete", _bundle); request.setCurrentDirectory(oldrequestdir); } catch (IOException e1) { // SFV not readable } catch (SlaveUnavailableException e1) { // No Slave with SFV available } } catch (IOException e) { // zip not readable } }
public void doLinksZipWIPECleanupHook(CommandRequest request, CommandResponse response) { if (response.getCode() != 200) { // WIPE failed, abort cleanup return; } String arg = request.getArgument(); if (arg.startsWith("-r ")) { arg = arg.substring(3); } if (arg.endsWith(VirtualFileSystem.separator)) { arg = arg.substring(0,arg.length()-1); } DirectoryHandle wipeDir = request.getCurrentDirectory().getNonExistentDirectoryHandle(arg).getParent(); if (!wipeDir.exists()) { return; } DirectoryHandle oldrequestdir = request.getCurrentDirectory(); ZipscriptVFSDataZip zipData = new ZipscriptVFSDataZip(wipeDir); try { DizStatus dizStatus = zipData.getDizStatus(); if (!dizStatus.isFinished()) { // dir is now incomplete, add link request.setCurrentDirectory(wipeDir); LinkUtils.processLink(request, "create", _bundle); request.setCurrentDirectory(oldrequestdir); } } catch (NoAvailableSlaveException e) { // Slave holding zip is unavailable } catch (FileNotFoundException e) { // No zip in dir // We have to make sure there is a .sfv in this dir before deleting try { ZipscriptVFSDataSFV sfvData = new ZipscriptVFSDataSFV(wipeDir); sfvData.getSFVStatus(); } catch (NoAvailableSlaveException e1) { // Slave holding sfv is unavailable } catch (FileNotFoundException e1) { // No SFV in dir - now we can delete link request.setCurrentDirectory(wipeDir); LinkUtils.processLink(request, "delete", _bundle); request.setCurrentDirectory(oldrequestdir); } catch (IOException e1) { // SFV not readable } catch (SlaveUnavailableException e1) { // No Slave with SFV available } } catch (IOException e) { // zip not readable } }
diff --git a/src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/transform/ResolvedValueSetTransform.java b/src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/transform/ResolvedValueSetTransform.java index 7f40013..a186683 100644 --- a/src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/transform/ResolvedValueSetTransform.java +++ b/src/main/java/edu/mayo/cts2/framework/plugin/service/bioportal/transform/ResolvedValueSetTransform.java @@ -1,104 +1,110 @@ /* * Copyright: (c) 2004-2011 Mayo Foundation for Medical Education and * Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the * triple-shield Mayo logo are trademarks and service marks of MFMER. * * Except as contained in the copyright notice above, or as used to identify * MFMER as the author of this software, the trade names, trademarks, service * marks, or product names of the copyright holder shall not be used in * advertising, promotion or otherwise in connection with this software without * prior written authorization of the copyright holder. * * 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 edu.mayo.cts2.framework.plugin.service.bioportal.transform; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.w3c.dom.Node; import edu.mayo.cts2.framework.model.valuesetdefinition.ResolvedValueSetDirectoryEntry; import edu.mayo.cts2.framework.model.valuesetdefinition.ResolvedValueSetHeader; import edu.mayo.cts2.framework.plugin.service.bioportal.rest.BioportalRestUtils; /** * The Class CodeSystemVersionTransform. * * @author <a href="mailto:[email protected]">Kevin Peterson</a> */ @Component public class ResolvedValueSetTransform extends AbstractOntologyTransform { /* (non-Javadoc) * @see edu.mayo.cts2.framework.plugin.service.bioportal.transform.AbstractBioportalOntologyVersionTransformTemplate#createNewResourceVersion() */ public List<ResolvedValueSetDirectoryEntry> transfrom(String xml) { Document doc = BioportalRestUtils.getDocument(xml); List<Node> nodeList = TransformUtils.getNodeListWithPath(doc, "success.data.list.ontologyBean"); List<ResolvedValueSetDirectoryEntry> returnList = new ArrayList<ResolvedValueSetDirectoryEntry>(); for(Node node : nodeList){ ResolvedValueSetDirectoryEntry entry = new ResolvedValueSetDirectoryEntry(); String ontologyVersionId = TransformUtils.getNamedChildText(node, ONTOLOGY_VERSION_ID); - ResolvedValueSetHeader header = this.getHeader(node); + ResolvedValueSetHeader header; + try { + header = this.getHeader(node); + } catch (Exception e) { + //sometimes these ontologies may be removed from Bioportal.. if so, skip. + continue; + } entry.setResolvedHeader(header); entry.setHref(this.getUrlConstructor().createResolvedValueSetUrl( header.getResolutionOf().getValueSet().getContent(), header.getResolutionOf().getValueSetDefinition().getContent(), ontologyVersionId)); entry.setResolvedValueSetURI(header.getResolutionOf().getValueSet().getUri() + "/resolution/" + ontologyVersionId); returnList.add(entry); } return returnList; } public ResolvedValueSetHeader getHeader(Node node){ String ontologyId = TransformUtils.getNamedChildText(node, ONTOLOGY_ID); String ontologyVersionId = TransformUtils.getNamedChildText(node, ONTOLOGY_VERSION_ID); ResolvedValueSetHeader header = new ResolvedValueSetHeader(); header.setResolutionOf(this.getValueSetDefinitionReference(ontologyId, ontologyVersionId)); List<Node> resolvedCodeSystemVersions = TransformUtils.getNodeListWithPath(node, "viewOnOntologyVersionId.int"); for(Node resolvedCodeSystemVersion : resolvedCodeSystemVersions){ String codeSystemVersionOntologyVersionId = TransformUtils.getNodeText(resolvedCodeSystemVersion); String codeSystemVersionName = this.getIdentityConverter().ontologyVersionIdToCodeSystemVersionName(codeSystemVersionOntologyVersionId); String codeSystemName = this.getIdentityConverter().codeSystemVersionNameCodeSystemName(codeSystemVersionName); header.addResolvedUsingCodeSystem( this.buildCodeSystemVersionReference( codeSystemName, codeSystemVersionName)); } return header; } }
true
true
public List<ResolvedValueSetDirectoryEntry> transfrom(String xml) { Document doc = BioportalRestUtils.getDocument(xml); List<Node> nodeList = TransformUtils.getNodeListWithPath(doc, "success.data.list.ontologyBean"); List<ResolvedValueSetDirectoryEntry> returnList = new ArrayList<ResolvedValueSetDirectoryEntry>(); for(Node node : nodeList){ ResolvedValueSetDirectoryEntry entry = new ResolvedValueSetDirectoryEntry(); String ontologyVersionId = TransformUtils.getNamedChildText(node, ONTOLOGY_VERSION_ID); ResolvedValueSetHeader header = this.getHeader(node); entry.setResolvedHeader(header); entry.setHref(this.getUrlConstructor().createResolvedValueSetUrl( header.getResolutionOf().getValueSet().getContent(), header.getResolutionOf().getValueSetDefinition().getContent(), ontologyVersionId)); entry.setResolvedValueSetURI(header.getResolutionOf().getValueSet().getUri() + "/resolution/" + ontologyVersionId); returnList.add(entry); } return returnList; }
public List<ResolvedValueSetDirectoryEntry> transfrom(String xml) { Document doc = BioportalRestUtils.getDocument(xml); List<Node> nodeList = TransformUtils.getNodeListWithPath(doc, "success.data.list.ontologyBean"); List<ResolvedValueSetDirectoryEntry> returnList = new ArrayList<ResolvedValueSetDirectoryEntry>(); for(Node node : nodeList){ ResolvedValueSetDirectoryEntry entry = new ResolvedValueSetDirectoryEntry(); String ontologyVersionId = TransformUtils.getNamedChildText(node, ONTOLOGY_VERSION_ID); ResolvedValueSetHeader header; try { header = this.getHeader(node); } catch (Exception e) { //sometimes these ontologies may be removed from Bioportal.. if so, skip. continue; } entry.setResolvedHeader(header); entry.setHref(this.getUrlConstructor().createResolvedValueSetUrl( header.getResolutionOf().getValueSet().getContent(), header.getResolutionOf().getValueSetDefinition().getContent(), ontologyVersionId)); entry.setResolvedValueSetURI(header.getResolutionOf().getValueSet().getUri() + "/resolution/" + ontologyVersionId); returnList.add(entry); } return returnList; }
diff --git a/src/main/java/test/cli/cloudify/cloud/byon/RepetativeInstallAndUninstallOnByonTest.java b/src/main/java/test/cli/cloudify/cloud/byon/RepetativeInstallAndUninstallOnByonTest.java index a54330a4..1ad7fe93 100644 --- a/src/main/java/test/cli/cloudify/cloud/byon/RepetativeInstallAndUninstallOnByonTest.java +++ b/src/main/java/test/cli/cloudify/cloud/byon/RepetativeInstallAndUninstallOnByonTest.java @@ -1,65 +1,65 @@ package test.cli.cloudify.cloud.byon; import java.util.concurrent.TimeUnit; import org.openspaces.admin.pu.ProcessingUnit; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import framework.utils.AssertUtils; import framework.utils.LogUtils; import framework.utils.ScriptUtils; /** * <p> * 1. bootstrap byon. * <p> * 2. repeat steps 3-4 three times. * <p> * 3. install petclinic-simple and assert installation. * <p> * 4. uninstall petclinic-simple and assert successful uninstall. * */ public class RepetativeInstallAndUninstallOnByonTest extends AbstractByonCloudTest { private final static int REPETITIONS = 3; @BeforeClass(alwaysRun = true) protected void bootstrap() throws Exception { super.bootstrap(); } @Test(timeOut = DEFAULT_TEST_TIMEOUT * 2, enabled = true) public void testPetclinicSimple() throws Exception { for (int i = 0; i < REPETITIONS; i++) { LogUtils.log("petclinic install number " + (i + 1)); installApplicationAndWait(ScriptUtils.getBuildPath() + "/recipes/apps/petclinic-simple", "petclinic"); - ProcessingUnit mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 5, TimeUnit.MINUTES); - ProcessingUnit tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 5, TimeUnit.MINUTES); + ProcessingUnit mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 1, TimeUnit.MINUTES); + ProcessingUnit tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 1, TimeUnit.MINUTES); AssertUtils.assertNotNull("Failed to discover processing unit petclinic.mongod even though it was installed succesfully ", mongod); AssertUtils.assertNotNull("Failed to discover processing unit petclinic.tomcat even though it was installed succesfully ", tomcat); LogUtils.log("petclinic uninstall number " + (i + 1)); uninstallApplicationAndWait("petclinic"); LogUtils.log("Application petclinic uninstalled succesfully"); - mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 5, TimeUnit.MINUTES); - tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 5, TimeUnit.MINUTES); + mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 1, TimeUnit.MINUTES); + tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 1, TimeUnit.MINUTES); AssertUtils.assertNull("Processing unit petclinic.mongod is still discovered even though it was uninstalled succesfully ", mongod); AssertUtils.assertNull("Processing unit petclinic.tomcat is still discovered even though it was uninstalled succesfully ", tomcat); } } @AfterClass(alwaysRun = true) protected void teardown() throws Exception { super.teardown(); } }
false
true
public void testPetclinicSimple() throws Exception { for (int i = 0; i < REPETITIONS; i++) { LogUtils.log("petclinic install number " + (i + 1)); installApplicationAndWait(ScriptUtils.getBuildPath() + "/recipes/apps/petclinic-simple", "petclinic"); ProcessingUnit mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 5, TimeUnit.MINUTES); ProcessingUnit tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 5, TimeUnit.MINUTES); AssertUtils.assertNotNull("Failed to discover processing unit petclinic.mongod even though it was installed succesfully ", mongod); AssertUtils.assertNotNull("Failed to discover processing unit petclinic.tomcat even though it was installed succesfully ", tomcat); LogUtils.log("petclinic uninstall number " + (i + 1)); uninstallApplicationAndWait("petclinic"); LogUtils.log("Application petclinic uninstalled succesfully"); mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 5, TimeUnit.MINUTES); tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 5, TimeUnit.MINUTES); AssertUtils.assertNull("Processing unit petclinic.mongod is still discovered even though it was uninstalled succesfully ", mongod); AssertUtils.assertNull("Processing unit petclinic.tomcat is still discovered even though it was uninstalled succesfully ", tomcat); } }
public void testPetclinicSimple() throws Exception { for (int i = 0; i < REPETITIONS; i++) { LogUtils.log("petclinic install number " + (i + 1)); installApplicationAndWait(ScriptUtils.getBuildPath() + "/recipes/apps/petclinic-simple", "petclinic"); ProcessingUnit mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 1, TimeUnit.MINUTES); ProcessingUnit tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 1, TimeUnit.MINUTES); AssertUtils.assertNotNull("Failed to discover processing unit petclinic.mongod even though it was installed succesfully ", mongod); AssertUtils.assertNotNull("Failed to discover processing unit petclinic.tomcat even though it was installed succesfully ", tomcat); LogUtils.log("petclinic uninstall number " + (i + 1)); uninstallApplicationAndWait("petclinic"); LogUtils.log("Application petclinic uninstalled succesfully"); mongod = admin.getProcessingUnits().waitFor("petclinic.mongod", 1, TimeUnit.MINUTES); tomcat = admin.getProcessingUnits().waitFor("petclinic.tomcat", 1, TimeUnit.MINUTES); AssertUtils.assertNull("Processing unit petclinic.mongod is still discovered even though it was uninstalled succesfully ", mongod); AssertUtils.assertNull("Processing unit petclinic.tomcat is still discovered even though it was uninstalled succesfully ", tomcat); } }
diff --git a/src/libbluray/bdj/java/java/awt/BDFontMetrics.java b/src/libbluray/bdj/java/java/awt/BDFontMetrics.java index 0c6afb1..aa597f9 100644 --- a/src/libbluray/bdj/java/java/awt/BDFontMetrics.java +++ b/src/libbluray/bdj/java/java/awt/BDFontMetrics.java @@ -1,251 +1,253 @@ /* * This file is part of libbluray * Copyright (C) 2012 libbluray * * 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, see * <http://www.gnu.org/licenses/>. */ package java.awt; import java.io.*; import java.security.*; import java.util.*; public class BDFontMetrics extends FontMetrics { static final long serialVersionUID = -4956160226949100590L; private static long ftLib = 0; private static Map fontNameMap; private static native long initN(); private static native void destroyN(long ftLib); public static void init() { //System.loadLibrary("bluray"); if (ftLib != 0) return; ftLib = initN(); - if (ftLib == 0) + if (ftLib == 0) { + System.err.println("freetype library not loaded"); throw new AWTError("freetype lib not loaded"); + } Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { Iterator it = fontMetricsMap.values().iterator(); while (it.hasNext()) { try { BDFontMetrics fm = (BDFontMetrics)it.next(); it.remove(); fm.finalize(); } catch (Throwable e) { e.printStackTrace(); } } BDFontMetrics.destroyN(BDFontMetrics.ftLib); } } ); String javaHome = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return System.getProperty("java.home"); } } ); File f = new File(javaHome, "lib" + File.separator + "fonts"); String dir = f.getAbsolutePath() + File.separator; fontNameMap = new HashMap(24); fontNameMap.put("serif.0", dir + "LucidaBrightRegular.ttf"); fontNameMap.put("serif.1", dir + "LucidaBrightDemiBold.ttf"); fontNameMap.put("serif.2", dir + "LucidaBrightItalic.ttf"); fontNameMap.put("serif.3", dir + "LucidaBrightDemiItalic.ttf"); fontNameMap.put("sansserif.0", dir + "LucidaSansRegular.ttf"); fontNameMap.put("sansserif.1", dir + "LucidaSansDemiBold.ttf"); fontNameMap.put("sansserif.2", dir + "LucidaSansOblique.ttf"); fontNameMap.put("sansserif.3", dir + "LucidaSansDemiOblique.ttf"); fontNameMap.put("monospaced.0", dir + "LucidaTypewriterRegular.ttf"); fontNameMap.put("monospaced.1", dir + "LucidaTypewriterBold.ttf"); fontNameMap.put("monospaced.2", dir + "LucidaTypewriterOblique.ttf"); fontNameMap.put("monospaced.3", dir + "LucidaTypewriterBoldOblique.ttf"); fontNameMap.put("dialog.0", dir + "LucidaSansRegular.ttf"); fontNameMap.put("dialog.1", dir + "LucidaSansDemiBold.ttf"); fontNameMap.put("dialog.2", dir + "LucidaSansOblique.ttf"); fontNameMap.put("dialog.3", dir + "LucidaSansDemiOblique.ttf"); fontNameMap.put("dialoginput.0", dir + "LucidaTypewriterRegular.ttf"); fontNameMap.put("dialoginput.1", dir + "LucidaTypewriterBold.ttf"); fontNameMap.put("dialoginput.2", dir + "LucidaTypewriterOblique.ttf"); fontNameMap.put("dialoginput.3", dir + "LucidaTypewriterBoldOblique.ttf"); fontNameMap.put("default.0", dir + "LucidaSansRegular.ttf"); fontNameMap.put("default.1", dir + "LucidaSansDemiBold.ttf"); fontNameMap.put("default.2", dir + "LucidaSansOblique.ttf"); fontNameMap.put("default.3", dir + "LucidaSansDemiOblique.ttf"); } /** A map which maps a native font name and size to a font metrics object. This is used as a cache to prevent loading the same fonts multiple times. */ private static Map fontMetricsMap = new HashMap(); /** Gets the BDFontMetrics object for the supplied font. This method caches font metrics to ensure native fonts are not loaded twice for the same font. */ static synchronized BDFontMetrics getFontMetrics(Font font) { /* See if metrics has been stored in font already. */ BDFontMetrics fm = null; //BDFontMetrics fm = (BDFontMetrics)font.metrics; //if (fm == null) { /* See if a font metrics of the same native name and size has already been loaded. If it has then we use that one. */ String nativeName = (String)fontNameMap.get(font.getName().toLowerCase() + "." + font.getStyle()); if (nativeName == null) nativeName = (String)fontNameMap.get("default." + font.getStyle()); String key = nativeName + "." + font.getSize(); fm = (BDFontMetrics)fontMetricsMap.get(key); if (fm == null) fontMetricsMap.put(key, fm = new BDFontMetrics(font, nativeName)); //font.metrics = fm; //} return fm; } static String[] getFontList() { init(); ArrayList fontNames = new ArrayList(); Iterator fonts = fontNameMap.keySet().iterator(); int dotidx; while (fonts.hasNext()) { String fontname = (String) fonts.next(); if ((dotidx = fontname.indexOf('.')) == -1) dotidx = fontname.length(); fontname = fontname.substring(0, dotidx); if (!fontNames.contains(fontname)) fontNames.add(fontname); } return (String[])fontNames.toArray(new String[fontNames.size()]); } public static void registerFont(String name, int style, String path) { File f = new File(path); path = f.getAbsolutePath(); if (path != null) { name = name.toLowerCase() + "." + style; fontNameMap.put(name, path); } } public static boolean registerFont(File f) { //TODO org.videolan.Logger.unimplemented("BDFontMetrics", "registerFont"); return false; } public static void unregisterFont(String name, int style) { name = name.toLowerCase() + "." + style; fontNameMap.remove(name); } long ftFace; private int ascent; private int descent; private int leading; private int maxAdvance; /** Cache of first 256 Unicode characters as these map to ASCII characters and are often used. */ private int[] widths; /** * Creates a font metrics for the supplied font. To get a font metrics for a font * use the static method getFontMetrics instead which does caching. */ private BDFontMetrics(Font font, String nativeName) { super(font); ftFace = loadFontN(ftLib, nativeName, font.getSize()); if (ftFace == 0) throw new AWTError("font face:" + nativeName + " not loaded"); /* Cache first 256 char widths for use by the getWidths method and for faster metric calculation as they are commonly used (ASCII) characters. */ widths = new int[256]; for (int i = 0; i < 256; i++) widths[i] = charWidthN(ftFace, (char)i); } private native long loadFontN(long ftLib, String fontName, int size); private native void destroyFontN(long ftFace); private native int charWidthN(long ftFace, char c); private native int stringWidthN(long ftFace, String string); private native int charsWidthN(long ftFace, char chars[], int offset, int len); public int getAscent() { return ascent; } public int getDescent() { return descent; } public int getLeading() { return leading; } public int getMaxAdvance() { return maxAdvance; } /** * Fast lookup of first 256 chars as these are always the same eg. ASCII charset. */ public int charWidth(char c) { if (c < 256) return widths[c]; return charWidthN(ftFace, c); } /** * Return the width of the specified string in this Font. */ public int stringWidth(String string) { return stringWidthN(ftFace, string); } /** * Return the width of the specified char[] in this Font. */ public int charsWidth(char chars[], int offset, int length) { return charsWidthN(ftFace, chars, offset, length); } /** * Get the widths of the first 256 characters in the font. */ public int[] getWidths() { int[] newWidths = new int[256]; System.arraycopy(widths, 0, newWidths, 0, 256); return newWidths; } protected void finalize() throws Throwable { if (ftFace != 0) { destroyFontN(ftFace); ftFace = 0; } super.finalize(); } }
false
true
public static void init() { //System.loadLibrary("bluray"); if (ftLib != 0) return; ftLib = initN(); if (ftLib == 0) throw new AWTError("freetype lib not loaded"); Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { Iterator it = fontMetricsMap.values().iterator(); while (it.hasNext()) { try { BDFontMetrics fm = (BDFontMetrics)it.next(); it.remove(); fm.finalize(); } catch (Throwable e) { e.printStackTrace(); } } BDFontMetrics.destroyN(BDFontMetrics.ftLib); } } ); String javaHome = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return System.getProperty("java.home"); } } ); File f = new File(javaHome, "lib" + File.separator + "fonts"); String dir = f.getAbsolutePath() + File.separator; fontNameMap = new HashMap(24); fontNameMap.put("serif.0", dir + "LucidaBrightRegular.ttf"); fontNameMap.put("serif.1", dir + "LucidaBrightDemiBold.ttf"); fontNameMap.put("serif.2", dir + "LucidaBrightItalic.ttf"); fontNameMap.put("serif.3", dir + "LucidaBrightDemiItalic.ttf"); fontNameMap.put("sansserif.0", dir + "LucidaSansRegular.ttf"); fontNameMap.put("sansserif.1", dir + "LucidaSansDemiBold.ttf"); fontNameMap.put("sansserif.2", dir + "LucidaSansOblique.ttf"); fontNameMap.put("sansserif.3", dir + "LucidaSansDemiOblique.ttf"); fontNameMap.put("monospaced.0", dir + "LucidaTypewriterRegular.ttf"); fontNameMap.put("monospaced.1", dir + "LucidaTypewriterBold.ttf"); fontNameMap.put("monospaced.2", dir + "LucidaTypewriterOblique.ttf"); fontNameMap.put("monospaced.3", dir + "LucidaTypewriterBoldOblique.ttf"); fontNameMap.put("dialog.0", dir + "LucidaSansRegular.ttf"); fontNameMap.put("dialog.1", dir + "LucidaSansDemiBold.ttf"); fontNameMap.put("dialog.2", dir + "LucidaSansOblique.ttf"); fontNameMap.put("dialog.3", dir + "LucidaSansDemiOblique.ttf"); fontNameMap.put("dialoginput.0", dir + "LucidaTypewriterRegular.ttf"); fontNameMap.put("dialoginput.1", dir + "LucidaTypewriterBold.ttf"); fontNameMap.put("dialoginput.2", dir + "LucidaTypewriterOblique.ttf"); fontNameMap.put("dialoginput.3", dir + "LucidaTypewriterBoldOblique.ttf"); fontNameMap.put("default.0", dir + "LucidaSansRegular.ttf"); fontNameMap.put("default.1", dir + "LucidaSansDemiBold.ttf"); fontNameMap.put("default.2", dir + "LucidaSansOblique.ttf"); fontNameMap.put("default.3", dir + "LucidaSansDemiOblique.ttf"); }
public static void init() { //System.loadLibrary("bluray"); if (ftLib != 0) return; ftLib = initN(); if (ftLib == 0) { System.err.println("freetype library not loaded"); throw new AWTError("freetype lib not loaded"); } Runtime.getRuntime().addShutdownHook( new Thread() { public void run() { Iterator it = fontMetricsMap.values().iterator(); while (it.hasNext()) { try { BDFontMetrics fm = (BDFontMetrics)it.next(); it.remove(); fm.finalize(); } catch (Throwable e) { e.printStackTrace(); } } BDFontMetrics.destroyN(BDFontMetrics.ftLib); } } ); String javaHome = (String) AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return System.getProperty("java.home"); } } ); File f = new File(javaHome, "lib" + File.separator + "fonts"); String dir = f.getAbsolutePath() + File.separator; fontNameMap = new HashMap(24); fontNameMap.put("serif.0", dir + "LucidaBrightRegular.ttf"); fontNameMap.put("serif.1", dir + "LucidaBrightDemiBold.ttf"); fontNameMap.put("serif.2", dir + "LucidaBrightItalic.ttf"); fontNameMap.put("serif.3", dir + "LucidaBrightDemiItalic.ttf"); fontNameMap.put("sansserif.0", dir + "LucidaSansRegular.ttf"); fontNameMap.put("sansserif.1", dir + "LucidaSansDemiBold.ttf"); fontNameMap.put("sansserif.2", dir + "LucidaSansOblique.ttf"); fontNameMap.put("sansserif.3", dir + "LucidaSansDemiOblique.ttf"); fontNameMap.put("monospaced.0", dir + "LucidaTypewriterRegular.ttf"); fontNameMap.put("monospaced.1", dir + "LucidaTypewriterBold.ttf"); fontNameMap.put("monospaced.2", dir + "LucidaTypewriterOblique.ttf"); fontNameMap.put("monospaced.3", dir + "LucidaTypewriterBoldOblique.ttf"); fontNameMap.put("dialog.0", dir + "LucidaSansRegular.ttf"); fontNameMap.put("dialog.1", dir + "LucidaSansDemiBold.ttf"); fontNameMap.put("dialog.2", dir + "LucidaSansOblique.ttf"); fontNameMap.put("dialog.3", dir + "LucidaSansDemiOblique.ttf"); fontNameMap.put("dialoginput.0", dir + "LucidaTypewriterRegular.ttf"); fontNameMap.put("dialoginput.1", dir + "LucidaTypewriterBold.ttf"); fontNameMap.put("dialoginput.2", dir + "LucidaTypewriterOblique.ttf"); fontNameMap.put("dialoginput.3", dir + "LucidaTypewriterBoldOblique.ttf"); fontNameMap.put("default.0", dir + "LucidaSansRegular.ttf"); fontNameMap.put("default.1", dir + "LucidaSansDemiBold.ttf"); fontNameMap.put("default.2", dir + "LucidaSansOblique.ttf"); fontNameMap.put("default.3", dir + "LucidaSansDemiOblique.ttf"); }
diff --git a/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/utils/IntentEditorOpener.java b/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/utils/IntentEditorOpener.java index 556400be..66976d30 100644 --- a/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/utils/IntentEditorOpener.java +++ b/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/utils/IntentEditorOpener.java @@ -1,260 +1,261 @@ /******************************************************************************* * Copyright (c) 2010, 2011 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.mylyn.docs.intent.client.ui.utils; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.mylyn.docs.intent.client.ui.IntentEditorActivator; import org.eclipse.mylyn.docs.intent.client.ui.editor.IntentEditor; import org.eclipse.mylyn.docs.intent.client.ui.editor.IntentEditorInput; import org.eclipse.mylyn.docs.intent.client.ui.logger.IntentUiLogger; import org.eclipse.mylyn.docs.intent.collab.common.location.IntentLocations; import org.eclipse.mylyn.docs.intent.collab.handlers.adapters.ReadOnlyException; import org.eclipse.mylyn.docs.intent.collab.handlers.adapters.RepositoryAdapter; import org.eclipse.mylyn.docs.intent.collab.repository.Repository; import org.eclipse.mylyn.docs.intent.core.document.IntentDocument; import org.eclipse.mylyn.docs.intent.core.document.IntentGenericElement; import org.eclipse.mylyn.docs.intent.core.query.IntentHelper; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IEditorReference; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; /** * Class used for opening ReStrucutred Models editor. * * @author <a href="mailto:[email protected]">Alex Lagarde</a> * @author <a href="mailto:[email protected]">William Piers</a> */ public final class IntentEditorOpener { /** * EditorUtil constructor. */ private IntentEditorOpener() { } /** * Opens an editor on the Intent document contained in the given repository. * * @param repository * The repository to use for this editor * @param readOnlyMode * indicates if the editor should be opened in readOnly mode. * @param elementToSelectRangeWith * the element on which the created editor should select its range (can be null). * @param forceNewEditor * if true, will open in a new editor anyway. If false, will open in a new editor or select * inside of an already opened editor */ public static void openIntentEditor(final Repository repository, boolean readOnlyMode) { try { final RepositoryAdapter repositoryAdapter = repository.createRepositoryAdapter(); Resource resource = repositoryAdapter.getOrCreateResource(IntentLocations.INTENT_INDEX); if (!resource.getContents().isEmpty() && resource.getContents().iterator().next() instanceof IntentDocument) { EObject elementToOpen = resource.getContents().iterator().next(); openIntentEditor(repositoryAdapter, elementToOpen, false, elementToOpen, false); } } catch (PartInitException e) { IntentUiLogger.logError(e); } catch (ReadOnlyException e) { IntentUiLogger.logError(e); } } /** * Opens an editor on the element with the given identifier. * * @param repository * The repository to use for this editor * @param elementToOpen * the element to open. * @param readOnlyMode * indicates if the editor should be opened in readOnly mode. * @param elementToSelectRangeWith * the element on which the created editor should select its range (can be null). * @param forceNewEditor * if true, will open in a new editor anyway. If false, will open in a new editor or select * inside of an already opened editor */ public static void openIntentEditor(final Repository repository, final EObject elementToOpen, boolean readOnlyMode, EObject elementToSelectRangeWith, boolean forceNewEditor) { try { final RepositoryAdapter repositoryAdapter = repository.createRepositoryAdapter(); openIntentEditor(repositoryAdapter, elementToOpen, false, elementToSelectRangeWith, forceNewEditor); } catch (PartInitException e) { IntentUiLogger.logError(e); } } /** * Opens an editor on the element with the given identifier. * * @param repositoryAdapter * the repository adapter * @param elementToOpen * the element to open. * @param readOnlyMode * indicates if the editor should be opened in readOnly mode. * @param elementToSelectRangeWith * the element on which the created editor should select its range (can be null). * @param forceNewEditor * if true, will open in a new editor anyway. If false, will open in a new editor or select * inside of an already opened editor * @return the opened editor * @throws PartInitException * if the editor cannot be opened. */ private static IntentEditor openIntentEditor(RepositoryAdapter repositoryAdapter, EObject elementToOpen, boolean readOnlyMode, EObject elementToSelectRangeWith, boolean forceNewEditor) throws PartInitException { IntentEditor openedEditor = null; IStatus status = null; // We get the element on which open this editor if (readOnlyMode) { repositoryAdapter.openReadOnlyContext(); } else { repositoryAdapter.openSaveContext(); } boolean foundInAlreadyExistingEditor = false; if (!forceNewEditor) { // Step 2 : if an editor containing this element is already opened IntentEditor editor = getAlreadyOpenedEditor(elementToOpen); if (editor != null) { editor.getEditorSite().getPage().activate(editor); openedEditor = editor; - foundInAlreadyExistingEditor = editor.selectRange((IntentGenericElement)elementToOpen); + foundInAlreadyExistingEditor = editor + .selectRange((IntentGenericElement)elementToSelectRangeWith); } } if (openedEditor == null || !foundInAlreadyExistingEditor) { // Step 3 : we open a new editor. IWorkbenchPage page = null; try { page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); openedEditor = IntentEditorOpener.openEditor(repositoryAdapter, page, elementToOpen); EObject container = elementToSelectRangeWith; while (container != null && !(container instanceof IntentGenericElement)) { container = container.eContainer(); } if (container instanceof IntentGenericElement) { openedEditor.selectRange((IntentGenericElement)container); } else { if (elementToOpen instanceof IntentGenericElement) { openedEditor.selectRange((IntentGenericElement)elementToOpen); } } } catch (NullPointerException e) { status = new Status(IStatus.ERROR, IntentEditorActivator.PLUGIN_ID, "An unexpected error has occured"); throw new PartInitException(status); } } return openedEditor; } /** * If an editor is already opened on the given element, returns it ; returns null otherwise. * * @param elementToOpen * the element to search in editors * @return an IntentEditor already opened on the given element, null otherwise. */ public static IntentEditor getAlreadyOpenedEditor(EObject elementToOpen) { IntentEditor alreadyOpenedEditor = null; IWorkbenchPage activePage = null; IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow(); if (activeWorkbenchWindow != null) { activePage = activeWorkbenchWindow.getActivePage(); } if (activePage != null) { // While no editor containing the given element has been found IEditorReference[] editorReferences = activePage.getEditorReferences(); int editorCount = 0; while ((editorCount < editorReferences.length) && alreadyOpenedEditor == null) { IEditorReference editorReference = editorReferences[editorCount]; IEditorPart editor = editorReference.getEditor(false); if (editor instanceof IntentEditor) { if (((IntentEditor)editor).containsElement((IntentGenericElement)elementToOpen)) { alreadyOpenedEditor = (IntentEditor)editor; activePage.activate(alreadyOpenedEditor); } } editorCount++; } } return alreadyOpenedEditor; } /** * Opens an editor on the given IntentModel element. * * @param repositoryAdapter * the repository adapter to use for this document * @param page * the page in which the editor should be opened * @param intentElementToOpen * the Intent element to open * @return the opened editor * @throws PartInitException * if the editor cannot be opened. */ private static IntentEditor openEditor(RepositoryAdapter repositoryAdapter, IWorkbenchPage page, Object intentElementToOpen) throws PartInitException { // If we can't open a IntentEditor on the given element, we try to get its container until null or an // editable intent element is found boolean canBeOpenedByIntentEditor = IntentHelper.canBeOpenedByIntentEditor(intentElementToOpen); EObject elementToOpen = null; if (intentElementToOpen instanceof EObject) { elementToOpen = (EObject)intentElementToOpen; } while (!canBeOpenedByIntentEditor && elementToOpen != null && !(elementToOpen instanceof Resource)) { elementToOpen = elementToOpen.eContainer(); canBeOpenedByIntentEditor = IntentHelper.canBeOpenedByIntentEditor(elementToOpen); } if (canBeOpenedByIntentEditor) { IntentEditorInput input = new IntentEditorInput(elementToOpen, repositoryAdapter); IEditorPart part = page.openEditor(input, IntentEditorActivator.EDITOR_ID); if (part instanceof IntentEditor) { return (IntentEditor)part; } else { IStatus status = new Status(IStatus.ERROR, IntentEditorActivator.PLUGIN_ID, "cannot open the editor"); throw new PartInitException(status); } } else { IntentUiLogger.logError("this element is not a correct Intent element", new PartInitException( "Invalid element : must be a Intent Element")); IStatus status = new Status(IStatus.ERROR, IntentEditorActivator.PLUGIN_ID, "this element is not a correct Intent element"); throw new PartInitException(status); } } }
true
true
private static IntentEditor openIntentEditor(RepositoryAdapter repositoryAdapter, EObject elementToOpen, boolean readOnlyMode, EObject elementToSelectRangeWith, boolean forceNewEditor) throws PartInitException { IntentEditor openedEditor = null; IStatus status = null; // We get the element on which open this editor if (readOnlyMode) { repositoryAdapter.openReadOnlyContext(); } else { repositoryAdapter.openSaveContext(); } boolean foundInAlreadyExistingEditor = false; if (!forceNewEditor) { // Step 2 : if an editor containing this element is already opened IntentEditor editor = getAlreadyOpenedEditor(elementToOpen); if (editor != null) { editor.getEditorSite().getPage().activate(editor); openedEditor = editor; foundInAlreadyExistingEditor = editor.selectRange((IntentGenericElement)elementToOpen); } } if (openedEditor == null || !foundInAlreadyExistingEditor) { // Step 3 : we open a new editor. IWorkbenchPage page = null; try { page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); openedEditor = IntentEditorOpener.openEditor(repositoryAdapter, page, elementToOpen); EObject container = elementToSelectRangeWith; while (container != null && !(container instanceof IntentGenericElement)) { container = container.eContainer(); } if (container instanceof IntentGenericElement) { openedEditor.selectRange((IntentGenericElement)container); } else { if (elementToOpen instanceof IntentGenericElement) { openedEditor.selectRange((IntentGenericElement)elementToOpen); } } } catch (NullPointerException e) { status = new Status(IStatus.ERROR, IntentEditorActivator.PLUGIN_ID, "An unexpected error has occured"); throw new PartInitException(status); } } return openedEditor; }
private static IntentEditor openIntentEditor(RepositoryAdapter repositoryAdapter, EObject elementToOpen, boolean readOnlyMode, EObject elementToSelectRangeWith, boolean forceNewEditor) throws PartInitException { IntentEditor openedEditor = null; IStatus status = null; // We get the element on which open this editor if (readOnlyMode) { repositoryAdapter.openReadOnlyContext(); } else { repositoryAdapter.openSaveContext(); } boolean foundInAlreadyExistingEditor = false; if (!forceNewEditor) { // Step 2 : if an editor containing this element is already opened IntentEditor editor = getAlreadyOpenedEditor(elementToOpen); if (editor != null) { editor.getEditorSite().getPage().activate(editor); openedEditor = editor; foundInAlreadyExistingEditor = editor .selectRange((IntentGenericElement)elementToSelectRangeWith); } } if (openedEditor == null || !foundInAlreadyExistingEditor) { // Step 3 : we open a new editor. IWorkbenchPage page = null; try { page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); openedEditor = IntentEditorOpener.openEditor(repositoryAdapter, page, elementToOpen); EObject container = elementToSelectRangeWith; while (container != null && !(container instanceof IntentGenericElement)) { container = container.eContainer(); } if (container instanceof IntentGenericElement) { openedEditor.selectRange((IntentGenericElement)container); } else { if (elementToOpen instanceof IntentGenericElement) { openedEditor.selectRange((IntentGenericElement)elementToOpen); } } } catch (NullPointerException e) { status = new Status(IStatus.ERROR, IntentEditorActivator.PLUGIN_ID, "An unexpected error has occured"); throw new PartInitException(status); } } return openedEditor; }
diff --git a/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityFeed.java b/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityFeed.java index 3396fc5f4a..48b013bd34 100644 --- a/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityFeed.java +++ b/test-modules/webservice-test/src/test/java/org/openlmis/functional/FacilityFeed.java @@ -1,459 +1,459 @@ /* * Copyright © 2013 VillageReach. All Rights Reserved. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. * * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.openlmis.functional; import org.openlmis.UiUtils.HttpClient; import org.openlmis.UiUtils.ResponseEntity; import org.openlmis.UiUtils.TestCaseHelper; import org.openlmis.pageobjects.*; import org.openlmis.restapi.domain.Agent; import org.openqa.selenium.WebDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import java.util.List; import static com.thoughtworks.selenium.SeleneseTestBase.assertFalse; import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertEquals; import static com.thoughtworks.selenium.SeleneseTestNgHelper.assertTrue; import static org.openlmis.functional.JsonUtility.getJsonStringFor; import static org.openlmis.functional.JsonUtility.readObjectFromFile; public class FacilityFeed extends TestCaseHelper { public WebDriver driver; public static final String FULL_JSON_TXT_FILE_NAME = "AgentValid.txt"; public static final String userEmail = "[email protected]"; public static final String CREATE_URL = "http://localhost:9091/rest-api/agent.json"; public static final String UPDATE_URL = "http://localhost:9091/rest-api/agent/"; public static final String commTrackUser = "commTrack"; public static final String PHONE_NUMBER = "0099887766"; public static final String DEFAULT_AGENT_NAME = "AgentVinod"; public static final String DEFAULT_PARENT_FACILITY_CODE = "F10"; public static final String ACTIVE_STATUS = "true"; public static final String DEFAULT_AGENT_CODE = "A2"; public static final String JSON_EXTENSION = ".json"; public static final String GET = "GET"; public static final String POST = "POST"; public static final String PUT = "PUT"; @BeforeMethod(groups = {"webservice"}) public void setUp() throws Exception { super.setup(); super.setupDataExternalVendor(true); } @AfterMethod(groups = {"webservice"}) public void tearDown() throws Exception { dbWrapper.deleteData(); dbWrapper.closeConnection(); } @Test(groups = {"webservice"}, dataProvider = "Data-Provider-Function-Positive") public void testFacilityFeedUsingUI(String user, String program, String[] credentials) throws Exception { HttpClient client = new HttpClient(); client.createContext(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); dbWrapper.insertUser("200", user, "Ag/myf1Whs0fxr1FFfK8cs3q/VJ1qMs3yuMLDTeEcZEGzstj/waaUsQNQTIKk1U5JRzrDbPLCzCO1/vB5YGaEQ==", "F10", "[email protected]", "openLmis"); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility(); String geoZone = "Ngorongoro"; String facilityType = "Lvl3 Hospital"; String operatedBy = "MoH"; String facilityCodePrefix = "FCcode"; String facilityNamePrefix = "FCname"; String catchmentPopulationValue = "100"; String date_time = createFacilityPage.enterValuesInFacilityAndClickSave(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy, catchmentPopulationValue); createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created"); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + facilityCodePrefix + date_time + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + facilityNamePrefix + date_time + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"type\":\"" + facilityType + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"description\":\"Testing description\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"9711231305\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"fax\":\"9711231305\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address1\":\"Address1\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address2\":\"Address2\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"" + geoZone + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"catchmentPopulation\":" + catchmentPopulationValue + "")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"latitude\":-555.5555")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"longitude\":444.4444")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"altitude\":4545.4545")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"" + operatedBy + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageGrossCapacity\":3434.3434")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageNetCapacity\":3535.3535")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"suppliesOthers\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":true")); - assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\":1377369000000")); - assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goDownDate\":1377455400000")); + assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\":1380047400000")); + assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goDownDate\":1380133800000")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":false")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"comments\":\"Comments\"")); // assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"modifiedDate\"")); DeleteFacilityPage deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); deleteFacilityPage.disableFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time); deleteFacilityPage.verifyDisabledFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time); deleteFacilityPage.enableFacility(); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"online\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"gln\":\"Testing Gln\"")); // assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"type\":\"" + facilityType + "\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"operatedBy\":\"" + operatedBy + "\"")); // assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"active\":true")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"type\":\"" + facilityType + "\"")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"operatedBy\":\"" + operatedBy + "\"")); // assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"modifiedDate\"")); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.addProgram("VACCINES", true); createFacilityPage.saveFacility(); Thread.sleep(5000); assertEquals(feedJSONList.size(), 3); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.removeFirstProgram(); createFacilityPage.saveFacility(); Thread.sleep(5000); assertEquals(feedJSONList.size(), 3); homePage.logout(baseUrlGlobal); } @Test(groups = {"webservice"}, dataProvider = "Data-Provider-Function-Positive") public void shouldVerifyFacilityFeedForFacilityUpload(String user, String program, String[] credentials) throws Exception { HttpClient client = new HttpClient(); client.createContext(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); String geoZone = "virtualgeozone"; String facilityType = "Lvl3 Hospital"; String operatedBy = "MoH"; String facilityCodePrefix = "facilityf10"; String parentFacilityCode = "F10"; String facilityNamePrefix = "facilityf10 Village Dispensary"; String facilityCodeUpdatedPrefix = "facilityf11"; String facilityNameUpdatedPrefix = "facilityf11 Village Dispensary"; String catchmentPopulationValue = "100"; String catchmentPopulationUpdatedValue = "9999999"; HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); UploadPage uploadPage = homePage.navigateUploads(); uploadPage.uploadAndVerifyGeographicZone("QA_Geographic_Data_WebService.csv"); uploadPage.verifySuccessMessageOnUploadScreen(); uploadPage.uploadFacilities("QA_facilities_WebService.csv"); uploadPage.verifySuccessMessageOnUploadScreen(); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + facilityCodePrefix + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + facilityNamePrefix + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"type\":\"" + facilityType + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"description\":\"IT department\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"9711231305\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"fax\":\"9711231305\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address1\":\"Address1\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address2\":\"Address2\",")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"" + geoZone + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"catchmentPopulation\":" + catchmentPopulationValue + "")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"latitude\":-555.5555")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"longitude\":444.4444")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"altitude\":4545.4545")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"" + operatedBy + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageGrossCapacity\":3434.3434")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageNetCapacity\":3535.3535")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"suppliesOthers\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\":1352572200000")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goDownDate\":-2592106200000")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"satelliteFacility\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":false")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"comments\":\"fc\"")); // assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"modifiedDate\"")); uploadPage.uploadFacilities("QA_facilities_Subsequent_WebService.csv"); uploadPage.verifySuccessMessageOnUploadScreen(); ResponseEntity responseEntityUpdated = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content"); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"code\":\"" + facilityCodeUpdatedPrefix + "\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"name\":\"" + facilityNameUpdatedPrefix + "\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"catchmentPopulation\":" + catchmentPopulationUpdatedValue)); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"sdp\":true")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"online\":true")); // assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"parentFacility\":\"" + parentFacilityCode + "\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"gln\":\"G7645\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true")); // assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"modifiedDate\"")); homePage.logout(baseUrlGlobal); } @Test(groups = {"webservice"}) public void testFacilityFeedUsingCommTrack() throws Exception { HttpClient client = new HttpClient(); client.createContext(); Agent agentJson = readObjectFromFile(FULL_JSON_TXT_FILE_NAME, Agent.class); agentJson.setAgentCode(DEFAULT_AGENT_CODE); agentJson.setAgentName(DEFAULT_AGENT_NAME); agentJson.setParentFacilityCode(DEFAULT_PARENT_FACILITY_CODE); agentJson.setPhoneNumber(PHONE_NUMBER); agentJson.setActive(ACTIVE_STATUS); client.SendJSON(getJsonStringFor(agentJson), CREATE_URL, POST, commTrackUser, dbWrapper.getAuthToken(commTrackUser)); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + DEFAULT_AGENT_CODE + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + DEFAULT_AGENT_NAME + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"type\":\"Lvl3 Hospital\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"" + PHONE_NUMBER + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"Ngorongoro\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"NGO\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":" + ACTIVE_STATUS + "")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"parentFacility\":\"" + DEFAULT_PARENT_FACILITY_CODE + "\"")); // assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"modifiedDate\"")); assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityIsOnline\":")); assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":")); assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":")); assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":")); assertFalse("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"satelliteFacility\":")); agentJson.setActive("false"); client.SendJSON(getJsonStringFor(agentJson), UPDATE_URL + DEFAULT_AGENT_CODE + JSON_EXTENSION, PUT, commTrackUser, dbWrapper.getAuthToken(commTrackUser)); ResponseEntity responseEntityUpdated = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); assertTrue("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"active\":false")); // assertTrue("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"modifiedDate\"")); assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"facilityIsOnline\":")); assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"hasElectricity\":")); assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"hasElectronicSCC\":")); assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"hasElectronicDAR\":")); assertFalse("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"satelliteFacility\":")); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content"); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true")); // assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true")); // assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"modifiedDate\"")); } @Test(groups = {"webservice"}) public void testFacilityFeedUsingCommTrackUsingOpenLmisVendor() throws Exception { HttpClient client = new HttpClient(); client.createContext(); Agent agentJson = readObjectFromFile(FULL_JSON_TXT_FILE_NAME, Agent.class); agentJson.setAgentCode(DEFAULT_AGENT_CODE); agentJson.setAgentName(DEFAULT_AGENT_NAME); agentJson.setParentFacilityCode(DEFAULT_PARENT_FACILITY_CODE); agentJson.setPhoneNumber(PHONE_NUMBER); agentJson.setActive(ACTIVE_STATUS); client.SendJSON(getJsonStringFor(agentJson), CREATE_URL, POST, commTrackUser, dbWrapper.getAuthToken(commTrackUser)); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent?vendor=openlmis", "GET", "", ""); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + DEFAULT_AGENT_CODE + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + DEFAULT_AGENT_NAME + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"type\":\"Lvl3 Hospital\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"" + PHONE_NUMBER + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"Ngorongoro\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"NGO\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":" + ACTIVE_STATUS + "")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"parentFacility\":\"" + DEFAULT_PARENT_FACILITY_CODE + "\"")); // assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"modifiedDate\"")); agentJson.setActive("false"); client.SendJSON(getJsonStringFor(agentJson), UPDATE_URL + DEFAULT_AGENT_CODE + JSON_EXTENSION, PUT, commTrackUser, dbWrapper.getAuthToken(commTrackUser)); ResponseEntity responseEntityUpdated = client.SendJSON("", "http://localhost:9091/feeds/facility/recent?vendor=openlmis", "GET", "", ""); assertTrue("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"active\":false")); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content"); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true")); // assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true")); // assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"modifiedDate\"")); } @Test(groups = {"webservice"}) public void testFacilityFeedUsingCommTrackUsingInvalidVendor() throws Exception { HttpClient client = new HttpClient(); client.createContext(); Agent agentJson = readObjectFromFile(FULL_JSON_TXT_FILE_NAME, Agent.class); agentJson.setAgentCode(DEFAULT_AGENT_CODE); agentJson.setAgentName(DEFAULT_AGENT_NAME); agentJson.setParentFacilityCode(DEFAULT_PARENT_FACILITY_CODE); agentJson.setPhoneNumber(PHONE_NUMBER); agentJson.setActive(ACTIVE_STATUS); client.SendJSON(getJsonStringFor(agentJson), CREATE_URL, POST, commTrackUser, dbWrapper.getAuthToken(commTrackUser)); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent?vendor=testing", "GET", "", ""); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + DEFAULT_AGENT_CODE + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + DEFAULT_AGENT_NAME + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"type\":\"Lvl3 Hospital\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"" + PHONE_NUMBER + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"Ngorongoro\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"NGO\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":" + ACTIVE_STATUS + "")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"parentFacility\":\"" + DEFAULT_PARENT_FACILITY_CODE + "\"")); // assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"modifiedDate\"")); agentJson.setActive("false"); client.SendJSON(getJsonStringFor(agentJson), UPDATE_URL + DEFAULT_AGENT_CODE + JSON_EXTENSION, PUT, commTrackUser, dbWrapper.getAuthToken(commTrackUser)); ResponseEntity responseEntityUpdated = client.SendJSON("", "http://localhost:9091/feeds/facility/recent?vendor=testing", "GET", "", ""); assertTrue("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"active\":false")); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content"); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true")); // assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true")); // assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"modifiedDate\"")); } @Test(groups = {"webservice"}) public void testFacilityFeedForCommTrackVendorSpecificInfo() throws Exception { HttpClient client = new HttpClient(); client.createContext(); Agent agentJson = readObjectFromFile(FULL_JSON_TXT_FILE_NAME, Agent.class); agentJson.setAgentCode(DEFAULT_AGENT_CODE); agentJson.setAgentName(DEFAULT_AGENT_NAME); agentJson.setParentFacilityCode(DEFAULT_PARENT_FACILITY_CODE); agentJson.setPhoneNumber(PHONE_NUMBER); agentJson.setActive(ACTIVE_STATUS); client.SendJSON(getJsonStringFor(agentJson), CREATE_URL, POST, commTrackUser, dbWrapper.getAuthToken(commTrackUser)); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent?vendor=commtrack", "GET", "", ""); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityCode\":\"" + DEFAULT_AGENT_CODE + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityName\":\"" + DEFAULT_AGENT_NAME + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityType\":\"Lvl3 Hospital\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityMainPhone\":\"" + PHONE_NUMBER + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"Ngorongoro\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityOperatedBy\":\"NGO\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityIsActive\":" + ACTIVE_STATUS + "")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityGoLiveDate\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"facilityIsVirtual\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"SatelliteParent\":\"" + DEFAULT_PARENT_FACILITY_CODE + "\"")); // assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"modifiedDate\"")); agentJson.setActive("false"); client.SendJSON(getJsonStringFor(agentJson), UPDATE_URL + DEFAULT_AGENT_CODE + JSON_EXTENSION, PUT, commTrackUser, dbWrapper.getAuthToken(commTrackUser)); ResponseEntity responseEntityUpdated = client.SendJSON("", "http://localhost:9091/feeds/facility/recent?vendor=commtrack", "GET", "", ""); assertTrue("Response entity : " + responseEntityUpdated.getResponse(), responseEntityUpdated.getResponse().contains("\"facilityIsActive\":false")); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntityUpdated.getResponse(), "content"); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"facilityIsActive\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"facilityIsSDP\":true")); // assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"facilityIsActive\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":true")); // assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"modifiedDate\"")); } @DataProvider(name = "Data-Provider-Function-Positive") public Object[][] parameterIntTestProviderPositive() { return new Object[][]{ {"User123", "HIV", new String[]{"Admin123", "Admin123"}} }; } }
true
true
public void testFacilityFeedUsingUI(String user, String program, String[] credentials) throws Exception { HttpClient client = new HttpClient(); client.createContext(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); dbWrapper.insertUser("200", user, "Ag/myf1Whs0fxr1FFfK8cs3q/VJ1qMs3yuMLDTeEcZEGzstj/waaUsQNQTIKk1U5JRzrDbPLCzCO1/vB5YGaEQ==", "F10", "[email protected]", "openLmis"); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility(); String geoZone = "Ngorongoro"; String facilityType = "Lvl3 Hospital"; String operatedBy = "MoH"; String facilityCodePrefix = "FCcode"; String facilityNamePrefix = "FCname"; String catchmentPopulationValue = "100"; String date_time = createFacilityPage.enterValuesInFacilityAndClickSave(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy, catchmentPopulationValue); createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created"); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + facilityCodePrefix + date_time + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + facilityNamePrefix + date_time + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"type\":\"" + facilityType + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"description\":\"Testing description\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"9711231305\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"fax\":\"9711231305\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address1\":\"Address1\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address2\":\"Address2\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"" + geoZone + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"catchmentPopulation\":" + catchmentPopulationValue + "")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"latitude\":-555.5555")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"longitude\":444.4444")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"altitude\":4545.4545")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"" + operatedBy + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageGrossCapacity\":3434.3434")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageNetCapacity\":3535.3535")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"suppliesOthers\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\":1377369000000")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goDownDate\":1377455400000")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":false")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"comments\":\"Comments\"")); // assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"modifiedDate\"")); DeleteFacilityPage deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); deleteFacilityPage.disableFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time); deleteFacilityPage.verifyDisabledFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time); deleteFacilityPage.enableFacility(); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"online\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"gln\":\"Testing Gln\"")); // assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"type\":\"" + facilityType + "\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"operatedBy\":\"" + operatedBy + "\"")); // assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"active\":true")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"type\":\"" + facilityType + "\"")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"operatedBy\":\"" + operatedBy + "\"")); // assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"modifiedDate\"")); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.addProgram("VACCINES", true); createFacilityPage.saveFacility(); Thread.sleep(5000); assertEquals(feedJSONList.size(), 3); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.removeFirstProgram(); createFacilityPage.saveFacility(); Thread.sleep(5000); assertEquals(feedJSONList.size(), 3); homePage.logout(baseUrlGlobal); }
public void testFacilityFeedUsingUI(String user, String program, String[] credentials) throws Exception { HttpClient client = new HttpClient(); client.createContext(); LoginPage loginPage = new LoginPage(testWebDriver, baseUrlGlobal); dbWrapper.insertUser("200", user, "Ag/myf1Whs0fxr1FFfK8cs3q/VJ1qMs3yuMLDTeEcZEGzstj/waaUsQNQTIKk1U5JRzrDbPLCzCO1/vB5YGaEQ==", "F10", "[email protected]", "openLmis"); HomePage homePage = loginPage.loginAs(credentials[0], credentials[1]); CreateFacilityPage createFacilityPage = homePage.navigateCreateFacility(); String geoZone = "Ngorongoro"; String facilityType = "Lvl3 Hospital"; String operatedBy = "MoH"; String facilityCodePrefix = "FCcode"; String facilityNamePrefix = "FCname"; String catchmentPopulationValue = "100"; String date_time = createFacilityPage.enterValuesInFacilityAndClickSave(facilityCodePrefix, facilityNamePrefix, program, geoZone, facilityType, operatedBy, catchmentPopulationValue); createFacilityPage.verifyMessageOnFacilityScreen(facilityNamePrefix + date_time, "created"); ResponseEntity responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"code\":\"" + facilityCodePrefix + date_time + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"name\":\"" + facilityNamePrefix + date_time + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"type\":\"" + facilityType + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"description\":\"Testing description\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"mainPhone\":\"9711231305\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"fax\":\"9711231305\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address1\":\"Address1\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"address2\":\"Address2\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"geographicZone\":\"" + geoZone + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"catchmentPopulation\":" + catchmentPopulationValue + "")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"latitude\":-555.5555")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"longitude\":444.4444")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"altitude\":4545.4545")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"operatedBy\":\"" + operatedBy + "\"")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageGrossCapacity\":3434.3434")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"coldStorageNetCapacity\":3535.3535")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"suppliesOthers\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectricity\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicSCC\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"hasElectronicDAR\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"active\":true")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goLiveDate\":1380047400000")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"goDownDate\":1380133800000")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"virtualFacility\":false")); assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"comments\":\"Comments\"")); // assertTrue("Response entity : " + responseEntity.getResponse(), responseEntity.getResponse().contains("\"modifiedDate\"")); DeleteFacilityPage deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); deleteFacilityPage.disableFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time); deleteFacilityPage.verifyDisabledFacility(facilityCodePrefix + date_time, facilityNamePrefix + date_time); deleteFacilityPage.enableFacility(); responseEntity = client.SendJSON("", "http://localhost:9091/feeds/facility/recent", "GET", "", ""); List<String> feedJSONList = XmlUtils.getNodeValues(responseEntity.getResponse(), "content"); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"active\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"sdp\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"online\":true")); assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"gln\":\"Testing Gln\"")); // assertTrue("feed json list : " + feedJSONList.get(0), feedJSONList.get(0).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"active\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"enabled\":false")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"type\":\"" + facilityType + "\"")); assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"operatedBy\":\"" + operatedBy + "\"")); // assertTrue("feed json list : " + feedJSONList.get(1), feedJSONList.get(1).contains("\"modifiedDate\"")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"active\":true")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"enabled\":true")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"type\":\"" + facilityType + "\"")); assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"operatedBy\":\"" + operatedBy + "\"")); // assertTrue("feed json list : " + feedJSONList.get(2), feedJSONList.get(2).contains("\"modifiedDate\"")); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.addProgram("VACCINES", true); createFacilityPage.saveFacility(); Thread.sleep(5000); assertEquals(feedJSONList.size(), 3); deleteFacilityPage = homePage.navigateSearchFacility(); deleteFacilityPage.searchFacility(date_time); deleteFacilityPage.clickFacilityList(date_time); createFacilityPage.removeFirstProgram(); createFacilityPage.saveFacility(); Thread.sleep(5000); assertEquals(feedJSONList.size(), 3); homePage.logout(baseUrlGlobal); }
diff --git a/server/mmud/commands/BowCommand.java b/server/mmud/commands/BowCommand.java index 39f6bc60..10026e74 100644 --- a/server/mmud/commands/BowCommand.java +++ b/server/mmud/commands/BowCommand.java @@ -1,78 +1,78 @@ /*------------------------------------------------------------------------- cvsinfo: $Header$ Maarten's Mud, WWW-based MUD using MYSQL Copyright (C) 1998 Maarten van Leunen 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Maarten van Leunen Appelhof 27 5345 KA Oss Nederland Europe [email protected] -------------------------------------------------------------------------*/ package mmud.commands; import java.util.logging.Logger; import mmud.*; import mmud.characters.*; import mmud.items.*; import mmud.rooms.*; import mmud.database.*; /** * Bow : "bow". */ public class BowCommand extends NormalCommand { public BowCommand(String aRegExpr) { super(aRegExpr); } public boolean run(User aUser) throws MudException { Logger.getLogger("mmud").finer(""); if (!super.run(aUser)) { return false; } String command = getCommand(); String[] myParsed = getParsedCommand(); if (myParsed.length > 2 && myParsed[1].equalsIgnoreCase("to")) { Person toChar = Persons.retrievePerson(myParsed[2]); if ((toChar == null) || (!toChar.getRoom().equals(aUser.getRoom()))) { aUser.writeMessage("Cannot find that person.<BR>\r\n"); } else { - Persons.sendMessage(aUser, toChar, "%SNAME bow%VERB to %TNAME.<BR>\r\n"); + Persons.sendMessage(aUser, toChar, "%SNAME bow%VERB1 to %TNAME.<BR>\r\n"); } } else { Persons.sendMessage(aUser, "%SNAME bow%VERB2.<BR>\r\n"); } return true; } }
true
true
public boolean run(User aUser) throws MudException { Logger.getLogger("mmud").finer(""); if (!super.run(aUser)) { return false; } String command = getCommand(); String[] myParsed = getParsedCommand(); if (myParsed.length > 2 && myParsed[1].equalsIgnoreCase("to")) { Person toChar = Persons.retrievePerson(myParsed[2]); if ((toChar == null) || (!toChar.getRoom().equals(aUser.getRoom()))) { aUser.writeMessage("Cannot find that person.<BR>\r\n"); } else { Persons.sendMessage(aUser, toChar, "%SNAME bow%VERB to %TNAME.<BR>\r\n"); } } else { Persons.sendMessage(aUser, "%SNAME bow%VERB2.<BR>\r\n"); } return true; }
public boolean run(User aUser) throws MudException { Logger.getLogger("mmud").finer(""); if (!super.run(aUser)) { return false; } String command = getCommand(); String[] myParsed = getParsedCommand(); if (myParsed.length > 2 && myParsed[1].equalsIgnoreCase("to")) { Person toChar = Persons.retrievePerson(myParsed[2]); if ((toChar == null) || (!toChar.getRoom().equals(aUser.getRoom()))) { aUser.writeMessage("Cannot find that person.<BR>\r\n"); } else { Persons.sendMessage(aUser, toChar, "%SNAME bow%VERB1 to %TNAME.<BR>\r\n"); } } else { Persons.sendMessage(aUser, "%SNAME bow%VERB2.<BR>\r\n"); } return true; }
diff --git a/service/src/main/java/com/pms/service/annotation/InitBean.java b/service/src/main/java/com/pms/service/annotation/InitBean.java index 7104c88f..51f10c71 100644 --- a/service/src/main/java/com/pms/service/annotation/InitBean.java +++ b/service/src/main/java/com/pms/service/annotation/InitBean.java @@ -1,277 +1,278 @@ package com.pms.service.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; 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 org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; import org.springframework.core.type.filter.AnnotationTypeFilter; import org.springframework.web.bind.annotation.RequestMapping; import com.pms.service.PackageRole; import com.pms.service.cfg.ConfigurationManager; import com.pms.service.dao.ICommonDao; import com.pms.service.dbhelper.DBQuery; import com.pms.service.dbhelper.DBQueryOpertion; import com.pms.service.mockbean.ApiConstants; import com.pms.service.mockbean.DBBean; import com.pms.service.mockbean.GroupBean; import com.pms.service.mockbean.RoleBean; import com.pms.service.mockbean.UserBean; import com.pms.service.util.DataEncrypt; public class InitBean { public static final Set<String> loginPath = new HashSet<String>(); public static final Map<String, String> rolesValidationMap = new HashMap<String, String>(); private static final Logger logger = LogManager.getLogger(InitBean.class); public static final String ADMIN_USER_NAME = "admin"; /** * 初始化数据库 * * @param dao * @throws SecurityException * @throws ClassNotFoundException */ public static void initUserRoleDB(ICommonDao dao) throws SecurityException, ClassNotFoundException { initRoleItems(dao); setLoginPathValidation(); createAdminGroup(dao); createSystemDefaultGroups(dao); createAdminUser(dao); } private static void createSystemDefaultGroups(ICommonDao dao) { String[] groupNames = new String[] { GroupBean.PROJECT_MANAGER_VALUE, GroupBean.PROJECT_ASSISTANT_VALUE, GroupBean.SALES_ASSISTANT_VALUE, GroupBean.PM, GroupBean.FINANCE, GroupBean.SALES_MANAGER_VALUE, GroupBean.COO_VALUE, GroupBean.DEPOT_MANAGER_VALUE, GroupBean.PURCHASE_VALUE }; Map<String, String[]> groupRoles = new HashMap<String, String[]>(); groupRoles.put(GroupBean.PROJECT_MANAGER_VALUE, new String[] { RoleValidConstants.PAY_INVOICE_MANAGER_PROCESS, RoleValidConstants.PURCHASE_REQUEST_PROCESS, RoleValidConstants.PURCHASE_CONTRACT_PROCESS }); groupRoles.put(GroupBean.PROJECT_ASSISTANT_VALUE, new String[] { RoleValidConstants.PROJECT_UPDATE, RoleValidConstants.SALES_CONTRACT_UPDATE, RoleValidConstants.PURCHASE_ALLOCATE_MANAGEMENT, RoleValidConstants.PURCHASE_REQUEST_MANAGEMENT }); groupRoles.put(GroupBean.SALES_ASSISTANT_VALUE, new String[] { RoleValidConstants.PROJECT_ADD, RoleValidConstants.PROJECT_UPDATE, RoleValidConstants.SALES_CONTRACT_ADD, RoleValidConstants.SALES_CONTRACT_UPDATE, RoleValidConstants.PURCHASE_ALLOCATE_MANAGEMENT, RoleValidConstants.PURCHASE_REQUEST_MANAGEMENT }); groupRoles.put(GroupBean.PM, new String[] { RoleValidConstants.SHIP_MANAGEMENT, RoleValidConstants.BORROWING_MANAGEMENT, RoleValidConstants.PAY_INVOICE_ADD, RoleValidConstants.PURCHASE_BACK_MANAGEMENT }); groupRoles.put(GroupBean.FINANCE, new String[] { RoleValidConstants.PAY_INVOICE_FIN_PROCESS, - RoleValidConstants.PAY_INVOICE_DONE + RoleValidConstants.PAY_INVOICE_DONE, + RoleValidConstants.FINANCE_MANAGEMENT }); groupRoles.put(GroupBean.SALES_MANAGER_VALUE, new String[] { RoleValidConstants.PAY_INVOICE_MANAGER_PROCESS, RoleValidConstants.PURCHASE_REQUEST_PROCESS, RoleValidConstants.PURCHASE_CONTRACT_PROCESS }); groupRoles.put(GroupBean.DEPOT_MANAGER_VALUE, new String[] { RoleValidConstants.SHIP_MANAGEMENT_PROCESS, RoleValidConstants.BORROWING_MANAGEMENT_PROCESS, RoleValidConstants.PURCHASE_ALLOCATE_PROCESS, RoleValidConstants.REPOSITORY_MANAGEMENT_PROCESS }); groupRoles.put(GroupBean.PURCHASE_VALUE, new String[] { RoleValidConstants.PURCHASE_CONTRACT_MANAGEMENT, RoleValidConstants.PURCHASE_ORDER_MANAGEMENT, RoleValidConstants.PURCHASE_ORDER_PROCESS, RoleValidConstants.REPOSITORY_MANAGEMENT, RoleValidConstants.PURCHASE_REQUEST_PROCESS }); for (String name : groupNames) { Map<String, Object> newGroup = new HashMap<String, Object>(); newGroup.put(GroupBean.GROUP_NAME, name); // 查找是否角色已经初始化 Map<String, Object> group = dao.findOne(GroupBean.GROUP_NAME, name, DBBean.USER_GROUP); Map<String, Object> roleQuery = new HashMap<String, Object>(); roleQuery.put(RoleBean.ROLE_ID, new DBQuery(DBQueryOpertion.IN, groupRoles.get(name))); roleQuery.put(ApiConstants.LIMIT_KEYS, ApiConstants.MONGO_ID); List<Object> roles = dao.listLimitKeyValues(roleQuery, DBBean.ROLE_ITEM); if (group == null) { // 系统角色不允许删除 newGroup.put(GroupBean.IS_SYSTEM_GROUP, true); newGroup.put(GroupBean.ROLES, roles); dao.add(newGroup, DBBean.USER_GROUP); } else { group.put(GroupBean.ROLES, roles); group.put(GroupBean.IS_SYSTEM_GROUP, true); dao.updateById(group, DBBean.USER_GROUP); } } } private static void createAdminGroup(ICommonDao dao) { logger.info("Init admin group"); Map<String, Object> adminGroup = new HashMap<String, Object>(); adminGroup.put(GroupBean.GROUP_NAME, GroupBean.GROUP_ADMIN_VALUE); // 查找是否admin角色已经初始化 Map<String, Object> group = dao.findOne(GroupBean.GROUP_NAME, GroupBean.GROUP_ADMIN_VALUE, DBBean.USER_GROUP); // 查询所有的权限赋值给admin Map<String, Object> roleItemQuery = new HashMap<String, Object>(); roleItemQuery.put(ApiConstants.LIMIT_KEYS, new String[] { ApiConstants.MONGO_ID }); List<Object> list = dao.listLimitKeyValues(roleItemQuery, DBBean.ROLE_ITEM); if (group == null) { adminGroup.put(GroupBean.ROLES, list); dao.add(adminGroup, DBBean.USER_GROUP); } else { group.put(GroupBean.ROLES, list); dao.updateById(group, DBBean.USER_GROUP); } } private static void createAdminUser(ICommonDao dao) { Map<String, Object> adminUser = new HashMap<String, Object>(); adminUser.put(UserBean.USER_NAME, ADMIN_USER_NAME); Map<String, Object> user = dao.findOne(UserBean.USER_NAME, ADMIN_USER_NAME, DBBean.USER); // 查找admin角色的_id Map<String, Object> groupQuery = new HashMap<String, Object>(); groupQuery.put(GroupBean.GROUP_NAME, GroupBean.GROUP_ADMIN_VALUE); groupQuery.put(ApiConstants.LIMIT_KEYS, new String[] { ApiConstants.MONGO_ID }); List<Object> list = dao.listLimitKeyValues(groupQuery, DBBean.USER_GROUP); if (user == null) { adminUser.put(UserBean.GROUPS, list); adminUser.put(UserBean.PASSWORD, DataEncrypt.generatePassword("123456")); dao.add(adminUser, DBBean.USER); } else { user.put(UserBean.GROUPS, list); dao.updateById(user, DBBean.USER); } } /** * 初始化那些path需要登录验证,数据放到内存中 * * * @throws ClassNotFoundException */ private static void setLoginPathValidation() throws ClassNotFoundException { ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.resetFilters(true); scanner.addIncludeFilter(new AnnotationTypeFilter(LoginRequired.class)); for (BeanDefinition bd : scanner.findCandidateComponents(PackageRole.class.getPackage().getName())) { Class<?> classzz = Class.forName(bd.getBeanClassName()); Method metods[] = classzz.getMethods(); RequestMapping parent = classzz.getAnnotation(RequestMapping.class); String path = ""; if (parent != null) { path = parent.value()[0]; } for (Method m : metods) { LoginRequired rv = m.getAnnotation(LoginRequired.class); if (rv != null) { RequestMapping mapping = m.getAnnotation(RequestMapping.class); if (mapping != null) { loginPath.add(path + mapping.value()[0]); } } } } } /** * * 出事化权限表,权限来至于 @RoleValidate * * @param dao * @throws ClassNotFoundException */ private static void initRoleItems(ICommonDao dao) throws ClassNotFoundException { ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); scanner.addIncludeFilter(new AnnotationTypeFilter(RoleValidate.class)); List<String> roleIds = new ArrayList<String>(); // FIXME: 删除不存在的role,但是也需要删除group, user中相关联的数据 for (BeanDefinition bd : scanner.findCandidateComponents(PackageRole.class.getPackage().getName())) { Class<?> classzz = Class.forName(bd.getBeanClassName()); Method metods[] = classzz.getMethods(); RequestMapping parent = classzz.getAnnotation(RequestMapping.class); String path = ""; if (parent != null) { path = parent.value()[0]; } for (Method m : metods) { Annotation annotations[] = m.getAnnotations(); for (Annotation anno : annotations) { if (anno instanceof RoleValidate) { RoleValidate rv = (RoleValidate) anno; RequestMapping mapping = m.getAnnotation(RequestMapping.class); if (!roleIds.contains(rv.roleID())) { roleIds.add(rv.roleID()); } @SuppressWarnings("unchecked") Map<String, Object> role = dao.findOne(RoleBean.ROLE_ID, rv.roleID(), DBBean.ROLE_ITEM); if (role != null) { role.put(RoleBean.ROLE_DESC, rv.desc()); dao.updateById(role, DBBean.ROLE_ITEM); } else { Map<String, Object> roleMap = new HashMap<String, Object>(); roleMap.put(RoleBean.ROLE_ID, rv.roleID()); roleMap.put(RoleBean.ROLE_DESC, rv.desc()); dao.add(roleMap, DBBean.ROLE_ITEM); } String validPath = path + mapping.value()[0]; if (rolesValidationMap.get(validPath) != null) { rolesValidationMap.put(validPath, rv.roleID() + "," + rolesValidationMap.get(validPath)); } else { rolesValidationMap.put(validPath, rv.roleID()); } } } } } } }
true
true
private static void createSystemDefaultGroups(ICommonDao dao) { String[] groupNames = new String[] { GroupBean.PROJECT_MANAGER_VALUE, GroupBean.PROJECT_ASSISTANT_VALUE, GroupBean.SALES_ASSISTANT_VALUE, GroupBean.PM, GroupBean.FINANCE, GroupBean.SALES_MANAGER_VALUE, GroupBean.COO_VALUE, GroupBean.DEPOT_MANAGER_VALUE, GroupBean.PURCHASE_VALUE }; Map<String, String[]> groupRoles = new HashMap<String, String[]>(); groupRoles.put(GroupBean.PROJECT_MANAGER_VALUE, new String[] { RoleValidConstants.PAY_INVOICE_MANAGER_PROCESS, RoleValidConstants.PURCHASE_REQUEST_PROCESS, RoleValidConstants.PURCHASE_CONTRACT_PROCESS }); groupRoles.put(GroupBean.PROJECT_ASSISTANT_VALUE, new String[] { RoleValidConstants.PROJECT_UPDATE, RoleValidConstants.SALES_CONTRACT_UPDATE, RoleValidConstants.PURCHASE_ALLOCATE_MANAGEMENT, RoleValidConstants.PURCHASE_REQUEST_MANAGEMENT }); groupRoles.put(GroupBean.SALES_ASSISTANT_VALUE, new String[] { RoleValidConstants.PROJECT_ADD, RoleValidConstants.PROJECT_UPDATE, RoleValidConstants.SALES_CONTRACT_ADD, RoleValidConstants.SALES_CONTRACT_UPDATE, RoleValidConstants.PURCHASE_ALLOCATE_MANAGEMENT, RoleValidConstants.PURCHASE_REQUEST_MANAGEMENT }); groupRoles.put(GroupBean.PM, new String[] { RoleValidConstants.SHIP_MANAGEMENT, RoleValidConstants.BORROWING_MANAGEMENT, RoleValidConstants.PAY_INVOICE_ADD, RoleValidConstants.PURCHASE_BACK_MANAGEMENT }); groupRoles.put(GroupBean.FINANCE, new String[] { RoleValidConstants.PAY_INVOICE_FIN_PROCESS, RoleValidConstants.PAY_INVOICE_DONE }); groupRoles.put(GroupBean.SALES_MANAGER_VALUE, new String[] { RoleValidConstants.PAY_INVOICE_MANAGER_PROCESS, RoleValidConstants.PURCHASE_REQUEST_PROCESS, RoleValidConstants.PURCHASE_CONTRACT_PROCESS }); groupRoles.put(GroupBean.DEPOT_MANAGER_VALUE, new String[] { RoleValidConstants.SHIP_MANAGEMENT_PROCESS, RoleValidConstants.BORROWING_MANAGEMENT_PROCESS, RoleValidConstants.PURCHASE_ALLOCATE_PROCESS, RoleValidConstants.REPOSITORY_MANAGEMENT_PROCESS }); groupRoles.put(GroupBean.PURCHASE_VALUE, new String[] { RoleValidConstants.PURCHASE_CONTRACT_MANAGEMENT, RoleValidConstants.PURCHASE_ORDER_MANAGEMENT, RoleValidConstants.PURCHASE_ORDER_PROCESS, RoleValidConstants.REPOSITORY_MANAGEMENT, RoleValidConstants.PURCHASE_REQUEST_PROCESS }); for (String name : groupNames) { Map<String, Object> newGroup = new HashMap<String, Object>(); newGroup.put(GroupBean.GROUP_NAME, name); // 查找是否角色已经初始化 Map<String, Object> group = dao.findOne(GroupBean.GROUP_NAME, name, DBBean.USER_GROUP); Map<String, Object> roleQuery = new HashMap<String, Object>(); roleQuery.put(RoleBean.ROLE_ID, new DBQuery(DBQueryOpertion.IN, groupRoles.get(name))); roleQuery.put(ApiConstants.LIMIT_KEYS, ApiConstants.MONGO_ID); List<Object> roles = dao.listLimitKeyValues(roleQuery, DBBean.ROLE_ITEM); if (group == null) { // 系统角色不允许删除 newGroup.put(GroupBean.IS_SYSTEM_GROUP, true); newGroup.put(GroupBean.ROLES, roles); dao.add(newGroup, DBBean.USER_GROUP); } else { group.put(GroupBean.ROLES, roles); group.put(GroupBean.IS_SYSTEM_GROUP, true); dao.updateById(group, DBBean.USER_GROUP); } } }
private static void createSystemDefaultGroups(ICommonDao dao) { String[] groupNames = new String[] { GroupBean.PROJECT_MANAGER_VALUE, GroupBean.PROJECT_ASSISTANT_VALUE, GroupBean.SALES_ASSISTANT_VALUE, GroupBean.PM, GroupBean.FINANCE, GroupBean.SALES_MANAGER_VALUE, GroupBean.COO_VALUE, GroupBean.DEPOT_MANAGER_VALUE, GroupBean.PURCHASE_VALUE }; Map<String, String[]> groupRoles = new HashMap<String, String[]>(); groupRoles.put(GroupBean.PROJECT_MANAGER_VALUE, new String[] { RoleValidConstants.PAY_INVOICE_MANAGER_PROCESS, RoleValidConstants.PURCHASE_REQUEST_PROCESS, RoleValidConstants.PURCHASE_CONTRACT_PROCESS }); groupRoles.put(GroupBean.PROJECT_ASSISTANT_VALUE, new String[] { RoleValidConstants.PROJECT_UPDATE, RoleValidConstants.SALES_CONTRACT_UPDATE, RoleValidConstants.PURCHASE_ALLOCATE_MANAGEMENT, RoleValidConstants.PURCHASE_REQUEST_MANAGEMENT }); groupRoles.put(GroupBean.SALES_ASSISTANT_VALUE, new String[] { RoleValidConstants.PROJECT_ADD, RoleValidConstants.PROJECT_UPDATE, RoleValidConstants.SALES_CONTRACT_ADD, RoleValidConstants.SALES_CONTRACT_UPDATE, RoleValidConstants.PURCHASE_ALLOCATE_MANAGEMENT, RoleValidConstants.PURCHASE_REQUEST_MANAGEMENT }); groupRoles.put(GroupBean.PM, new String[] { RoleValidConstants.SHIP_MANAGEMENT, RoleValidConstants.BORROWING_MANAGEMENT, RoleValidConstants.PAY_INVOICE_ADD, RoleValidConstants.PURCHASE_BACK_MANAGEMENT }); groupRoles.put(GroupBean.FINANCE, new String[] { RoleValidConstants.PAY_INVOICE_FIN_PROCESS, RoleValidConstants.PAY_INVOICE_DONE, RoleValidConstants.FINANCE_MANAGEMENT }); groupRoles.put(GroupBean.SALES_MANAGER_VALUE, new String[] { RoleValidConstants.PAY_INVOICE_MANAGER_PROCESS, RoleValidConstants.PURCHASE_REQUEST_PROCESS, RoleValidConstants.PURCHASE_CONTRACT_PROCESS }); groupRoles.put(GroupBean.DEPOT_MANAGER_VALUE, new String[] { RoleValidConstants.SHIP_MANAGEMENT_PROCESS, RoleValidConstants.BORROWING_MANAGEMENT_PROCESS, RoleValidConstants.PURCHASE_ALLOCATE_PROCESS, RoleValidConstants.REPOSITORY_MANAGEMENT_PROCESS }); groupRoles.put(GroupBean.PURCHASE_VALUE, new String[] { RoleValidConstants.PURCHASE_CONTRACT_MANAGEMENT, RoleValidConstants.PURCHASE_ORDER_MANAGEMENT, RoleValidConstants.PURCHASE_ORDER_PROCESS, RoleValidConstants.REPOSITORY_MANAGEMENT, RoleValidConstants.PURCHASE_REQUEST_PROCESS }); for (String name : groupNames) { Map<String, Object> newGroup = new HashMap<String, Object>(); newGroup.put(GroupBean.GROUP_NAME, name); // 查找是否角色已经初始化 Map<String, Object> group = dao.findOne(GroupBean.GROUP_NAME, name, DBBean.USER_GROUP); Map<String, Object> roleQuery = new HashMap<String, Object>(); roleQuery.put(RoleBean.ROLE_ID, new DBQuery(DBQueryOpertion.IN, groupRoles.get(name))); roleQuery.put(ApiConstants.LIMIT_KEYS, ApiConstants.MONGO_ID); List<Object> roles = dao.listLimitKeyValues(roleQuery, DBBean.ROLE_ITEM); if (group == null) { // 系统角色不允许删除 newGroup.put(GroupBean.IS_SYSTEM_GROUP, true); newGroup.put(GroupBean.ROLES, roles); dao.add(newGroup, DBBean.USER_GROUP); } else { group.put(GroupBean.ROLES, roles); group.put(GroupBean.IS_SYSTEM_GROUP, true); dao.updateById(group, DBBean.USER_GROUP); } } }
diff --git a/src/de/caluga/morphium/Morphium.java b/src/de/caluga/morphium/Morphium.java index 6197034b..63d8357a 100644 --- a/src/de/caluga/morphium/Morphium.java +++ b/src/de/caluga/morphium/Morphium.java @@ -1,2000 +1,2000 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.caluga.morphium; import com.mongodb.*; import de.caluga.morphium.aggregation.Aggregator; import de.caluga.morphium.annotations.*; import de.caluga.morphium.annotations.caching.Cache; import de.caluga.morphium.annotations.caching.NoCache; import de.caluga.morphium.annotations.lifecycle.*; import de.caluga.morphium.annotations.security.NoProtection; import de.caluga.morphium.cache.CacheElement; import de.caluga.morphium.cache.CacheHousekeeper; import de.caluga.morphium.query.MongoField; import de.caluga.morphium.query.Query; import de.caluga.morphium.replicaset.ConfNode; import de.caluga.morphium.replicaset.ReplicaSetConf; import de.caluga.morphium.replicaset.ReplicaSetNode; import de.caluga.morphium.secure.MongoSecurityException; import de.caluga.morphium.secure.MongoSecurityManager; import de.caluga.morphium.secure.Permission; import de.caluga.morphium.validation.JavaxValidationStorageListener; import net.sf.cglib.proxy.Enhancer; import org.apache.log4j.Logger; import org.bson.types.ObjectId; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * This is the single access point for accessing MongoDB. This should * * @author stephan */ public final class Morphium { /** * singleton is usually not a good idea in j2ee-Context, but as we did it on * several places in the Application it's the easiest way Usage: * <code> * MorphiumConfig cfg=new MorphiumConfig("testdb",false,false,10,5000,2500); * cfg.addAddress("localhost",27017); * Morphium.config=cfg; * Morphium l=Morphium.get(); * if (l==null) { * System.out.println("Error establishing connection!"); * System.exit(1); * } * </code> * * @see MorphiumConfig */ private final static Logger logger = Logger.getLogger(Morphium.class); private MorphiumConfig config; private Mongo mongo; private DB database; private ThreadPoolExecutor writers = new ThreadPoolExecutor(10, 50, 10000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); //Cache by Type, query String -> CacheElement (contains list etc) private Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cache; private Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idCache; private final Map<StatisticKeys, StatisticValue> stats; private Map<Class<?>, Map<Class<? extends Annotation>, Method>> lifeCycleMethods; /** * String Representing current user - needs to be set by Application */ private String currentUser; private CacheHousekeeper cacheHousekeeper; private List<MorphiumStorageListener> listeners; private Vector<ProfilingListener> profilingListeners; private Vector<Thread> privileged; private Vector<ShutdownListener> shutDownListeners; public MorphiumConfig getConfig() { return config; } // private boolean securityEnabled = false; /** * init the MongoDbLayer. Uses Morphium-Configuration Object for Configuration. * Needs to be set before use or RuntimeException is thrown! * all logging is done in INFO level * * @see MorphiumConfig */ public Morphium(MorphiumConfig cfg) { if (cfg == null) { throw new RuntimeException("Please specify configuration!"); } config = cfg; privileged = new Vector<Thread>(); shutDownListeners = new Vector<ShutdownListener>(); listeners = new ArrayList<MorphiumStorageListener>(); profilingListeners = new Vector<ProfilingListener>(); cache = new Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>(); idCache = new Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>>(); stats = new Hashtable<StatisticKeys, StatisticValue>(); lifeCycleMethods = new Hashtable<Class<?>, Map<Class<? extends Annotation>, Method>>(); for (StatisticKeys k : StatisticKeys.values()) { stats.put(k, new StatisticValue()); } //dummyUser.setGroupIds(); MongoOptions o = new MongoOptions(); o.autoConnectRetry = true; o.fsync = true; o.socketTimeout = config.getSocketTimeout(); o.connectTimeout = config.getConnectionTimeout(); o.connectionsPerHost = config.getMaxConnections(); o.socketKeepAlive = config.isSocketKeepAlive(); o.threadsAllowedToBlockForConnectionMultiplier = 5; o.safe = false; writers.setCorePoolSize(config.getMaxConnections() / 2); writers.setMaximumPoolSize(config.getMaxConnections()); if (config.getAdr().isEmpty()) { throw new RuntimeException("Error - no server address specified!"); } switch (config.getMode()) { case REPLICASET: if (config.getAdr().size() < 2) { throw new RuntimeException("at least 2 Server Adresses needed for MongoDB in ReplicaSet Mode!"); } mongo = new Mongo(config.getAdr(), o); break; case PAIRED: throw new RuntimeException("PAIRED Mode not available anymore!!!!"); // if (config.getAdr().size() != 2) { // morphia = null; // dataStore = null; // throw new RuntimeException("2 Server Adresses needed for MongoDB in Paired Mode!"); // } // // morphium = new Mongo(config.getAdr().get(0), config.getAdr().get(1), o); // break; case SINGLE: default: if (config.getAdr().size() > 1) { // Logger.getLogger(Morphium.class.getName()).warning("WARNING: ignoring additional server Adresses only using 1st!"); } mongo = new Mongo(config.getAdr().get(0), o); break; } database = mongo.getDB(config.getDatabase()); if (config.getDefaultReadPreference() != null) { mongo.setReadPreference(config.getDefaultReadPreference().getPref()); } if (config.getMongoLogin() != null) { if (!database.authenticate(config.getMongoLogin(), config.getMongoPassword().toCharArray())) { throw new RuntimeException("Authentication failed!"); } } // int cnt = database.getCollection("system.indexes").find().count(); //test connection if (config.getConfigManager() == null) { config.setConfigManager(new ConfigManagerImpl()); } config.getConfigManager().setMorphium(this); cacheHousekeeper = new CacheHousekeeper(this, 5000, config.getGlobalCacheValidTime()); cacheHousekeeper.start(); config.getConfigManager().startCleanupThread(); if (config.getMapper() == null) { config.setMapper(new ObjectMapperImpl(this)); } else { config.getMapper().setMorphium(this); } if (config.getWriter() == null) { config.setWriter(new WriterImpl()); } config.getWriter().setMorphium(this); // enable/disable javax.validation support if (hasValidationSupport()) { logger.info("Adding javax.validation Support..."); addListener(new JavaxValidationStorageListener()); } logger.info("Initialization successful..."); } /** * Checks if javax.validation is available and enables validation support. * * @return */ private boolean hasValidationSupport() { try { Class c = getClass().getClassLoader().loadClass("javax.validation.ValidatorFactory"); } catch (ClassNotFoundException cnf) { return false; } return true; } public void addListener(MorphiumStorageListener lst) { List<MorphiumStorageListener> newList = new ArrayList<MorphiumStorageListener>(); newList.addAll(listeners); newList.add(lst); listeners = newList; } public void removeListener(MorphiumStorageListener lst) { List<MorphiumStorageListener> newList = new ArrayList<MorphiumStorageListener>(); newList.addAll(listeners); newList.remove(lst); listeners = newList; } public Mongo getMongo() { return mongo; } public DB getDatabase() { return database; } public ConfigManager getConfigManager() { return config.getConfigManager(); } /** * search for objects similar to template concerning all given fields. * If no fields are specified, all NON Null-Fields are taken into account * if specified, field might also be null * * @param template * @param fields * @param <T> * @return */ public <T> List<T> findByTemplate(T template, String... fields) { Class cls = template.getClass(); List<String> flds = new ArrayList<String>(); if (fields.length > 0) { flds.addAll(Arrays.asList(fields)); } else { flds = getFields(cls); } Query<T> q = createQueryFor(cls); for (String f : flds) { try { q.f(f).eq(getValue(template, f)); } catch (Exception e) { logger.error("Could not read field " + f + " of object " + cls.getName()); } } return q.asList(); } public void unset(Object toSet, Enum field) { unset(toSet, field.name()); } public void unset(final Object toSet, final String field) { if (toSet == null) throw new RuntimeException("Cannot update null!"); if (!isAnnotationPresentInHierarchy(toSet.getClass(), NoProtection.class)) { if (accessDenied(toSet.getClass(), Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } firePreUpdateEvent(toSet.getClass(), MorphiumStorageListener.UpdateTypes.UNSET); Cache c = getAnnotationFromHierarchy(toSet.getClass(), Cache.class); if (isAnnotationPresentInHierarchy(toSet.getClass(), NoCache.class) || c == null || !c.writeCache()) { config.getWriter().unset(toSet, field); firePostUpdateEvent(toSet.getClass(), MorphiumStorageListener.UpdateTypes.UNSET); return; } writers.execute(new Runnable() { @Override public void run() { config.getWriter().unset(toSet, field); firePostUpdateEvent(toSet.getClass(), MorphiumStorageListener.UpdateTypes.UNSET); } }); } /** * can be called for autmatic index ensurance. Attention: might cause heavy load on mongo * will be called automatically if a new collection is created * * @param type */ public void ensureIndicesFor(Class type) { if (isAnnotationPresentInHierarchy(type, Index.class)) { //type must be marked as to be indexed List<Annotation> lst = getAllAnnotationsFromHierachy(type, Index.class); for (Annotation a : lst) { Index i = (Index) a; if (i.value().length > 0) { for (String idx : i.value()) { String[] idxStr = idx.replaceAll(" +", "").split(","); ensureIndex(type, idxStr); } } } List<String> flds = config.getMapper().getFields(type, Index.class); if (flds != null && flds.size() > 0) { for (String f : flds) { Index i = config.getMapper().getField(type, f).getAnnotation(Index.class); if (i.decrement()) { ensureIndex(type, "-" + f); } else { ensureIndex(type, f); } } } } } public void clearCacheIfNecessary(Class cls) { Cache c = getAnnotationFromHierarchy(cls, Cache.class); //cls.getAnnotation(Cache.class); if (c != null) { if (c.clearOnWrite()) { clearCachefor(cls); } } } public DBObject simplifyQueryObject(DBObject q) { if (q.keySet().size() == 1 && q.get("$and") != null) { BasicDBObject ret = new BasicDBObject(); BasicDBList lst = (BasicDBList) q.get("$and"); for (Object o : lst) { if (o instanceof DBObject) { ret.putAll(((DBObject) o)); } else if (o instanceof Map) { ret.putAll(((Map) o)); } else { //something we cannot handle return q; } } return ret; } return q; } public void set(Query<?> query, Enum field, Object val) { set(query, field.name(), val); } public void set(Query<?> query, String field, Object val) { set(query, field, val, false, false); } public void setEnum(Query<?> query, Map<Enum, Object> values, boolean insertIfNotExist, boolean multiple) { HashMap<String, Object> toSet = new HashMap<String, Object>(); for (Map.Entry<Enum, Object> est : values.entrySet()) { toSet.put(est.getKey().name(), values.get(est.getValue())); } set(query, toSet, insertIfNotExist, multiple); } public void push(final Query<?> query, final Enum field, final Object value) { push(query, field, value, false, true); } public void pull(Query<?> query, Enum field, Object value) { pull(query, field.name(), value, false, true); } public void push(Query<?> query, String field, Object value) { push(query, field, value, false, true); } public void pull(Query<?> query, String field, Object value) { pull(query, field, value, false, true); } public void push(Query<?> query, Enum field, Object value, boolean insertIfNotExist, boolean multiple) { push(query, field.name(), value, insertIfNotExist, multiple); } public void pull(Query<?> query, Enum field, Object value, boolean insertIfNotExist, boolean multiple) { pull(query, field.name(), value, insertIfNotExist, multiple); } public void pushAll(Query<?> query, Enum field, List<Object> value, boolean insertIfNotExist, boolean multiple) { push(query, field.name(), value, insertIfNotExist, multiple); } public void pullAll(Query<?> query, Enum field, List<Object> value, boolean insertIfNotExist, boolean multiple) { pull(query, field.name(), value, insertIfNotExist, multiple); } public void push(final Query<?> query, final String field, final Object value, final boolean insertIfNotExist, final boolean multiple) { if (query == null || field == null) throw new RuntimeException("Cannot update null!"); if (accessDenied(query.getType(), Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } firePreUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.PUSH); if (!isWriteCached(query.getType())) { config.getWriter().pushPull(true, query, field, value, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.PUSH); return; } writers.execute(new Runnable() { @Override public void run() { config.getWriter().pushPull(true, query, field, value, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.PUSH); } }); } public void pull(final Query<?> query, final String field, final Object value, final boolean insertIfNotExist, final boolean multiple) { if (query == null || field == null) throw new RuntimeException("Cannot update null!"); if (accessDenied(query.getType(), Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } firePreUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.PULL); if (!isWriteCached(query.getType())) { config.getWriter().pushPull(false, query, field, value, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.PULL); return; } writers.execute(new Runnable() { @Override public void run() { config.getWriter().pushPull(false, query, field, value, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.PULL); } }); } public void pushAll(final Query<?> query, final String field, final List<Object> value, final boolean insertIfNotExist, final boolean multiple) { if (query == null || field == null) throw new RuntimeException("Cannot update null!"); if (accessDenied(query.getType(), Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } firePreUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.PUSH); if (!isWriteCached(query.getType())) { config.getWriter().pushPullAll(true, query, field, value, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.PUSH); return; } writers.execute(new Runnable() { @Override public void run() { config.getWriter().pushPullAll(true, query, field, value, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.PUSH); } }); } public void pullAll(Query<?> query, String field, List<Object> value, boolean insertIfNotExist, boolean multiple) { pull(query, field, value, insertIfNotExist, multiple); } /** * will change an entry in mongodb-collection corresponding to given class object * if query is too complex, upsert might not work! * Upsert should consist of single and-queries, which will be used to generate the object to create, unless * it already exists. look at Mongodb-query documentation as well * * @param query - query to specify which objects should be set * @param field - field to set * @param val - value to set * @param insertIfNotExist - insert, if it does not exist (query needs to be simple!) * @param multiple - update several documents, if false, only first hit will be updated */ public void set(Query<?> query, String field, Object val, boolean insertIfNotExist, boolean multiple) { Map<String, Object> map = new HashMap<String, Object>(); map.put(field, val); set(query, map, insertIfNotExist, multiple); } public void set(final Query<?> query, final Map<String, Object> map, final boolean insertIfNotExist, final boolean multiple) { if (query == null) throw new RuntimeException("Cannot update null!"); if (accessDenied(query.getType(), Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } firePreUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.SET); Cache c = getAnnotationFromHierarchy(query.getType(), Cache.class); if (isAnnotationPresentInHierarchy(query.getType(), NoCache.class) || c == null || !c.writeCache()) { config.getWriter().set(query, map, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.SET); return; } writers.execute(new Runnable() { @Override public void run() { config.getWriter().set(query, map, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.SET); } }); } public void dec(Query<?> query, Enum field, int amount, boolean insertIfNotExist, boolean multiple) { dec(query, field.name(), amount, insertIfNotExist, multiple); } public void dec(Query<?> query, String field, int amount, boolean insertIfNotExist, boolean multiple) { inc(query, field, -amount, insertIfNotExist, multiple); } public void dec(Query<?> query, String field, int amount) { inc(query, field, -amount, false, false); } public void dec(Query<?> query, Enum field, int amount) { inc(query, field, -amount, false, false); } public void inc(Query<?> query, String field, int amount) { inc(query, field, amount, false, false); } public void inc(Query<?> query, Enum field, int amount) { inc(query, field, amount, false, false); } public void inc(Query<?> query, Enum field, int amount, boolean insertIfNotExist, boolean multiple) { inc(query, field.name(), amount, insertIfNotExist, multiple); } public void inc(final Query<?> query, final String name, final int amount, final boolean insertIfNotExist, final boolean multiple) { if (query == null) throw new RuntimeException("Cannot update null!"); if (!isAnnotationPresentInHierarchy(query.getType(), NoProtection.class)) { if (accessDenied(query.getType(), Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } firePreUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.INC); Cache c = getAnnotationFromHierarchy(query.getType(), Cache.class); if (isAnnotationPresentInHierarchy(query.getType(), NoCache.class) || c == null || !c.writeCache()) { config.getWriter().inc(query, name, amount, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.INC); return; } writers.execute(new Runnable() { @Override public void run() { config.getWriter().inc(query, name, amount, insertIfNotExist, multiple); firePostUpdateEvent(query.getType(), MorphiumStorageListener.UpdateTypes.INC); } }); } public void set(Object toSet, Enum field, Object value) { set(toSet, field.name(), value); } /** * setting a value in an existing mongo collection entry - no reading necessary. Object is altered in place * db.collection.update({"_id":toSet.id},{$set:{field:value}} * <b>attention</b>: this alteres the given object toSet in a similar way * * @param toSet: object to set the value in (or better - the corresponding entry in mongo) * @param field: the field to change * @param value: the value to set */ public void set(final Object toSet, final String field, final Object value) { if (toSet == null) throw new RuntimeException("Cannot update null!"); if (!isAnnotationPresentInHierarchy(toSet.getClass(), NoProtection.class)) { if (getId(toSet) == null) { if (accessDenied(toSet, Permission.INSERT)) { throw new SecurityException("Insert of new Object denied!"); } } else { if (accessDenied(toSet, Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } } if (getId(toSet) == null) { logger.info("just storing object as it is new..."); store(toSet); return; } firePreUpdateEvent(toSet.getClass(), MorphiumStorageListener.UpdateTypes.SET); Cache c = getAnnotationFromHierarchy(toSet.getClass(), Cache.class); if (isAnnotationPresentInHierarchy(toSet.getClass(), NoCache.class) || c == null || !c.writeCache()) { config.getWriter().set(toSet, field, value); firePostUpdateEvent(toSet.getClass(), MorphiumStorageListener.UpdateTypes.SET); return; } writers.execute(new Runnable() { @Override public void run() { config.getWriter().set(toSet, field, value); firePostUpdateEvent(toSet.getClass(), MorphiumStorageListener.UpdateTypes.SET); } }); } /** * decreasing a value of a given object * calles <code>inc(toDec,field,-amount);</code> */ public void dec(Object toDec, String field, int amount) { inc(toDec, field, -amount); } public void inc(final Object toSet, final String field, final int i) { if (toSet == null) throw new RuntimeException("Cannot update null!"); if (!isAnnotationPresentInHierarchy(toSet.getClass(), NoProtection.class)) { if (getId(toSet) == null) { if (accessDenied(toSet, Permission.INSERT)) { throw new SecurityException("Insert of new Object denied!"); } } else { if (accessDenied(toSet, Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } } if (getId(toSet) == null) { logger.info("just storing object as it is new..."); store(toSet); return; } firePreUpdateEvent(toSet.getClass(), MorphiumStorageListener.UpdateTypes.INC); Cache c = getAnnotationFromHierarchy(toSet.getClass(), Cache.class); if (isAnnotationPresentInHierarchy(toSet.getClass(), NoCache.class) || c == null || !c.writeCache()) { config.getWriter().inc(toSet, field, i); firePostUpdateEvent(toSet.getClass(), MorphiumStorageListener.UpdateTypes.INC); return; } writers.execute(new Runnable() { @Override public void run() { config.getWriter().set(toSet, field, i); firePostUpdateEvent(toSet.getClass(), MorphiumStorageListener.UpdateTypes.INC); } }); } public void setIdCache(Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> c) { idCache = c; } /** * adds some list of objects to the cache manually... * is being used internally, and should be used with care * * @param k - Key, usually the mongodb query string * @param type - class type * @param ret - list of results * @param <T> - Type of record */ public <T extends Object> void addToCache(String k, Class<? extends Object> type, List<T> ret) { if (k == null) { return; } if (ret != null) { //copy from idCache Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idCacheClone = cloneIdCache(); for (T record : ret) { if (idCacheClone.get(type) == null) { idCacheClone.put(type, new Hashtable<ObjectId, Object>()); } idCacheClone.get(type).put(config.getMapper().getId(record), record); } setIdCache(idCacheClone); } CacheElement e = new CacheElement(ret); e.setLru(System.currentTimeMillis()); Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cl = (Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>) cache.clone(); if (cl.get(type) == null) { cl.put(type, new Hashtable<String, CacheElement>()); } cl.get(type).put(k, e); //atomar execution of this operand - no synchronization needed cache = cl; } public void setPrivilegedThread(Thread thr) { } public void inc(StatisticKeys k) { stats.get(k).inc(); } public String toJsonString(Object o) { return config.getMapper().marshall(o).toString(); } public int writeBufferCount() { return writers.getQueue().size(); } public String getCacheKey(DBObject qo, Map<String, Integer> sort, int skip, int limit) { StringBuffer b = new StringBuffer(); b.append(qo.toString()); b.append(" l:"); b.append(limit); b.append(" s:"); b.append(skip); if (sort != null) { b.append(" sort:"); b.append(new BasicDBObject(sort).toString()); } return b.toString(); } /** * create unique cache key for queries, also honoring skip & limit and sorting * * @param q * @return */ public String getCacheKey(Query q) { return getCacheKey(q.toQueryObject(), q.getOrder(), q.getSkip(), q.getLimit()); } /** * updating an enty in DB without sending the whole entity * only transfers the fields to be changed / set * * @param ent * @param fields */ public void updateUsingFields(final Object ent, final String... fields) { if (ent == null) return; if (fields.length == 0) return; //not doing an update - no change if (!isAnnotationPresentInHierarchy(ent.getClass(), NoProtection.class)) { if (getId(ent) == null) { if (accessDenied(ent, Permission.INSERT)) { throw new SecurityException("Insert of new Object denied!"); } } else { if (accessDenied(ent, Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } } if (isAnnotationPresentInHierarchy(ent.getClass(), NoCache.class)) { config.getWriter().storeUsingFields(ent, fields); return; } firePreUpdateEvent(ent.getClass(), MorphiumStorageListener.UpdateTypes.SET); Cache c = getAnnotationFromHierarchy(ent.getClass(), Cache.class); if (isAnnotationPresentInHierarchy(ent.getClass(), NoCache.class) || c == null || !c.writeCache()) { config.getWriter().storeUsingFields(ent, fields); firePostUpdateEvent(ent.getClass(), MorphiumStorageListener.UpdateTypes.SET); return; } writers.execute(new Runnable() { @Override public void run() { config.getWriter().storeUsingFields(ent, fields); firePostUpdateEvent(ent.getClass(), MorphiumStorageListener.UpdateTypes.SET); } }); } public List<Annotation> getAllAnnotationsFromHierachy(Class<?> cls, Class<? extends Annotation>... anCls) { cls = getRealClass(cls); List<Annotation> ret = new ArrayList<Annotation>(); Class<?> z = cls; while (!z.equals(Object.class)) { if (z.getAnnotations() != null && z.getAnnotations().length != 0) { if (anCls.length == 0) { ret.addAll(Arrays.asList(z.getAnnotations())); } else { for (Annotation a : z.getAnnotations()) { for (Class<? extends Annotation> ac : anCls) { if (a.annotationType().equals(ac)) { ret.add(a); } } } } } z = z.getSuperclass(); if (z == null) break; } return ret; } /** * returns annotations, even if in class hierarchy or * lazyloading proxy * * @param cls * @return */ public <T extends Annotation> T getAnnotationFromHierarchy(Class<?> cls, Class<T> anCls) { cls = getRealClass(cls); if (cls.isAnnotationPresent(anCls)) { return cls.getAnnotation(anCls); } //class hierarchy? Class<?> z = cls; while (!z.equals(Object.class)) { if (z.isAnnotationPresent(anCls)) { return z.getAnnotation(anCls); } z = z.getSuperclass(); if (z == null) break; } return null; } public ObjectMapper getMapper() { return config.getMapper(); } Class<?> getRealClass(Class<?> cls) { return config.getMapper().getRealClass(cls); } <T> T getRealObject(T o) { return config.getMapper().getRealObject(o); } public <T extends Annotation> boolean isAnnotationPresentInHierarchy(Class<?> cls, Class<T> anCls) { return getAnnotationFromHierarchy(cls, anCls) != null; } public void callLifecycleMethod(Class<? extends Annotation> type, Object on) { if (on == null) return; //No synchronized block - might cause the methods to be put twice into the //hashtabel - but for performance reasons, it's ok... Class<?> cls = on.getClass(); //No Lifecycle annotation - no method calling if (!isAnnotationPresentInHierarchy(cls, Lifecycle.class)) {//cls.isAnnotationPresent(Lifecycle.class)) { return; } //Already stored - should not change during runtime if (lifeCycleMethods.get(cls) != null) { if (lifeCycleMethods.get(cls).get(type) != null) { try { lifeCycleMethods.get(cls).get(type).invoke(on); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } return; } Map<Class<? extends Annotation>, Method> methods = new HashMap<Class<? extends Annotation>, Method>(); //Methods must be public for (Method m : cls.getMethods()) { for (Annotation a : m.getAnnotations()) { methods.put(a.annotationType(), m); } } lifeCycleMethods.put(cls, methods); if (methods.get(type) != null) { try { methods.get(type).invoke(on); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } /** * careful this actually changes the parameter o! * * @param o * @param <T> * @return */ public <T> T reread(T o) { if (o == null) throw new RuntimeException("Cannot re read null!"); ObjectId id = getId(o); if (id == null) { return null; } DBCollection col = database.getCollection(getConfig().getMapper().getCollectionName(o.getClass())); BasicDBObject srch = new BasicDBObject("_id", id); DBCursor crs = col.find(srch).limit(1); if (crs.hasNext()) { DBObject dbo = crs.next(); Object fromDb = getConfig().getMapper().unmarshall(o.getClass(), dbo); List<String> flds = getFields(o.getClass()); for (String f : flds) { Field fld = getConfig().getMapper().getField(o.getClass(), f); if (java.lang.reflect.Modifier.isStatic(fld.getModifiers())) { continue; } try { fld.set(o, fld.get(fromDb)); } catch (IllegalAccessException e) { logger.error("Could not set Value: " + fld); } } firePostLoadEvent(o); } else { logger.info("Did not find object with id " + id); return null; } return o; } public void firePreStoreEvent(Object o, boolean isNew) { if (o == null) return; for (MorphiumStorageListener l : listeners) { l.preStore(o, isNew); } callLifecycleMethod(PreStore.class, o); } public void firePostStoreEvent(Object o, boolean isNew) { for (MorphiumStorageListener l : listeners) { l.postStore(o, isNew); } callLifecycleMethod(PostStore.class, o); //existing object => store last Access, if needed } public void firePreDropEvent(Class cls) { for (MorphiumStorageListener l : listeners) { l.preDrop(cls); } } public void firePostDropEvent(Class cls) { for (MorphiumStorageListener l : listeners) { l.postDrop(cls); } } public void firePostUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) { for (MorphiumStorageListener l : listeners) { l.postUpdate(cls, t); } } public void firePreUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) { for (MorphiumStorageListener l : listeners) { l.preUpdate(cls, t); } } public void firePostRemoveEvent(Object o) { for (MorphiumStorageListener l : listeners) { l.postRemove(o); } callLifecycleMethod(PostRemove.class, o); } public void firePostRemoveEvent(Query q) { for (MorphiumStorageListener l : listeners) { l.postRemove(q); } //TODO: FIX - Cannot call lifecycle method here } public void firePreRemoveEvent(Object o) { for (MorphiumStorageListener l : listeners) { l.preDelete(o); } callLifecycleMethod(PreRemove.class, o); } public void firePreRemoveEvent(Query q) { for (MorphiumStorageListener l : listeners) { l.preRemove(q); } //TODO: Fix - cannot call lifecycle method } /** * will be called by query after unmarshalling * * @param o */ public void firePostLoadEvent(Object o) { for (MorphiumStorageListener l : listeners) { l.postLoad(o); } callLifecycleMethod(PostLoad.class, o); } /** * same as retReplicaSetStatus(false); * * @return */ public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus() { return getReplicaSetStatus(false); } /** * get the current replicaset status - issues the replSetGetStatus command to mongo * if full==true, also the configuration is read. This method is called with full==false for every write in * case a Replicaset is configured to find out the current number of active nodes * * @param full * @return */ public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus(boolean full) { if (config.getMode().equals(MongoDbMode.REPLICASET)) { try { CommandResult res = getMongo().getDB("admin").command("replSetGetStatus"); de.caluga.morphium.replicaset.ReplicaSetStatus status = getConfig().getMapper().unmarshall(de.caluga.morphium.replicaset.ReplicaSetStatus.class, res); if (full) { DBCursor rpl = getMongo().getDB("local").getCollection("system.replset").find(); DBObject stat = rpl.next(); //should only be one, i think ReplicaSetConf cfg = getConfig().getMapper().unmarshall(ReplicaSetConf.class, stat); List<Object> mem = cfg.getMemberList(); List<ConfNode> cmembers = new ArrayList<ConfNode>(); for (Object o : mem) { DBObject dbo = (DBObject) o; ConfNode cn = getConfig().getMapper().unmarshall(ConfNode.class, dbo); cmembers.add(cn); } cfg.setMembers(cmembers); status.setConfig(cfg); } //de-referencing list List lst = status.getMembers(); List<ReplicaSetNode> members = new ArrayList<ReplicaSetNode>(); for (Object l : lst) { DBObject o = (DBObject) l; ReplicaSetNode n = getConfig().getMapper().unmarshall(ReplicaSetNode.class, o); members.add(n); } status.setMembers(members); return status; } catch (Exception e) { logger.error("Could not get Replicaset status", e); } } return null; } public boolean isReplicaSet() { return config.getMode().equals(MongoDbMode.REPLICASET); } public WriteConcern getWriteConcernForClass(Class<?> cls) { if (logger.isDebugEnabled()) logger.debug("returning write concern for " + cls.getSimpleName()); WriteSafety safety = getAnnotationFromHierarchy(cls, WriteSafety.class); // cls.getAnnotation(WriteSafety.class); if (safety == null) return null; boolean fsync = safety.waitForSync(); boolean j = safety.waitForJournalCommit(); if (j && fsync) { fsync = false; } int w = safety.level().getValue(); if (!isReplicaSet() && w > 1) { w = 1; } int timeout = safety.timeout(); if (isReplicaSet() && w > 2) { de.caluga.morphium.replicaset.ReplicaSetStatus s = getReplicaSetStatus(); if (s == null || s.getActiveNodes() == 0) { logger.warn("ReplicaSet status is null or no node active! Assuming default write concern"); return null; } if (logger.isDebugEnabled()) logger.debug("Active nodes now: " + s.getActiveNodes()); int activeNodes = s.getActiveNodes(); if (timeout == 0) { if (getConfig().getConnectionTimeout() == 0) { if (logger.isDebugEnabled()) logger.debug("Not waiting for all slaves withoug timeout - unfortunately no connection timeout set in config - setting to 10s, Type: " + cls.getSimpleName()); timeout = 10000; } else { if (logger.isDebugEnabled()) logger.debug("Not waiting for all slaves without timeout - could cause deadlock. Setting to connectionTimeout value, Type: " + cls.getSimpleName()); timeout = getConfig().getConnectionTimeout(); } } //Wait for all active slaves w = activeNodes; } // if (w==0) { // return WriteConcern.NONE; // } // if(w==1) { // return WriteConcern.FSYNC_SAFE; // } // if (w==2) { // return WriteConcern.JOURNAL_SAFE; // } // if (w==3) { // return WriteConcern.REPLICAS_SAFE; // } if (w == -99) { return new WriteConcern("majority", timeout, fsync, j); } return new WriteConcern(w, timeout, fsync, j); } public void addProfilingListener(ProfilingListener l) { profilingListeners.add(l); } public void removeProfilingListener(ProfilingListener l) { profilingListeners.remove(l); } public void fireProfilingWriteEvent(Class type, Object data, long time, boolean isNew, WriteAccessType wt) { for (ProfilingListener l : profilingListeners) { try { l.writeAccess(type, data, time, isNew, wt); } catch (Throwable e) { logger.error("Error during profiling: ", e); } } } public void fireProfilingReadEvent(Query q, long time, ReadAccessType t) { for (ProfilingListener l : profilingListeners) { try { l.readAccess(q, time, t); } catch (Throwable e) { logger.error("Error during profiling", e); } } } public boolean isCached(Class<? extends Object> type, String k) { Cache c = getAnnotationFromHierarchy(type, Cache.class); ///type.getAnnotation(Cache.class); if (c != null) { if (!c.readCache()) return false; } else { return false; } return cache.get(type) != null && cache.get(type).get(k) != null && cache.get(type).get(k).getFound() != null; } /** * return object by from cache. Cache key usually is the string-representation of the search * query.toQueryObject() * * @param type * @param k * @param <T> * @return */ public <T> List<T> getFromCache(Class<T> type, String k) { if (cache.get(type) == null || cache.get(type).get(k) == null) return null; final CacheElement cacheElement = cache.get(type).get(k); cacheElement.setLru(System.currentTimeMillis()); return cacheElement.getFound(); } public Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cloneCache() { return (Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>) cache.clone(); } public Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> cloneIdCache() { return (Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>>) idCache.clone(); } /** * issues a delete command - no lifecycle methods calles, no drop, keeps all indexec this way * * @param cls */ public void clearCollection(Class<? extends Object> cls) { if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { //cls.isAnnotationPresent(NoProtection.class)) { try { if (accessDenied(cls.newInstance(), Permission.DROP)) { throw new SecurityException("Drop / clear of Collection denied!"); } } catch (InstantiationException ex) { Logger.getLogger(Morphium.class).error(ex); } catch (IllegalAccessException ex) { Logger.getLogger(Morphium.class).error(ex); } } firePreDropEvent(cls); delete(createQueryFor(cls)); firePostDropEvent(cls); } /** * clears every single object in collection - reads ALL objects to do so * this way Lifecycle methods can be called! * * @param cls */ public void clearCollectionOneByOne(Class<? extends Object> cls) { if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { //cls.isAnnotationPresent(NoProtection.class)) { try { if (accessDenied(cls.newInstance(), Permission.DROP)) { throw new SecurityException("Drop / clear of Collection denied!"); } } catch (InstantiationException ex) { Logger.getLogger(Morphium.class).error(ex); } catch (IllegalAccessException ex) { Logger.getLogger(Morphium.class).error(ex); } } inc(StatisticKeys.WRITES); List<? extends Object> lst = readAll(cls); for (Object r : lst) { delete(r); } clearCacheIfNecessary(cls); } /** * return a list of all elements stored in morphium for this type * * @param cls - type to search for, needs to be an Property * @param <T> - Type * @return - list of all elements stored */ public <T> List<T> readAll(Class<T> cls) { inc(StatisticKeys.READS); Query<T> qu; qu = createQueryFor(cls); return qu.asList(); } public <T> Query<T> createQueryFor(Class<T> type) { Query<T> q = config.getQueryFact().createQuery(this, type); q.setMorphium(this); return q; } public <T> List<T> find(Query<T> q) { return q.asList(); } private <T> T getFromIDCache(Class<T> type, ObjectId id) { if (idCache.get(type) != null) { return (T) idCache.get(type).get(id); } return null; } public List<Object> distinct(Enum key, Class c) { return distinct(key.name(), c); } /** * returns a distinct list of values of the given collection * Attention: these values are not unmarshalled, you might get MongoDBObjects */ public List<Object> distinct(Enum key, Query q) { return distinct(key.name(), q); } /** * returns a distinct list of values of the given collection * Attention: these values are not unmarshalled, you might get MongoDBObjects */ public List<Object> distinct(String key, Query q) { return database.getCollection(config.getMapper().getCollectionName(q.getType())).distinct(key, q.toQueryObject()); } public List<Object> distinct(String key, Class cls) { DBCollection collection = database.getCollection(config.getMapper().getCollectionName(cls)); setReadPreference(collection, cls); return collection.distinct(key, new BasicDBObject()); } private void setReadPreference(DBCollection c, Class type) { DefaultReadPreference pr = getAnnotationFromHierarchy(type, DefaultReadPreference.class); if (pr != null) { c.setReadPreference(pr.value().getPref()); } else { c.setReadPreference(null); } } public DBObject group(Query q, Map<String, Object> initial, String jsReduce, String jsFinalize, String... keys) { BasicDBObject k = new BasicDBObject(); BasicDBObject ini = new BasicDBObject(); ini.putAll(initial); for (String ks : keys) { if (ks.startsWith("-")) { k.append(ks.substring(1), "false"); } else if (ks.startsWith("+")) { k.append(ks.substring(1), "true"); } else { k.append(ks, "true"); } } if (!jsReduce.trim().startsWith("function(")) { jsReduce = "function (obj,data) { " + jsReduce + " }"; } if (jsFinalize == null) { jsFinalize = ""; } if (!jsFinalize.trim().startsWith("function(")) { jsFinalize = "function (data) {" + jsFinalize + "}"; } GroupCommand cmd = new GroupCommand(database.getCollection(config.getMapper().getCollectionName(q.getType())), k, q.toQueryObject(), ini, jsReduce, jsFinalize); return database.getCollection(config.getMapper().getCollectionName(q.getType())).group(cmd); } public <T> T findById(Class<T> type, ObjectId id) { T ret = getFromIDCache(type, id); if (ret != null) return ret; List<String> ls = config.getMapper().getFields(type, Id.class); if (ls.size() == 0) throw new RuntimeException("Cannot find by ID on non-Entity"); return (T) createQueryFor(type).f(ls.get(0)).eq(id).get(); } // /** // * returns a list of all elements for the given type, matching the given query // * @param qu - the query to search // * @param <T> - type of the elementyx // * @return - list of elements matching query // */ // public <T> List<T> readAll(Query<T> qu) { // inc(StatisticKeys.READS); // if (qu.getEntityClass().isAnnotationPresent(Cache.class)) { // if (isCached(qu.getEntityClass(), qu.toString())) { // inc(StatisticKeys.CHITS); // return getFromCache(qu.getEntityClass(), qu.toString()); // } else { // inc(StatisticKeys.CMISS); // } // } // List<T> lst = qu.asList(); // addToCache(qu.toString()+" / l:"+((QueryImpl)qu).getLimit()+" o:"+((QueryImpl)qu).getOffset(), qu.getEntityClass(), lst); // return lst; // // } /** * does not set values in DB only in the entity * * @param toSetValueIn */ public void setValueIn(Object toSetValueIn, String fld, Object value) { config.getMapper().setValue(toSetValueIn, value, fld); } public void setValueIn(Object toSetValueIn, Enum fld, Object value) { config.getMapper().setValue(toSetValueIn, value, fld.name()); } public Object getValueOf(Object toGetValueFrom, String fld) { return config.getMapper().getValue(toGetValueFrom, fld); } public Object getValueOf(Object toGetValueFrom, Enum fld) { return config.getMapper().getValue(toGetValueFrom, fld.name()); } @SuppressWarnings("unchecked") public <T> List<T> findByField(Class<T> cls, String fld, Object val) { Query<T> q = createQueryFor(cls); q = q.f(fld).eq(val); return q.asList(); // return createQueryFor(cls).field(fld).equal(val).asList(); } public <T> List<T> findByField(Class<T> cls, Enum fld, Object val) { Query<T> q = createQueryFor(cls); q = q.f(fld).eq(val); return q.asList(); // return createQueryFor(cls).field(fld).equal(val).asList(); } /** * get a list of valid fields of a given record as they are in the MongoDB * so, if you have a field Mapping, the mapped Property-name will be used * * @param cls * @return */ public final List<String> getFields(Class cls) { return config.getMapper().getFields(cls); } public final Class getTypeOfField(Class cls, String fld) { Field f = getField(cls, fld); if (f == null) return null; return f.getType(); } public boolean storesLastChange(Class<? extends Object> cls) { return isAnnotationPresentInHierarchy(cls, StoreLastChange.class); } public boolean storesLastAccess(Class<? extends Object> cls) { return isAnnotationPresentInHierarchy(cls, StoreLastAccess.class); } public boolean storesCreation(Class<? extends Object> cls) { return isAnnotationPresentInHierarchy(cls, StoreCreationTime.class); } public String getFieldName(Class cls, String fld) { return config.getMapper().getFieldName(cls, fld); } /** * extended logic: Fld may be, the java field name, the name of the specified value in Property-Annotation or * the translated underscored lowercase name (mongoId => mongo_id) * * @param cls - class to search * @param fld - field name * @return field, if found, null else */ public Field getField(Class cls, String fld) { return config.getMapper().getField(cls, fld); } public void setValue(Object in, String fld, Object val) { config.getMapper().setValue(in, val, fld); } public Object getValue(Object o, String fld) { return config.getMapper().getValue(o, fld); } public Long getLongValue(Object o, String fld) { return (Long) getValue(o, fld); } public String getStringValue(Object o, String fld) { return (String) getValue(o, fld); } public Date getDateValue(Object o, String fld) { return (Date) getValue(o, fld); } public Double getDoubleValue(Object o, String fld) { return (Double) getValue(o, fld); } /** * Erase cache entries for the given type. is being called after every store * depending on cache settings! * * @param cls */ public void clearCachefor(Class<? extends Object> cls) { if (cache.get(cls) != null) { cache.get(cls).clear(); } if (idCache.get(cls) != null) { idCache.get(cls).clear(); } //clearCacheFor(cls); } public void storeNoCache(Object lst) { config.getWriter().store(lst); } public void storeInBackground(final Object lst) { inc(StatisticKeys.WRITES_CACHED); writers.execute(new Runnable() { @Override public void run() { boolean isNew = getId(lst) == null; firePreStoreEvent(lst, isNew); config.getWriter().store(lst); firePostStoreEvent(lst, isNew); } }); } public ObjectId getId(Object o) { return config.getMapper().getId(o); } public void dropCollection(Class<? extends Object> cls) { if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { try { if (accessDenied(cls.newInstance(), Permission.DROP)) { throw new SecurityException("Drop of Collection denied!"); } } catch (InstantiationException ex) { Logger.getLogger(Morphium.class.getName()).fatal(ex); } catch (IllegalAccessException ex) { Logger.getLogger(Morphium.class.getName()).fatal(ex); } } if (config.getMode() == MongoDbMode.REPLICASET && config.getAdr().size() > 1) { //replicaset logger.warn("Cannot drop collection for class " + cls.getSimpleName() + " as we're in a clustered environment (Driver 2.8.0)"); clearCollection(cls); return; } if (isAnnotationPresentInHierarchy(cls, Entity.class)) { firePreDropEvent(cls); long start = System.currentTimeMillis(); // Entity entity = getAnnotationFromHierarchy(cls, Entity.class); //cls.getAnnotation(Entity.class); DBCollection coll = database.getCollection(config.getMapper().getCollectionName(cls)); // coll.setReadPreference(com.mongodb.ReadPreference.PRIMARY); coll.drop(); long dur = System.currentTimeMillis() - start; fireProfilingWriteEvent(cls, null, dur, false, WriteAccessType.DROP); firePostDropEvent(cls); } else { throw new RuntimeException("No entity class: " + cls.getName()); } } public void ensureIndex(Class<?> cls, Map<String, Integer> index) { List<String> fields = getFields(cls); Map<String, Integer> idx = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> es : index.entrySet()) { String k = es.getKey(); if (!fields.contains(k) && !fields.contains(config.getMapper().convertCamelCase(k))) { throw new IllegalArgumentException("Field unknown for type " + cls.getSimpleName() + ": " + k); } String fn = config.getMapper().getFieldName(cls, k); idx.put(fn, es.getValue()); } long start = System.currentTimeMillis(); database.getCollection(config.getMapper().getCollectionName(cls)).ensureIndex(new BasicDBObject(idx)); long dur = System.currentTimeMillis() - start; fireProfilingWriteEvent(cls, new BasicDBObject(idx), dur, false, WriteAccessType.ENSURE_INDEX); } /** * ensureIndex(CachedObject.class,"counter","-value"); * Similar to sorting * * @param cls * @param fldStr */ public void ensureIndex(Class<?> cls, String... fldStr) { Map<String, Integer> m = new LinkedHashMap<String, Integer>(); for (String f : fldStr) { int idx = 1; if (f.startsWith("-")) { idx = -1; f = f.substring(1); } else if (f.startsWith("+")) { f = f.substring(1); } m.put(f, idx); } ensureIndex(cls, m); } public void ensureIndex(Class<?> cls, Enum... fldStr) { Map<String, Integer> m = new LinkedHashMap<String, Integer>(); for (Enum e : fldStr) { String f = e.name(); m.put(f, 1); } ensureIndex(cls, m); } /** * Stores a single Object. Clears the corresponding cache * * @param o - Object to store */ public void store(Object o) { if (o instanceof List) { throw new RuntimeException("Lists need to be stored with storeList"); } Class<?> type = getRealClass(o.getClass()); final boolean isNew = getId(o) == null; if (!isAnnotationPresentInHierarchy(type, NoProtection.class)) { //o.getClass().isAnnotationPresent(NoProtection.class)) { if (isNew) { if (accessDenied(o, Permission.INSERT)) { throw new SecurityException("Insert of new Object denied!"); } } else { if (accessDenied(o, Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } } firePreStoreEvent(o, isNew); Cache cc = getAnnotationFromHierarchy(type, Cache.class);//o.getClass().getAnnotation(Cache.class); if (cc == null || isAnnotationPresentInHierarchy(o.getClass(), NoCache.class) || !cc.writeCache()) { config.getWriter().store(o); firePostStoreEvent(o, isNew); return; } final Object fo = o; writers.execute(new Runnable() { @Override public void run() { config.getWriter().store(fo); firePostStoreEvent(fo, isNew); } }); inc(StatisticKeys.WRITES_CACHED); } public <T> void storeList(List<T> lst) { //have to sort list - might have different objects List<T> storeDirect = new ArrayList<T>(); final List<T> storeInBg = new ArrayList<T>(); //checking permission - might take some time ;-( for (T o : lst) { if (getId(o) == null) { if (accessDenied(o, Permission.INSERT)) { throw new SecurityException("Insert of new Object denied!"); } } else { if (accessDenied(o, Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } Cache c = getAnnotationFromHierarchy(o.getClass(), Cache.class);//o.getClass().getAnnotation(Cache.class); if (isAnnotationPresentInHierarchy(o.getClass(), NoCache.class) || c == null || !c.writeCache()) { storeDirect.add(o); } else { storeDirect.add(o); } } writers.execute(new Runnable() { @Override public void run() { callLifecycleMethod(PreStore.class, storeInBg); config.getWriter().store(storeInBg); callLifecycleMethod(PostStore.class, storeInBg); } }); callLifecycleMethod(PreStore.class, storeDirect); config.getWriter().store(storeDirect); callLifecycleMethod(PostStore.class, storeDirect); } public void delete(Query o) { if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) { if (accessDenied(o, Permission.DELETE)) { throw new SecurityException("Deletion of Object denied!"); } } callLifecycleMethod(PreRemove.class, o); firePreRemoveEvent(o); Cache cc = getAnnotationFromHierarchy(o.getType(), Cache.class);//o.getClass().getAnnotation(Cache.class); if (cc == null || isAnnotationPresentInHierarchy(o.getType(), NoCache.class) || !cc.writeCache()) { config.getWriter().delete(o); callLifecycleMethod(PostRemove.class, o); firePostRemoveEvent(o); return; } final Query fo = o; writers.execute(new Runnable() { @Override public void run() { config.getWriter().delete(fo); firePostRemoveEvent(fo); } }); inc(StatisticKeys.WRITES_CACHED); firePostRemoveEvent(o); } /** * deletes a single object from morphium backend. Clears cache * * @param o */ public void delete(Object o) { if (o instanceof Query) { delete((Query) o); return; } o = getRealObject(o); if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) { if (accessDenied(o, Permission.DELETE)) { throw new SecurityException("Deletion of Object denied!"); } } firePreRemoveEvent(o); Cache cc = getAnnotationFromHierarchy(o.getClass(), Cache.class);//o.getClass().getAnnotation(Cache.class); if (cc == null || isAnnotationPresentInHierarchy(o.getClass(), NoCache.class) || !cc.writeCache()) { - config.getWriter().store(o); + config.getWriter().delete(o); firePostRemoveEvent(o); return; } final Object fo = o; writers.execute(new Runnable() { @Override public void run() { config.getWriter().delete(fo); firePostRemoveEvent(fo); } }); inc(StatisticKeys.WRITES_CACHED); } public void resetCache() { setCache(new Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>()); } public void setCache(Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cache) { this.cache = cache; } ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////// /////////////// Statistics ///////// ///// /// public Map<String, Double> getStatistics() { return new Statistics(this); } public void removeEntryFromCache(Class cls, ObjectId id) { Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> c = cloneCache(); Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idc = cloneIdCache(); idc.get(cls).remove(id); ArrayList<String> toRemove = new ArrayList<String>(); for (String key : c.get(cls).keySet()) { for (Object el : c.get(cls).get(key).getFound()) { ObjectId lid = config.getMapper().getId(el); if (lid == null) { logger.error("Null id in CACHE?"); toRemove.add(key); } if (lid.equals(id)) { toRemove.add(key); } } } for (String k : toRemove) { c.get(cls).remove(k); } setCache(c); setIdCache(idc); } public Map<StatisticKeys, StatisticValue> getStats() { return stats; } public void addShutdownListener(ShutdownListener l) { shutDownListeners.add(l); } public void removeShutdownListener(ShutdownListener l) { shutDownListeners.remove(l); } public void close() { cacheHousekeeper.end(); for (ShutdownListener l : shutDownListeners) { l.onShutdown(this); } try { Thread.sleep(1000); //give it time to end ;-) } catch (Exception e) { logger.debug("Ignoring interrupted-exception"); } if (cacheHousekeeper.isAlive()) { cacheHousekeeper.interrupt(); } database = null; config = null; mongo.close(); MorphiumSingleton.reset(); } public String createCamelCase(String n) { return config.getMapper().createCamelCase(n, false); } public boolean isWriteCached(Class<?> cls) { Cache c = getAnnotationFromHierarchy(cls, Cache.class); if (isAnnotationPresentInHierarchy(cls, NoCache.class) || c == null || !c.writeCache()) { return false; } return true; } public <T, R> Aggregator<T, R> createAggregator(Class<T> type, Class<R> resultType) { Aggregator<T, R> aggregator = config.getAggregatorFactory().createAggregator(type, resultType); aggregator.setMorphium(this); return aggregator; } public <T, R> List<R> aggregate(Aggregator<T, R> a) { DBCollection coll = database.getCollection(config.getMapper().getCollectionName(a.getSearchType())); List<DBObject> agList = a.toAggregationList(); DBObject first = agList.get(0); agList.remove(0); AggregationOutput resp = coll.aggregate(first, agList.toArray(new DBObject[agList.size()])); List<R> ret = new ArrayList<R>(); for (DBObject o : resp.results()) { ret.add(getMapper().unmarshall(a.getResultType(), o)); } return ret; } /** * create a proxy object, implementing the ParitallyUpdateable Interface * these objects will be updated in mongo by only changing altered fields * <b>Attention:</b> the field name if determined by the setter name for now. That means, it does not honor the @Property-Annotation!!! * To make sure, you take the correct field - use the UpdatingField-Annotation for the setters! * * @param o * @param <T> * @return */ public <T> T createPartiallyUpdateableEntity(T o) { return (T) Enhancer.create(o.getClass(), new Class[]{PartiallyUpdateable.class, Serializable.class}, new PartiallyUpdateableProxy(this, o)); } public <T> T createLazyLoadedEntity(Class<T> cls, ObjectId id) { return (T) Enhancer.create(cls, new Class[]{Serializable.class}, new LazyDeReferencingProxy(this, cls, id)); } public <T> MongoField<T> createMongoField() { try { return (MongoField<T>) config.getFieldImplClass().newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public String getLastChangeField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastChange.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getLastChangeByField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastChangeBy.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getLastAccessField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastAccess.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getLastAccessByField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastAccessBy.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getCreationTimeField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null; List<String> lst = config.getMapper().getFields(cls, CreationTime.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getCreatedByField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null; List<String> lst = config.getMapper().getFields(cls, CreatedBy.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } ////////////////////////////////////////////////////// ////////// SecuritySettings /////// ///// //// /// // public MongoSecurityManager getSecurityManager() { return config.getSecurityMgr(); } /** * temporarily switch off security settings - needed by SecurityManagers */ public void setPrivileged() { privileged.add(Thread.currentThread()); } public boolean checkAccess(String domain, Permission p) throws MongoSecurityException { if (privileged.contains(Thread.currentThread())) { privileged.remove(Thread.currentThread()); return true; } return getSecurityManager().checkAccess(domain, p); } public boolean accessDenied(Class<?> cls, Permission p) throws MongoSecurityException { if (isAnnotationPresentInHierarchy(cls, NoProtection.class)) { return false; } if (privileged.contains(Thread.currentThread())) { privileged.remove(Thread.currentThread()); return false; } return !getSecurityManager().checkAccess(cls, p); } public boolean accessDenied(Object r, Permission p) throws MongoSecurityException { if (isAnnotationPresentInHierarchy(r.getClass(), NoProtection.class)) { return false; } if (privileged.contains(Thread.currentThread())) { privileged.remove(Thread.currentThread()); return false; } return !getSecurityManager().checkAccess(config.getMapper().getRealObject(r), p); } }
true
true
public void callLifecycleMethod(Class<? extends Annotation> type, Object on) { if (on == null) return; //No synchronized block - might cause the methods to be put twice into the //hashtabel - but for performance reasons, it's ok... Class<?> cls = on.getClass(); //No Lifecycle annotation - no method calling if (!isAnnotationPresentInHierarchy(cls, Lifecycle.class)) {//cls.isAnnotationPresent(Lifecycle.class)) { return; } //Already stored - should not change during runtime if (lifeCycleMethods.get(cls) != null) { if (lifeCycleMethods.get(cls).get(type) != null) { try { lifeCycleMethods.get(cls).get(type).invoke(on); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } return; } Map<Class<? extends Annotation>, Method> methods = new HashMap<Class<? extends Annotation>, Method>(); //Methods must be public for (Method m : cls.getMethods()) { for (Annotation a : m.getAnnotations()) { methods.put(a.annotationType(), m); } } lifeCycleMethods.put(cls, methods); if (methods.get(type) != null) { try { methods.get(type).invoke(on); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } /** * careful this actually changes the parameter o! * * @param o * @param <T> * @return */ public <T> T reread(T o) { if (o == null) throw new RuntimeException("Cannot re read null!"); ObjectId id = getId(o); if (id == null) { return null; } DBCollection col = database.getCollection(getConfig().getMapper().getCollectionName(o.getClass())); BasicDBObject srch = new BasicDBObject("_id", id); DBCursor crs = col.find(srch).limit(1); if (crs.hasNext()) { DBObject dbo = crs.next(); Object fromDb = getConfig().getMapper().unmarshall(o.getClass(), dbo); List<String> flds = getFields(o.getClass()); for (String f : flds) { Field fld = getConfig().getMapper().getField(o.getClass(), f); if (java.lang.reflect.Modifier.isStatic(fld.getModifiers())) { continue; } try { fld.set(o, fld.get(fromDb)); } catch (IllegalAccessException e) { logger.error("Could not set Value: " + fld); } } firePostLoadEvent(o); } else { logger.info("Did not find object with id " + id); return null; } return o; } public void firePreStoreEvent(Object o, boolean isNew) { if (o == null) return; for (MorphiumStorageListener l : listeners) { l.preStore(o, isNew); } callLifecycleMethod(PreStore.class, o); } public void firePostStoreEvent(Object o, boolean isNew) { for (MorphiumStorageListener l : listeners) { l.postStore(o, isNew); } callLifecycleMethod(PostStore.class, o); //existing object => store last Access, if needed } public void firePreDropEvent(Class cls) { for (MorphiumStorageListener l : listeners) { l.preDrop(cls); } } public void firePostDropEvent(Class cls) { for (MorphiumStorageListener l : listeners) { l.postDrop(cls); } } public void firePostUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) { for (MorphiumStorageListener l : listeners) { l.postUpdate(cls, t); } } public void firePreUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) { for (MorphiumStorageListener l : listeners) { l.preUpdate(cls, t); } } public void firePostRemoveEvent(Object o) { for (MorphiumStorageListener l : listeners) { l.postRemove(o); } callLifecycleMethod(PostRemove.class, o); } public void firePostRemoveEvent(Query q) { for (MorphiumStorageListener l : listeners) { l.postRemove(q); } //TODO: FIX - Cannot call lifecycle method here } public void firePreRemoveEvent(Object o) { for (MorphiumStorageListener l : listeners) { l.preDelete(o); } callLifecycleMethod(PreRemove.class, o); } public void firePreRemoveEvent(Query q) { for (MorphiumStorageListener l : listeners) { l.preRemove(q); } //TODO: Fix - cannot call lifecycle method } /** * will be called by query after unmarshalling * * @param o */ public void firePostLoadEvent(Object o) { for (MorphiumStorageListener l : listeners) { l.postLoad(o); } callLifecycleMethod(PostLoad.class, o); } /** * same as retReplicaSetStatus(false); * * @return */ public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus() { return getReplicaSetStatus(false); } /** * get the current replicaset status - issues the replSetGetStatus command to mongo * if full==true, also the configuration is read. This method is called with full==false for every write in * case a Replicaset is configured to find out the current number of active nodes * * @param full * @return */ public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus(boolean full) { if (config.getMode().equals(MongoDbMode.REPLICASET)) { try { CommandResult res = getMongo().getDB("admin").command("replSetGetStatus"); de.caluga.morphium.replicaset.ReplicaSetStatus status = getConfig().getMapper().unmarshall(de.caluga.morphium.replicaset.ReplicaSetStatus.class, res); if (full) { DBCursor rpl = getMongo().getDB("local").getCollection("system.replset").find(); DBObject stat = rpl.next(); //should only be one, i think ReplicaSetConf cfg = getConfig().getMapper().unmarshall(ReplicaSetConf.class, stat); List<Object> mem = cfg.getMemberList(); List<ConfNode> cmembers = new ArrayList<ConfNode>(); for (Object o : mem) { DBObject dbo = (DBObject) o; ConfNode cn = getConfig().getMapper().unmarshall(ConfNode.class, dbo); cmembers.add(cn); } cfg.setMembers(cmembers); status.setConfig(cfg); } //de-referencing list List lst = status.getMembers(); List<ReplicaSetNode> members = new ArrayList<ReplicaSetNode>(); for (Object l : lst) { DBObject o = (DBObject) l; ReplicaSetNode n = getConfig().getMapper().unmarshall(ReplicaSetNode.class, o); members.add(n); } status.setMembers(members); return status; } catch (Exception e) { logger.error("Could not get Replicaset status", e); } } return null; } public boolean isReplicaSet() { return config.getMode().equals(MongoDbMode.REPLICASET); } public WriteConcern getWriteConcernForClass(Class<?> cls) { if (logger.isDebugEnabled()) logger.debug("returning write concern for " + cls.getSimpleName()); WriteSafety safety = getAnnotationFromHierarchy(cls, WriteSafety.class); // cls.getAnnotation(WriteSafety.class); if (safety == null) return null; boolean fsync = safety.waitForSync(); boolean j = safety.waitForJournalCommit(); if (j && fsync) { fsync = false; } int w = safety.level().getValue(); if (!isReplicaSet() && w > 1) { w = 1; } int timeout = safety.timeout(); if (isReplicaSet() && w > 2) { de.caluga.morphium.replicaset.ReplicaSetStatus s = getReplicaSetStatus(); if (s == null || s.getActiveNodes() == 0) { logger.warn("ReplicaSet status is null or no node active! Assuming default write concern"); return null; } if (logger.isDebugEnabled()) logger.debug("Active nodes now: " + s.getActiveNodes()); int activeNodes = s.getActiveNodes(); if (timeout == 0) { if (getConfig().getConnectionTimeout() == 0) { if (logger.isDebugEnabled()) logger.debug("Not waiting for all slaves withoug timeout - unfortunately no connection timeout set in config - setting to 10s, Type: " + cls.getSimpleName()); timeout = 10000; } else { if (logger.isDebugEnabled()) logger.debug("Not waiting for all slaves without timeout - could cause deadlock. Setting to connectionTimeout value, Type: " + cls.getSimpleName()); timeout = getConfig().getConnectionTimeout(); } } //Wait for all active slaves w = activeNodes; } // if (w==0) { // return WriteConcern.NONE; // } // if(w==1) { // return WriteConcern.FSYNC_SAFE; // } // if (w==2) { // return WriteConcern.JOURNAL_SAFE; // } // if (w==3) { // return WriteConcern.REPLICAS_SAFE; // } if (w == -99) { return new WriteConcern("majority", timeout, fsync, j); } return new WriteConcern(w, timeout, fsync, j); } public void addProfilingListener(ProfilingListener l) { profilingListeners.add(l); } public void removeProfilingListener(ProfilingListener l) { profilingListeners.remove(l); } public void fireProfilingWriteEvent(Class type, Object data, long time, boolean isNew, WriteAccessType wt) { for (ProfilingListener l : profilingListeners) { try { l.writeAccess(type, data, time, isNew, wt); } catch (Throwable e) { logger.error("Error during profiling: ", e); } } } public void fireProfilingReadEvent(Query q, long time, ReadAccessType t) { for (ProfilingListener l : profilingListeners) { try { l.readAccess(q, time, t); } catch (Throwable e) { logger.error("Error during profiling", e); } } } public boolean isCached(Class<? extends Object> type, String k) { Cache c = getAnnotationFromHierarchy(type, Cache.class); ///type.getAnnotation(Cache.class); if (c != null) { if (!c.readCache()) return false; } else { return false; } return cache.get(type) != null && cache.get(type).get(k) != null && cache.get(type).get(k).getFound() != null; } /** * return object by from cache. Cache key usually is the string-representation of the search * query.toQueryObject() * * @param type * @param k * @param <T> * @return */ public <T> List<T> getFromCache(Class<T> type, String k) { if (cache.get(type) == null || cache.get(type).get(k) == null) return null; final CacheElement cacheElement = cache.get(type).get(k); cacheElement.setLru(System.currentTimeMillis()); return cacheElement.getFound(); } public Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cloneCache() { return (Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>) cache.clone(); } public Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> cloneIdCache() { return (Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>>) idCache.clone(); } /** * issues a delete command - no lifecycle methods calles, no drop, keeps all indexec this way * * @param cls */ public void clearCollection(Class<? extends Object> cls) { if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { //cls.isAnnotationPresent(NoProtection.class)) { try { if (accessDenied(cls.newInstance(), Permission.DROP)) { throw new SecurityException("Drop / clear of Collection denied!"); } } catch (InstantiationException ex) { Logger.getLogger(Morphium.class).error(ex); } catch (IllegalAccessException ex) { Logger.getLogger(Morphium.class).error(ex); } } firePreDropEvent(cls); delete(createQueryFor(cls)); firePostDropEvent(cls); } /** * clears every single object in collection - reads ALL objects to do so * this way Lifecycle methods can be called! * * @param cls */ public void clearCollectionOneByOne(Class<? extends Object> cls) { if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { //cls.isAnnotationPresent(NoProtection.class)) { try { if (accessDenied(cls.newInstance(), Permission.DROP)) { throw new SecurityException("Drop / clear of Collection denied!"); } } catch (InstantiationException ex) { Logger.getLogger(Morphium.class).error(ex); } catch (IllegalAccessException ex) { Logger.getLogger(Morphium.class).error(ex); } } inc(StatisticKeys.WRITES); List<? extends Object> lst = readAll(cls); for (Object r : lst) { delete(r); } clearCacheIfNecessary(cls); } /** * return a list of all elements stored in morphium for this type * * @param cls - type to search for, needs to be an Property * @param <T> - Type * @return - list of all elements stored */ public <T> List<T> readAll(Class<T> cls) { inc(StatisticKeys.READS); Query<T> qu; qu = createQueryFor(cls); return qu.asList(); } public <T> Query<T> createQueryFor(Class<T> type) { Query<T> q = config.getQueryFact().createQuery(this, type); q.setMorphium(this); return q; } public <T> List<T> find(Query<T> q) { return q.asList(); } private <T> T getFromIDCache(Class<T> type, ObjectId id) { if (idCache.get(type) != null) { return (T) idCache.get(type).get(id); } return null; } public List<Object> distinct(Enum key, Class c) { return distinct(key.name(), c); } /** * returns a distinct list of values of the given collection * Attention: these values are not unmarshalled, you might get MongoDBObjects */ public List<Object> distinct(Enum key, Query q) { return distinct(key.name(), q); } /** * returns a distinct list of values of the given collection * Attention: these values are not unmarshalled, you might get MongoDBObjects */ public List<Object> distinct(String key, Query q) { return database.getCollection(config.getMapper().getCollectionName(q.getType())).distinct(key, q.toQueryObject()); } public List<Object> distinct(String key, Class cls) { DBCollection collection = database.getCollection(config.getMapper().getCollectionName(cls)); setReadPreference(collection, cls); return collection.distinct(key, new BasicDBObject()); } private void setReadPreference(DBCollection c, Class type) { DefaultReadPreference pr = getAnnotationFromHierarchy(type, DefaultReadPreference.class); if (pr != null) { c.setReadPreference(pr.value().getPref()); } else { c.setReadPreference(null); } } public DBObject group(Query q, Map<String, Object> initial, String jsReduce, String jsFinalize, String... keys) { BasicDBObject k = new BasicDBObject(); BasicDBObject ini = new BasicDBObject(); ini.putAll(initial); for (String ks : keys) { if (ks.startsWith("-")) { k.append(ks.substring(1), "false"); } else if (ks.startsWith("+")) { k.append(ks.substring(1), "true"); } else { k.append(ks, "true"); } } if (!jsReduce.trim().startsWith("function(")) { jsReduce = "function (obj,data) { " + jsReduce + " }"; } if (jsFinalize == null) { jsFinalize = ""; } if (!jsFinalize.trim().startsWith("function(")) { jsFinalize = "function (data) {" + jsFinalize + "}"; } GroupCommand cmd = new GroupCommand(database.getCollection(config.getMapper().getCollectionName(q.getType())), k, q.toQueryObject(), ini, jsReduce, jsFinalize); return database.getCollection(config.getMapper().getCollectionName(q.getType())).group(cmd); } public <T> T findById(Class<T> type, ObjectId id) { T ret = getFromIDCache(type, id); if (ret != null) return ret; List<String> ls = config.getMapper().getFields(type, Id.class); if (ls.size() == 0) throw new RuntimeException("Cannot find by ID on non-Entity"); return (T) createQueryFor(type).f(ls.get(0)).eq(id).get(); } // /** // * returns a list of all elements for the given type, matching the given query // * @param qu - the query to search // * @param <T> - type of the elementyx // * @return - list of elements matching query // */ // public <T> List<T> readAll(Query<T> qu) { // inc(StatisticKeys.READS); // if (qu.getEntityClass().isAnnotationPresent(Cache.class)) { // if (isCached(qu.getEntityClass(), qu.toString())) { // inc(StatisticKeys.CHITS); // return getFromCache(qu.getEntityClass(), qu.toString()); // } else { // inc(StatisticKeys.CMISS); // } // } // List<T> lst = qu.asList(); // addToCache(qu.toString()+" / l:"+((QueryImpl)qu).getLimit()+" o:"+((QueryImpl)qu).getOffset(), qu.getEntityClass(), lst); // return lst; // // } /** * does not set values in DB only in the entity * * @param toSetValueIn */ public void setValueIn(Object toSetValueIn, String fld, Object value) { config.getMapper().setValue(toSetValueIn, value, fld); } public void setValueIn(Object toSetValueIn, Enum fld, Object value) { config.getMapper().setValue(toSetValueIn, value, fld.name()); } public Object getValueOf(Object toGetValueFrom, String fld) { return config.getMapper().getValue(toGetValueFrom, fld); } public Object getValueOf(Object toGetValueFrom, Enum fld) { return config.getMapper().getValue(toGetValueFrom, fld.name()); } @SuppressWarnings("unchecked") public <T> List<T> findByField(Class<T> cls, String fld, Object val) { Query<T> q = createQueryFor(cls); q = q.f(fld).eq(val); return q.asList(); // return createQueryFor(cls).field(fld).equal(val).asList(); } public <T> List<T> findByField(Class<T> cls, Enum fld, Object val) { Query<T> q = createQueryFor(cls); q = q.f(fld).eq(val); return q.asList(); // return createQueryFor(cls).field(fld).equal(val).asList(); } /** * get a list of valid fields of a given record as they are in the MongoDB * so, if you have a field Mapping, the mapped Property-name will be used * * @param cls * @return */ public final List<String> getFields(Class cls) { return config.getMapper().getFields(cls); } public final Class getTypeOfField(Class cls, String fld) { Field f = getField(cls, fld); if (f == null) return null; return f.getType(); } public boolean storesLastChange(Class<? extends Object> cls) { return isAnnotationPresentInHierarchy(cls, StoreLastChange.class); } public boolean storesLastAccess(Class<? extends Object> cls) { return isAnnotationPresentInHierarchy(cls, StoreLastAccess.class); } public boolean storesCreation(Class<? extends Object> cls) { return isAnnotationPresentInHierarchy(cls, StoreCreationTime.class); } public String getFieldName(Class cls, String fld) { return config.getMapper().getFieldName(cls, fld); } /** * extended logic: Fld may be, the java field name, the name of the specified value in Property-Annotation or * the translated underscored lowercase name (mongoId => mongo_id) * * @param cls - class to search * @param fld - field name * @return field, if found, null else */ public Field getField(Class cls, String fld) { return config.getMapper().getField(cls, fld); } public void setValue(Object in, String fld, Object val) { config.getMapper().setValue(in, val, fld); } public Object getValue(Object o, String fld) { return config.getMapper().getValue(o, fld); } public Long getLongValue(Object o, String fld) { return (Long) getValue(o, fld); } public String getStringValue(Object o, String fld) { return (String) getValue(o, fld); } public Date getDateValue(Object o, String fld) { return (Date) getValue(o, fld); } public Double getDoubleValue(Object o, String fld) { return (Double) getValue(o, fld); } /** * Erase cache entries for the given type. is being called after every store * depending on cache settings! * * @param cls */ public void clearCachefor(Class<? extends Object> cls) { if (cache.get(cls) != null) { cache.get(cls).clear(); } if (idCache.get(cls) != null) { idCache.get(cls).clear(); } //clearCacheFor(cls); } public void storeNoCache(Object lst) { config.getWriter().store(lst); } public void storeInBackground(final Object lst) { inc(StatisticKeys.WRITES_CACHED); writers.execute(new Runnable() { @Override public void run() { boolean isNew = getId(lst) == null; firePreStoreEvent(lst, isNew); config.getWriter().store(lst); firePostStoreEvent(lst, isNew); } }); } public ObjectId getId(Object o) { return config.getMapper().getId(o); } public void dropCollection(Class<? extends Object> cls) { if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { try { if (accessDenied(cls.newInstance(), Permission.DROP)) { throw new SecurityException("Drop of Collection denied!"); } } catch (InstantiationException ex) { Logger.getLogger(Morphium.class.getName()).fatal(ex); } catch (IllegalAccessException ex) { Logger.getLogger(Morphium.class.getName()).fatal(ex); } } if (config.getMode() == MongoDbMode.REPLICASET && config.getAdr().size() > 1) { //replicaset logger.warn("Cannot drop collection for class " + cls.getSimpleName() + " as we're in a clustered environment (Driver 2.8.0)"); clearCollection(cls); return; } if (isAnnotationPresentInHierarchy(cls, Entity.class)) { firePreDropEvent(cls); long start = System.currentTimeMillis(); // Entity entity = getAnnotationFromHierarchy(cls, Entity.class); //cls.getAnnotation(Entity.class); DBCollection coll = database.getCollection(config.getMapper().getCollectionName(cls)); // coll.setReadPreference(com.mongodb.ReadPreference.PRIMARY); coll.drop(); long dur = System.currentTimeMillis() - start; fireProfilingWriteEvent(cls, null, dur, false, WriteAccessType.DROP); firePostDropEvent(cls); } else { throw new RuntimeException("No entity class: " + cls.getName()); } } public void ensureIndex(Class<?> cls, Map<String, Integer> index) { List<String> fields = getFields(cls); Map<String, Integer> idx = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> es : index.entrySet()) { String k = es.getKey(); if (!fields.contains(k) && !fields.contains(config.getMapper().convertCamelCase(k))) { throw new IllegalArgumentException("Field unknown for type " + cls.getSimpleName() + ": " + k); } String fn = config.getMapper().getFieldName(cls, k); idx.put(fn, es.getValue()); } long start = System.currentTimeMillis(); database.getCollection(config.getMapper().getCollectionName(cls)).ensureIndex(new BasicDBObject(idx)); long dur = System.currentTimeMillis() - start; fireProfilingWriteEvent(cls, new BasicDBObject(idx), dur, false, WriteAccessType.ENSURE_INDEX); } /** * ensureIndex(CachedObject.class,"counter","-value"); * Similar to sorting * * @param cls * @param fldStr */ public void ensureIndex(Class<?> cls, String... fldStr) { Map<String, Integer> m = new LinkedHashMap<String, Integer>(); for (String f : fldStr) { int idx = 1; if (f.startsWith("-")) { idx = -1; f = f.substring(1); } else if (f.startsWith("+")) { f = f.substring(1); } m.put(f, idx); } ensureIndex(cls, m); } public void ensureIndex(Class<?> cls, Enum... fldStr) { Map<String, Integer> m = new LinkedHashMap<String, Integer>(); for (Enum e : fldStr) { String f = e.name(); m.put(f, 1); } ensureIndex(cls, m); } /** * Stores a single Object. Clears the corresponding cache * * @param o - Object to store */ public void store(Object o) { if (o instanceof List) { throw new RuntimeException("Lists need to be stored with storeList"); } Class<?> type = getRealClass(o.getClass()); final boolean isNew = getId(o) == null; if (!isAnnotationPresentInHierarchy(type, NoProtection.class)) { //o.getClass().isAnnotationPresent(NoProtection.class)) { if (isNew) { if (accessDenied(o, Permission.INSERT)) { throw new SecurityException("Insert of new Object denied!"); } } else { if (accessDenied(o, Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } } firePreStoreEvent(o, isNew); Cache cc = getAnnotationFromHierarchy(type, Cache.class);//o.getClass().getAnnotation(Cache.class); if (cc == null || isAnnotationPresentInHierarchy(o.getClass(), NoCache.class) || !cc.writeCache()) { config.getWriter().store(o); firePostStoreEvent(o, isNew); return; } final Object fo = o; writers.execute(new Runnable() { @Override public void run() { config.getWriter().store(fo); firePostStoreEvent(fo, isNew); } }); inc(StatisticKeys.WRITES_CACHED); } public <T> void storeList(List<T> lst) { //have to sort list - might have different objects List<T> storeDirect = new ArrayList<T>(); final List<T> storeInBg = new ArrayList<T>(); //checking permission - might take some time ;-( for (T o : lst) { if (getId(o) == null) { if (accessDenied(o, Permission.INSERT)) { throw new SecurityException("Insert of new Object denied!"); } } else { if (accessDenied(o, Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } Cache c = getAnnotationFromHierarchy(o.getClass(), Cache.class);//o.getClass().getAnnotation(Cache.class); if (isAnnotationPresentInHierarchy(o.getClass(), NoCache.class) || c == null || !c.writeCache()) { storeDirect.add(o); } else { storeDirect.add(o); } } writers.execute(new Runnable() { @Override public void run() { callLifecycleMethod(PreStore.class, storeInBg); config.getWriter().store(storeInBg); callLifecycleMethod(PostStore.class, storeInBg); } }); callLifecycleMethod(PreStore.class, storeDirect); config.getWriter().store(storeDirect); callLifecycleMethod(PostStore.class, storeDirect); } public void delete(Query o) { if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) { if (accessDenied(o, Permission.DELETE)) { throw new SecurityException("Deletion of Object denied!"); } } callLifecycleMethod(PreRemove.class, o); firePreRemoveEvent(o); Cache cc = getAnnotationFromHierarchy(o.getType(), Cache.class);//o.getClass().getAnnotation(Cache.class); if (cc == null || isAnnotationPresentInHierarchy(o.getType(), NoCache.class) || !cc.writeCache()) { config.getWriter().delete(o); callLifecycleMethod(PostRemove.class, o); firePostRemoveEvent(o); return; } final Query fo = o; writers.execute(new Runnable() { @Override public void run() { config.getWriter().delete(fo); firePostRemoveEvent(fo); } }); inc(StatisticKeys.WRITES_CACHED); firePostRemoveEvent(o); } /** * deletes a single object from morphium backend. Clears cache * * @param o */ public void delete(Object o) { if (o instanceof Query) { delete((Query) o); return; } o = getRealObject(o); if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) { if (accessDenied(o, Permission.DELETE)) { throw new SecurityException("Deletion of Object denied!"); } } firePreRemoveEvent(o); Cache cc = getAnnotationFromHierarchy(o.getClass(), Cache.class);//o.getClass().getAnnotation(Cache.class); if (cc == null || isAnnotationPresentInHierarchy(o.getClass(), NoCache.class) || !cc.writeCache()) { config.getWriter().store(o); firePostRemoveEvent(o); return; } final Object fo = o; writers.execute(new Runnable() { @Override public void run() { config.getWriter().delete(fo); firePostRemoveEvent(fo); } }); inc(StatisticKeys.WRITES_CACHED); } public void resetCache() { setCache(new Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>()); } public void setCache(Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cache) { this.cache = cache; } ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////// /////////////// Statistics ///////// ///// /// public Map<String, Double> getStatistics() { return new Statistics(this); } public void removeEntryFromCache(Class cls, ObjectId id) { Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> c = cloneCache(); Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idc = cloneIdCache(); idc.get(cls).remove(id); ArrayList<String> toRemove = new ArrayList<String>(); for (String key : c.get(cls).keySet()) { for (Object el : c.get(cls).get(key).getFound()) { ObjectId lid = config.getMapper().getId(el); if (lid == null) { logger.error("Null id in CACHE?"); toRemove.add(key); } if (lid.equals(id)) { toRemove.add(key); } } } for (String k : toRemove) { c.get(cls).remove(k); } setCache(c); setIdCache(idc); } public Map<StatisticKeys, StatisticValue> getStats() { return stats; } public void addShutdownListener(ShutdownListener l) { shutDownListeners.add(l); } public void removeShutdownListener(ShutdownListener l) { shutDownListeners.remove(l); } public void close() { cacheHousekeeper.end(); for (ShutdownListener l : shutDownListeners) { l.onShutdown(this); } try { Thread.sleep(1000); //give it time to end ;-) } catch (Exception e) { logger.debug("Ignoring interrupted-exception"); } if (cacheHousekeeper.isAlive()) { cacheHousekeeper.interrupt(); } database = null; config = null; mongo.close(); MorphiumSingleton.reset(); } public String createCamelCase(String n) { return config.getMapper().createCamelCase(n, false); } public boolean isWriteCached(Class<?> cls) { Cache c = getAnnotationFromHierarchy(cls, Cache.class); if (isAnnotationPresentInHierarchy(cls, NoCache.class) || c == null || !c.writeCache()) { return false; } return true; } public <T, R> Aggregator<T, R> createAggregator(Class<T> type, Class<R> resultType) { Aggregator<T, R> aggregator = config.getAggregatorFactory().createAggregator(type, resultType); aggregator.setMorphium(this); return aggregator; } public <T, R> List<R> aggregate(Aggregator<T, R> a) { DBCollection coll = database.getCollection(config.getMapper().getCollectionName(a.getSearchType())); List<DBObject> agList = a.toAggregationList(); DBObject first = agList.get(0); agList.remove(0); AggregationOutput resp = coll.aggregate(first, agList.toArray(new DBObject[agList.size()])); List<R> ret = new ArrayList<R>(); for (DBObject o : resp.results()) { ret.add(getMapper().unmarshall(a.getResultType(), o)); } return ret; } /** * create a proxy object, implementing the ParitallyUpdateable Interface * these objects will be updated in mongo by only changing altered fields * <b>Attention:</b> the field name if determined by the setter name for now. That means, it does not honor the @Property-Annotation!!! * To make sure, you take the correct field - use the UpdatingField-Annotation for the setters! * * @param o * @param <T> * @return */ public <T> T createPartiallyUpdateableEntity(T o) { return (T) Enhancer.create(o.getClass(), new Class[]{PartiallyUpdateable.class, Serializable.class}, new PartiallyUpdateableProxy(this, o)); } public <T> T createLazyLoadedEntity(Class<T> cls, ObjectId id) { return (T) Enhancer.create(cls, new Class[]{Serializable.class}, new LazyDeReferencingProxy(this, cls, id)); } public <T> MongoField<T> createMongoField() { try { return (MongoField<T>) config.getFieldImplClass().newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public String getLastChangeField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastChange.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getLastChangeByField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastChangeBy.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getLastAccessField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastAccess.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getLastAccessByField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastAccessBy.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getCreationTimeField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null; List<String> lst = config.getMapper().getFields(cls, CreationTime.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getCreatedByField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null; List<String> lst = config.getMapper().getFields(cls, CreatedBy.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } ////////////////////////////////////////////////////// ////////// SecuritySettings /////// ///// //// /// // public MongoSecurityManager getSecurityManager() { return config.getSecurityMgr(); } /** * temporarily switch off security settings - needed by SecurityManagers */ public void setPrivileged() { privileged.add(Thread.currentThread()); } public boolean checkAccess(String domain, Permission p) throws MongoSecurityException { if (privileged.contains(Thread.currentThread())) { privileged.remove(Thread.currentThread()); return true; } return getSecurityManager().checkAccess(domain, p); } public boolean accessDenied(Class<?> cls, Permission p) throws MongoSecurityException { if (isAnnotationPresentInHierarchy(cls, NoProtection.class)) { return false; } if (privileged.contains(Thread.currentThread())) { privileged.remove(Thread.currentThread()); return false; } return !getSecurityManager().checkAccess(cls, p); } public boolean accessDenied(Object r, Permission p) throws MongoSecurityException { if (isAnnotationPresentInHierarchy(r.getClass(), NoProtection.class)) { return false; } if (privileged.contains(Thread.currentThread())) { privileged.remove(Thread.currentThread()); return false; } return !getSecurityManager().checkAccess(config.getMapper().getRealObject(r), p); } }
public void callLifecycleMethod(Class<? extends Annotation> type, Object on) { if (on == null) return; //No synchronized block - might cause the methods to be put twice into the //hashtabel - but for performance reasons, it's ok... Class<?> cls = on.getClass(); //No Lifecycle annotation - no method calling if (!isAnnotationPresentInHierarchy(cls, Lifecycle.class)) {//cls.isAnnotationPresent(Lifecycle.class)) { return; } //Already stored - should not change during runtime if (lifeCycleMethods.get(cls) != null) { if (lifeCycleMethods.get(cls).get(type) != null) { try { lifeCycleMethods.get(cls).get(type).invoke(on); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } return; } Map<Class<? extends Annotation>, Method> methods = new HashMap<Class<? extends Annotation>, Method>(); //Methods must be public for (Method m : cls.getMethods()) { for (Annotation a : m.getAnnotations()) { methods.put(a.annotationType(), m); } } lifeCycleMethods.put(cls, methods); if (methods.get(type) != null) { try { methods.get(type).invoke(on); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } } } /** * careful this actually changes the parameter o! * * @param o * @param <T> * @return */ public <T> T reread(T o) { if (o == null) throw new RuntimeException("Cannot re read null!"); ObjectId id = getId(o); if (id == null) { return null; } DBCollection col = database.getCollection(getConfig().getMapper().getCollectionName(o.getClass())); BasicDBObject srch = new BasicDBObject("_id", id); DBCursor crs = col.find(srch).limit(1); if (crs.hasNext()) { DBObject dbo = crs.next(); Object fromDb = getConfig().getMapper().unmarshall(o.getClass(), dbo); List<String> flds = getFields(o.getClass()); for (String f : flds) { Field fld = getConfig().getMapper().getField(o.getClass(), f); if (java.lang.reflect.Modifier.isStatic(fld.getModifiers())) { continue; } try { fld.set(o, fld.get(fromDb)); } catch (IllegalAccessException e) { logger.error("Could not set Value: " + fld); } } firePostLoadEvent(o); } else { logger.info("Did not find object with id " + id); return null; } return o; } public void firePreStoreEvent(Object o, boolean isNew) { if (o == null) return; for (MorphiumStorageListener l : listeners) { l.preStore(o, isNew); } callLifecycleMethod(PreStore.class, o); } public void firePostStoreEvent(Object o, boolean isNew) { for (MorphiumStorageListener l : listeners) { l.postStore(o, isNew); } callLifecycleMethod(PostStore.class, o); //existing object => store last Access, if needed } public void firePreDropEvent(Class cls) { for (MorphiumStorageListener l : listeners) { l.preDrop(cls); } } public void firePostDropEvent(Class cls) { for (MorphiumStorageListener l : listeners) { l.postDrop(cls); } } public void firePostUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) { for (MorphiumStorageListener l : listeners) { l.postUpdate(cls, t); } } public void firePreUpdateEvent(Class cls, MorphiumStorageListener.UpdateTypes t) { for (MorphiumStorageListener l : listeners) { l.preUpdate(cls, t); } } public void firePostRemoveEvent(Object o) { for (MorphiumStorageListener l : listeners) { l.postRemove(o); } callLifecycleMethod(PostRemove.class, o); } public void firePostRemoveEvent(Query q) { for (MorphiumStorageListener l : listeners) { l.postRemove(q); } //TODO: FIX - Cannot call lifecycle method here } public void firePreRemoveEvent(Object o) { for (MorphiumStorageListener l : listeners) { l.preDelete(o); } callLifecycleMethod(PreRemove.class, o); } public void firePreRemoveEvent(Query q) { for (MorphiumStorageListener l : listeners) { l.preRemove(q); } //TODO: Fix - cannot call lifecycle method } /** * will be called by query after unmarshalling * * @param o */ public void firePostLoadEvent(Object o) { for (MorphiumStorageListener l : listeners) { l.postLoad(o); } callLifecycleMethod(PostLoad.class, o); } /** * same as retReplicaSetStatus(false); * * @return */ public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus() { return getReplicaSetStatus(false); } /** * get the current replicaset status - issues the replSetGetStatus command to mongo * if full==true, also the configuration is read. This method is called with full==false for every write in * case a Replicaset is configured to find out the current number of active nodes * * @param full * @return */ public de.caluga.morphium.replicaset.ReplicaSetStatus getReplicaSetStatus(boolean full) { if (config.getMode().equals(MongoDbMode.REPLICASET)) { try { CommandResult res = getMongo().getDB("admin").command("replSetGetStatus"); de.caluga.morphium.replicaset.ReplicaSetStatus status = getConfig().getMapper().unmarshall(de.caluga.morphium.replicaset.ReplicaSetStatus.class, res); if (full) { DBCursor rpl = getMongo().getDB("local").getCollection("system.replset").find(); DBObject stat = rpl.next(); //should only be one, i think ReplicaSetConf cfg = getConfig().getMapper().unmarshall(ReplicaSetConf.class, stat); List<Object> mem = cfg.getMemberList(); List<ConfNode> cmembers = new ArrayList<ConfNode>(); for (Object o : mem) { DBObject dbo = (DBObject) o; ConfNode cn = getConfig().getMapper().unmarshall(ConfNode.class, dbo); cmembers.add(cn); } cfg.setMembers(cmembers); status.setConfig(cfg); } //de-referencing list List lst = status.getMembers(); List<ReplicaSetNode> members = new ArrayList<ReplicaSetNode>(); for (Object l : lst) { DBObject o = (DBObject) l; ReplicaSetNode n = getConfig().getMapper().unmarshall(ReplicaSetNode.class, o); members.add(n); } status.setMembers(members); return status; } catch (Exception e) { logger.error("Could not get Replicaset status", e); } } return null; } public boolean isReplicaSet() { return config.getMode().equals(MongoDbMode.REPLICASET); } public WriteConcern getWriteConcernForClass(Class<?> cls) { if (logger.isDebugEnabled()) logger.debug("returning write concern for " + cls.getSimpleName()); WriteSafety safety = getAnnotationFromHierarchy(cls, WriteSafety.class); // cls.getAnnotation(WriteSafety.class); if (safety == null) return null; boolean fsync = safety.waitForSync(); boolean j = safety.waitForJournalCommit(); if (j && fsync) { fsync = false; } int w = safety.level().getValue(); if (!isReplicaSet() && w > 1) { w = 1; } int timeout = safety.timeout(); if (isReplicaSet() && w > 2) { de.caluga.morphium.replicaset.ReplicaSetStatus s = getReplicaSetStatus(); if (s == null || s.getActiveNodes() == 0) { logger.warn("ReplicaSet status is null or no node active! Assuming default write concern"); return null; } if (logger.isDebugEnabled()) logger.debug("Active nodes now: " + s.getActiveNodes()); int activeNodes = s.getActiveNodes(); if (timeout == 0) { if (getConfig().getConnectionTimeout() == 0) { if (logger.isDebugEnabled()) logger.debug("Not waiting for all slaves withoug timeout - unfortunately no connection timeout set in config - setting to 10s, Type: " + cls.getSimpleName()); timeout = 10000; } else { if (logger.isDebugEnabled()) logger.debug("Not waiting for all slaves without timeout - could cause deadlock. Setting to connectionTimeout value, Type: " + cls.getSimpleName()); timeout = getConfig().getConnectionTimeout(); } } //Wait for all active slaves w = activeNodes; } // if (w==0) { // return WriteConcern.NONE; // } // if(w==1) { // return WriteConcern.FSYNC_SAFE; // } // if (w==2) { // return WriteConcern.JOURNAL_SAFE; // } // if (w==3) { // return WriteConcern.REPLICAS_SAFE; // } if (w == -99) { return new WriteConcern("majority", timeout, fsync, j); } return new WriteConcern(w, timeout, fsync, j); } public void addProfilingListener(ProfilingListener l) { profilingListeners.add(l); } public void removeProfilingListener(ProfilingListener l) { profilingListeners.remove(l); } public void fireProfilingWriteEvent(Class type, Object data, long time, boolean isNew, WriteAccessType wt) { for (ProfilingListener l : profilingListeners) { try { l.writeAccess(type, data, time, isNew, wt); } catch (Throwable e) { logger.error("Error during profiling: ", e); } } } public void fireProfilingReadEvent(Query q, long time, ReadAccessType t) { for (ProfilingListener l : profilingListeners) { try { l.readAccess(q, time, t); } catch (Throwable e) { logger.error("Error during profiling", e); } } } public boolean isCached(Class<? extends Object> type, String k) { Cache c = getAnnotationFromHierarchy(type, Cache.class); ///type.getAnnotation(Cache.class); if (c != null) { if (!c.readCache()) return false; } else { return false; } return cache.get(type) != null && cache.get(type).get(k) != null && cache.get(type).get(k).getFound() != null; } /** * return object by from cache. Cache key usually is the string-representation of the search * query.toQueryObject() * * @param type * @param k * @param <T> * @return */ public <T> List<T> getFromCache(Class<T> type, String k) { if (cache.get(type) == null || cache.get(type).get(k) == null) return null; final CacheElement cacheElement = cache.get(type).get(k); cacheElement.setLru(System.currentTimeMillis()); return cacheElement.getFound(); } public Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cloneCache() { return (Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>) cache.clone(); } public Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> cloneIdCache() { return (Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>>) idCache.clone(); } /** * issues a delete command - no lifecycle methods calles, no drop, keeps all indexec this way * * @param cls */ public void clearCollection(Class<? extends Object> cls) { if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { //cls.isAnnotationPresent(NoProtection.class)) { try { if (accessDenied(cls.newInstance(), Permission.DROP)) { throw new SecurityException("Drop / clear of Collection denied!"); } } catch (InstantiationException ex) { Logger.getLogger(Morphium.class).error(ex); } catch (IllegalAccessException ex) { Logger.getLogger(Morphium.class).error(ex); } } firePreDropEvent(cls); delete(createQueryFor(cls)); firePostDropEvent(cls); } /** * clears every single object in collection - reads ALL objects to do so * this way Lifecycle methods can be called! * * @param cls */ public void clearCollectionOneByOne(Class<? extends Object> cls) { if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { //cls.isAnnotationPresent(NoProtection.class)) { try { if (accessDenied(cls.newInstance(), Permission.DROP)) { throw new SecurityException("Drop / clear of Collection denied!"); } } catch (InstantiationException ex) { Logger.getLogger(Morphium.class).error(ex); } catch (IllegalAccessException ex) { Logger.getLogger(Morphium.class).error(ex); } } inc(StatisticKeys.WRITES); List<? extends Object> lst = readAll(cls); for (Object r : lst) { delete(r); } clearCacheIfNecessary(cls); } /** * return a list of all elements stored in morphium for this type * * @param cls - type to search for, needs to be an Property * @param <T> - Type * @return - list of all elements stored */ public <T> List<T> readAll(Class<T> cls) { inc(StatisticKeys.READS); Query<T> qu; qu = createQueryFor(cls); return qu.asList(); } public <T> Query<T> createQueryFor(Class<T> type) { Query<T> q = config.getQueryFact().createQuery(this, type); q.setMorphium(this); return q; } public <T> List<T> find(Query<T> q) { return q.asList(); } private <T> T getFromIDCache(Class<T> type, ObjectId id) { if (idCache.get(type) != null) { return (T) idCache.get(type).get(id); } return null; } public List<Object> distinct(Enum key, Class c) { return distinct(key.name(), c); } /** * returns a distinct list of values of the given collection * Attention: these values are not unmarshalled, you might get MongoDBObjects */ public List<Object> distinct(Enum key, Query q) { return distinct(key.name(), q); } /** * returns a distinct list of values of the given collection * Attention: these values are not unmarshalled, you might get MongoDBObjects */ public List<Object> distinct(String key, Query q) { return database.getCollection(config.getMapper().getCollectionName(q.getType())).distinct(key, q.toQueryObject()); } public List<Object> distinct(String key, Class cls) { DBCollection collection = database.getCollection(config.getMapper().getCollectionName(cls)); setReadPreference(collection, cls); return collection.distinct(key, new BasicDBObject()); } private void setReadPreference(DBCollection c, Class type) { DefaultReadPreference pr = getAnnotationFromHierarchy(type, DefaultReadPreference.class); if (pr != null) { c.setReadPreference(pr.value().getPref()); } else { c.setReadPreference(null); } } public DBObject group(Query q, Map<String, Object> initial, String jsReduce, String jsFinalize, String... keys) { BasicDBObject k = new BasicDBObject(); BasicDBObject ini = new BasicDBObject(); ini.putAll(initial); for (String ks : keys) { if (ks.startsWith("-")) { k.append(ks.substring(1), "false"); } else if (ks.startsWith("+")) { k.append(ks.substring(1), "true"); } else { k.append(ks, "true"); } } if (!jsReduce.trim().startsWith("function(")) { jsReduce = "function (obj,data) { " + jsReduce + " }"; } if (jsFinalize == null) { jsFinalize = ""; } if (!jsFinalize.trim().startsWith("function(")) { jsFinalize = "function (data) {" + jsFinalize + "}"; } GroupCommand cmd = new GroupCommand(database.getCollection(config.getMapper().getCollectionName(q.getType())), k, q.toQueryObject(), ini, jsReduce, jsFinalize); return database.getCollection(config.getMapper().getCollectionName(q.getType())).group(cmd); } public <T> T findById(Class<T> type, ObjectId id) { T ret = getFromIDCache(type, id); if (ret != null) return ret; List<String> ls = config.getMapper().getFields(type, Id.class); if (ls.size() == 0) throw new RuntimeException("Cannot find by ID on non-Entity"); return (T) createQueryFor(type).f(ls.get(0)).eq(id).get(); } // /** // * returns a list of all elements for the given type, matching the given query // * @param qu - the query to search // * @param <T> - type of the elementyx // * @return - list of elements matching query // */ // public <T> List<T> readAll(Query<T> qu) { // inc(StatisticKeys.READS); // if (qu.getEntityClass().isAnnotationPresent(Cache.class)) { // if (isCached(qu.getEntityClass(), qu.toString())) { // inc(StatisticKeys.CHITS); // return getFromCache(qu.getEntityClass(), qu.toString()); // } else { // inc(StatisticKeys.CMISS); // } // } // List<T> lst = qu.asList(); // addToCache(qu.toString()+" / l:"+((QueryImpl)qu).getLimit()+" o:"+((QueryImpl)qu).getOffset(), qu.getEntityClass(), lst); // return lst; // // } /** * does not set values in DB only in the entity * * @param toSetValueIn */ public void setValueIn(Object toSetValueIn, String fld, Object value) { config.getMapper().setValue(toSetValueIn, value, fld); } public void setValueIn(Object toSetValueIn, Enum fld, Object value) { config.getMapper().setValue(toSetValueIn, value, fld.name()); } public Object getValueOf(Object toGetValueFrom, String fld) { return config.getMapper().getValue(toGetValueFrom, fld); } public Object getValueOf(Object toGetValueFrom, Enum fld) { return config.getMapper().getValue(toGetValueFrom, fld.name()); } @SuppressWarnings("unchecked") public <T> List<T> findByField(Class<T> cls, String fld, Object val) { Query<T> q = createQueryFor(cls); q = q.f(fld).eq(val); return q.asList(); // return createQueryFor(cls).field(fld).equal(val).asList(); } public <T> List<T> findByField(Class<T> cls, Enum fld, Object val) { Query<T> q = createQueryFor(cls); q = q.f(fld).eq(val); return q.asList(); // return createQueryFor(cls).field(fld).equal(val).asList(); } /** * get a list of valid fields of a given record as they are in the MongoDB * so, if you have a field Mapping, the mapped Property-name will be used * * @param cls * @return */ public final List<String> getFields(Class cls) { return config.getMapper().getFields(cls); } public final Class getTypeOfField(Class cls, String fld) { Field f = getField(cls, fld); if (f == null) return null; return f.getType(); } public boolean storesLastChange(Class<? extends Object> cls) { return isAnnotationPresentInHierarchy(cls, StoreLastChange.class); } public boolean storesLastAccess(Class<? extends Object> cls) { return isAnnotationPresentInHierarchy(cls, StoreLastAccess.class); } public boolean storesCreation(Class<? extends Object> cls) { return isAnnotationPresentInHierarchy(cls, StoreCreationTime.class); } public String getFieldName(Class cls, String fld) { return config.getMapper().getFieldName(cls, fld); } /** * extended logic: Fld may be, the java field name, the name of the specified value in Property-Annotation or * the translated underscored lowercase name (mongoId => mongo_id) * * @param cls - class to search * @param fld - field name * @return field, if found, null else */ public Field getField(Class cls, String fld) { return config.getMapper().getField(cls, fld); } public void setValue(Object in, String fld, Object val) { config.getMapper().setValue(in, val, fld); } public Object getValue(Object o, String fld) { return config.getMapper().getValue(o, fld); } public Long getLongValue(Object o, String fld) { return (Long) getValue(o, fld); } public String getStringValue(Object o, String fld) { return (String) getValue(o, fld); } public Date getDateValue(Object o, String fld) { return (Date) getValue(o, fld); } public Double getDoubleValue(Object o, String fld) { return (Double) getValue(o, fld); } /** * Erase cache entries for the given type. is being called after every store * depending on cache settings! * * @param cls */ public void clearCachefor(Class<? extends Object> cls) { if (cache.get(cls) != null) { cache.get(cls).clear(); } if (idCache.get(cls) != null) { idCache.get(cls).clear(); } //clearCacheFor(cls); } public void storeNoCache(Object lst) { config.getWriter().store(lst); } public void storeInBackground(final Object lst) { inc(StatisticKeys.WRITES_CACHED); writers.execute(new Runnable() { @Override public void run() { boolean isNew = getId(lst) == null; firePreStoreEvent(lst, isNew); config.getWriter().store(lst); firePostStoreEvent(lst, isNew); } }); } public ObjectId getId(Object o) { return config.getMapper().getId(o); } public void dropCollection(Class<? extends Object> cls) { if (!isAnnotationPresentInHierarchy(cls, NoProtection.class)) { try { if (accessDenied(cls.newInstance(), Permission.DROP)) { throw new SecurityException("Drop of Collection denied!"); } } catch (InstantiationException ex) { Logger.getLogger(Morphium.class.getName()).fatal(ex); } catch (IllegalAccessException ex) { Logger.getLogger(Morphium.class.getName()).fatal(ex); } } if (config.getMode() == MongoDbMode.REPLICASET && config.getAdr().size() > 1) { //replicaset logger.warn("Cannot drop collection for class " + cls.getSimpleName() + " as we're in a clustered environment (Driver 2.8.0)"); clearCollection(cls); return; } if (isAnnotationPresentInHierarchy(cls, Entity.class)) { firePreDropEvent(cls); long start = System.currentTimeMillis(); // Entity entity = getAnnotationFromHierarchy(cls, Entity.class); //cls.getAnnotation(Entity.class); DBCollection coll = database.getCollection(config.getMapper().getCollectionName(cls)); // coll.setReadPreference(com.mongodb.ReadPreference.PRIMARY); coll.drop(); long dur = System.currentTimeMillis() - start; fireProfilingWriteEvent(cls, null, dur, false, WriteAccessType.DROP); firePostDropEvent(cls); } else { throw new RuntimeException("No entity class: " + cls.getName()); } } public void ensureIndex(Class<?> cls, Map<String, Integer> index) { List<String> fields = getFields(cls); Map<String, Integer> idx = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> es : index.entrySet()) { String k = es.getKey(); if (!fields.contains(k) && !fields.contains(config.getMapper().convertCamelCase(k))) { throw new IllegalArgumentException("Field unknown for type " + cls.getSimpleName() + ": " + k); } String fn = config.getMapper().getFieldName(cls, k); idx.put(fn, es.getValue()); } long start = System.currentTimeMillis(); database.getCollection(config.getMapper().getCollectionName(cls)).ensureIndex(new BasicDBObject(idx)); long dur = System.currentTimeMillis() - start; fireProfilingWriteEvent(cls, new BasicDBObject(idx), dur, false, WriteAccessType.ENSURE_INDEX); } /** * ensureIndex(CachedObject.class,"counter","-value"); * Similar to sorting * * @param cls * @param fldStr */ public void ensureIndex(Class<?> cls, String... fldStr) { Map<String, Integer> m = new LinkedHashMap<String, Integer>(); for (String f : fldStr) { int idx = 1; if (f.startsWith("-")) { idx = -1; f = f.substring(1); } else if (f.startsWith("+")) { f = f.substring(1); } m.put(f, idx); } ensureIndex(cls, m); } public void ensureIndex(Class<?> cls, Enum... fldStr) { Map<String, Integer> m = new LinkedHashMap<String, Integer>(); for (Enum e : fldStr) { String f = e.name(); m.put(f, 1); } ensureIndex(cls, m); } /** * Stores a single Object. Clears the corresponding cache * * @param o - Object to store */ public void store(Object o) { if (o instanceof List) { throw new RuntimeException("Lists need to be stored with storeList"); } Class<?> type = getRealClass(o.getClass()); final boolean isNew = getId(o) == null; if (!isAnnotationPresentInHierarchy(type, NoProtection.class)) { //o.getClass().isAnnotationPresent(NoProtection.class)) { if (isNew) { if (accessDenied(o, Permission.INSERT)) { throw new SecurityException("Insert of new Object denied!"); } } else { if (accessDenied(o, Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } } firePreStoreEvent(o, isNew); Cache cc = getAnnotationFromHierarchy(type, Cache.class);//o.getClass().getAnnotation(Cache.class); if (cc == null || isAnnotationPresentInHierarchy(o.getClass(), NoCache.class) || !cc.writeCache()) { config.getWriter().store(o); firePostStoreEvent(o, isNew); return; } final Object fo = o; writers.execute(new Runnable() { @Override public void run() { config.getWriter().store(fo); firePostStoreEvent(fo, isNew); } }); inc(StatisticKeys.WRITES_CACHED); } public <T> void storeList(List<T> lst) { //have to sort list - might have different objects List<T> storeDirect = new ArrayList<T>(); final List<T> storeInBg = new ArrayList<T>(); //checking permission - might take some time ;-( for (T o : lst) { if (getId(o) == null) { if (accessDenied(o, Permission.INSERT)) { throw new SecurityException("Insert of new Object denied!"); } } else { if (accessDenied(o, Permission.UPDATE)) { throw new SecurityException("Update of Object denied!"); } } Cache c = getAnnotationFromHierarchy(o.getClass(), Cache.class);//o.getClass().getAnnotation(Cache.class); if (isAnnotationPresentInHierarchy(o.getClass(), NoCache.class) || c == null || !c.writeCache()) { storeDirect.add(o); } else { storeDirect.add(o); } } writers.execute(new Runnable() { @Override public void run() { callLifecycleMethod(PreStore.class, storeInBg); config.getWriter().store(storeInBg); callLifecycleMethod(PostStore.class, storeInBg); } }); callLifecycleMethod(PreStore.class, storeDirect); config.getWriter().store(storeDirect); callLifecycleMethod(PostStore.class, storeDirect); } public void delete(Query o) { if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) { if (accessDenied(o, Permission.DELETE)) { throw new SecurityException("Deletion of Object denied!"); } } callLifecycleMethod(PreRemove.class, o); firePreRemoveEvent(o); Cache cc = getAnnotationFromHierarchy(o.getType(), Cache.class);//o.getClass().getAnnotation(Cache.class); if (cc == null || isAnnotationPresentInHierarchy(o.getType(), NoCache.class) || !cc.writeCache()) { config.getWriter().delete(o); callLifecycleMethod(PostRemove.class, o); firePostRemoveEvent(o); return; } final Query fo = o; writers.execute(new Runnable() { @Override public void run() { config.getWriter().delete(fo); firePostRemoveEvent(fo); } }); inc(StatisticKeys.WRITES_CACHED); firePostRemoveEvent(o); } /** * deletes a single object from morphium backend. Clears cache * * @param o */ public void delete(Object o) { if (o instanceof Query) { delete((Query) o); return; } o = getRealObject(o); if (!isAnnotationPresentInHierarchy(o.getClass(), NoProtection.class)) { if (accessDenied(o, Permission.DELETE)) { throw new SecurityException("Deletion of Object denied!"); } } firePreRemoveEvent(o); Cache cc = getAnnotationFromHierarchy(o.getClass(), Cache.class);//o.getClass().getAnnotation(Cache.class); if (cc == null || isAnnotationPresentInHierarchy(o.getClass(), NoCache.class) || !cc.writeCache()) { config.getWriter().delete(o); firePostRemoveEvent(o); return; } final Object fo = o; writers.execute(new Runnable() { @Override public void run() { config.getWriter().delete(fo); firePostRemoveEvent(fo); } }); inc(StatisticKeys.WRITES_CACHED); } public void resetCache() { setCache(new Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>>()); } public void setCache(Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> cache) { this.cache = cache; } ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////// /////////////// Statistics ///////// ///// /// public Map<String, Double> getStatistics() { return new Statistics(this); } public void removeEntryFromCache(Class cls, ObjectId id) { Hashtable<Class<? extends Object>, Hashtable<String, CacheElement>> c = cloneCache(); Hashtable<Class<? extends Object>, Hashtable<ObjectId, Object>> idc = cloneIdCache(); idc.get(cls).remove(id); ArrayList<String> toRemove = new ArrayList<String>(); for (String key : c.get(cls).keySet()) { for (Object el : c.get(cls).get(key).getFound()) { ObjectId lid = config.getMapper().getId(el); if (lid == null) { logger.error("Null id in CACHE?"); toRemove.add(key); } if (lid.equals(id)) { toRemove.add(key); } } } for (String k : toRemove) { c.get(cls).remove(k); } setCache(c); setIdCache(idc); } public Map<StatisticKeys, StatisticValue> getStats() { return stats; } public void addShutdownListener(ShutdownListener l) { shutDownListeners.add(l); } public void removeShutdownListener(ShutdownListener l) { shutDownListeners.remove(l); } public void close() { cacheHousekeeper.end(); for (ShutdownListener l : shutDownListeners) { l.onShutdown(this); } try { Thread.sleep(1000); //give it time to end ;-) } catch (Exception e) { logger.debug("Ignoring interrupted-exception"); } if (cacheHousekeeper.isAlive()) { cacheHousekeeper.interrupt(); } database = null; config = null; mongo.close(); MorphiumSingleton.reset(); } public String createCamelCase(String n) { return config.getMapper().createCamelCase(n, false); } public boolean isWriteCached(Class<?> cls) { Cache c = getAnnotationFromHierarchy(cls, Cache.class); if (isAnnotationPresentInHierarchy(cls, NoCache.class) || c == null || !c.writeCache()) { return false; } return true; } public <T, R> Aggregator<T, R> createAggregator(Class<T> type, Class<R> resultType) { Aggregator<T, R> aggregator = config.getAggregatorFactory().createAggregator(type, resultType); aggregator.setMorphium(this); return aggregator; } public <T, R> List<R> aggregate(Aggregator<T, R> a) { DBCollection coll = database.getCollection(config.getMapper().getCollectionName(a.getSearchType())); List<DBObject> agList = a.toAggregationList(); DBObject first = agList.get(0); agList.remove(0); AggregationOutput resp = coll.aggregate(first, agList.toArray(new DBObject[agList.size()])); List<R> ret = new ArrayList<R>(); for (DBObject o : resp.results()) { ret.add(getMapper().unmarshall(a.getResultType(), o)); } return ret; } /** * create a proxy object, implementing the ParitallyUpdateable Interface * these objects will be updated in mongo by only changing altered fields * <b>Attention:</b> the field name if determined by the setter name for now. That means, it does not honor the @Property-Annotation!!! * To make sure, you take the correct field - use the UpdatingField-Annotation for the setters! * * @param o * @param <T> * @return */ public <T> T createPartiallyUpdateableEntity(T o) { return (T) Enhancer.create(o.getClass(), new Class[]{PartiallyUpdateable.class, Serializable.class}, new PartiallyUpdateableProxy(this, o)); } public <T> T createLazyLoadedEntity(Class<T> cls, ObjectId id) { return (T) Enhancer.create(cls, new Class[]{Serializable.class}, new LazyDeReferencingProxy(this, cls, id)); } public <T> MongoField<T> createMongoField() { try { return (MongoField<T>) config.getFieldImplClass().newInstance(); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } public String getLastChangeField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastChange.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getLastChangeByField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastChange.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastChangeBy.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getLastAccessField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastAccess.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getLastAccessByField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreLastAccess.class)) return null; List<String> lst = config.getMapper().getFields(cls, LastAccessBy.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getCreationTimeField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null; List<String> lst = config.getMapper().getFields(cls, CreationTime.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } public String getCreatedByField(Class<?> cls) { if (!isAnnotationPresentInHierarchy(cls, StoreCreationTime.class)) return null; List<String> lst = config.getMapper().getFields(cls, CreatedBy.class); if (lst == null || lst.isEmpty()) return null; return lst.get(0); } ////////////////////////////////////////////////////// ////////// SecuritySettings /////// ///// //// /// // public MongoSecurityManager getSecurityManager() { return config.getSecurityMgr(); } /** * temporarily switch off security settings - needed by SecurityManagers */ public void setPrivileged() { privileged.add(Thread.currentThread()); } public boolean checkAccess(String domain, Permission p) throws MongoSecurityException { if (privileged.contains(Thread.currentThread())) { privileged.remove(Thread.currentThread()); return true; } return getSecurityManager().checkAccess(domain, p); } public boolean accessDenied(Class<?> cls, Permission p) throws MongoSecurityException { if (isAnnotationPresentInHierarchy(cls, NoProtection.class)) { return false; } if (privileged.contains(Thread.currentThread())) { privileged.remove(Thread.currentThread()); return false; } return !getSecurityManager().checkAccess(cls, p); } public boolean accessDenied(Object r, Permission p) throws MongoSecurityException { if (isAnnotationPresentInHierarchy(r.getClass(), NoProtection.class)) { return false; } if (privileged.contains(Thread.currentThread())) { privileged.remove(Thread.currentThread()); return false; } return !getSecurityManager().checkAccess(config.getMapper().getRealObject(r), p); } }
diff --git a/esmska/src/esmska/gui/ConfigFrame.java b/esmska/src/esmska/gui/ConfigFrame.java index 71936d43..578915d4 100644 --- a/esmska/src/esmska/gui/ConfigFrame.java +++ b/esmska/src/esmska/gui/ConfigFrame.java @@ -1,1079 +1,1079 @@ /* * ConfigFrame.java * * Created on 20. červenec 2007, 18:59 */ package esmska.gui; import com.jgoodies.looks.plastic.PlasticLookAndFeel; import com.jgoodies.looks.plastic.PlasticTheme; import esmska.*; import esmska.data.Config; import esmska.data.CountryPrefix; import esmska.data.Icons; import esmska.data.Keyring; import esmska.operators.Operator; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.event.DocumentEvent; import org.jvnet.substance.SubstanceLookAndFeel; import org.jvnet.substance.skin.SkinInfo; import esmska.persistence.PersistenceManager; import esmska.transfer.ProxyManager; import esmska.utils.AbstractDocumentListener; import esmska.utils.Nullator; import java.awt.Toolkit; import javax.swing.AbstractAction; import javax.swing.InputMap; import javax.swing.InputVerifier; import javax.swing.KeyStroke; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; /** Configure settings form * * @author ripper */ public class ConfigFrame extends javax.swing.JFrame { private static final Logger logger = Logger.getLogger(ConfigFrame.class.getName()); private static final String RES = "/esmska/resources/"; private static final Keyring keyring = PersistenceManager.getKeyring(); /* when to take updates seriously */ private boolean fullyInicialized; private final String LAF_SYSTEM = "Systémový"; private final String LAF_CROSSPLATFORM = "Meziplatformní"; private final String LAF_GTK = "GTK"; private final String LAF_JGOODIES = "JGoodies"; private final String LAF_SUBSTANCE = "Substance"; /* the active LaF when dialog is opened, needed for live-updating LaF skins */ private String lafWhenLoaded; /** Creates new form ConfigFrame */ public ConfigFrame() { initComponents(); //close on Ctrl+W String command = "close"; getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke( KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()), command); getRootPane().getActionMap().put(command, new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { closeButtonActionPerformed(e); } }); //add development panel in development versions if (Config.getLatestVersion().contains("beta")) { tabbedPane.addTab("Devel", develPanel); } tabbedPane.setMnemonicAt(0, KeyEvent.VK_O); tabbedPane.setMnemonicAt(1, KeyEvent.VK_V); tabbedPane.setMnemonicAt(2, KeyEvent.VK_P); tabbedPane.setMnemonicAt(3, KeyEvent.VK_H); tabbedPane.setMnemonicAt(4, KeyEvent.VK_S); tabbedPane.setMnemonicAt(5, KeyEvent.VK_N); tabbedPane.setIconAt(0, new ImageIcon(getClass().getResource(RES + "config-16.png"))); tabbedPane.setIconAt(1, new ImageIcon(getClass().getResource(RES + "appearance-small.png"))); tabbedPane.setIconAt(2, Icons.OPERATOR_DEFAULT); tabbedPane.setIconAt(3, new ImageIcon(getClass().getResource(RES + "keyring-16.png"))); tabbedPane.setIconAt(4, new ImageIcon(getClass().getResource(RES + "lock-16.png"))); tabbedPane.setIconAt(5, new ImageIcon(getClass().getResource(RES + "connection-16.png"))); closeButton.requestFocusInWindow(); lafComboBox.setModel(new DefaultComboBoxModel(new String[] { LAF_SYSTEM, LAF_CROSSPLATFORM, LAF_GTK, LAF_JGOODIES, LAF_SUBSTANCE})); if (config.getLookAndFeel().equals(ThemeManager.LAF_SYSTEM)) lafComboBox.setSelectedItem(LAF_SYSTEM); else if (config.getLookAndFeel().equals(ThemeManager.LAF_CROSSPLATFORM)) lafComboBox.setSelectedItem(LAF_CROSSPLATFORM); else if (config.getLookAndFeel().equals(ThemeManager.LAF_GTK)) lafComboBox.setSelectedItem(LAF_GTK); else if (config.getLookAndFeel().equals(ThemeManager.LAF_JGOODIES)) lafComboBox.setSelectedItem(LAF_JGOODIES); else if (config.getLookAndFeel().equals(ThemeManager.LAF_SUBSTANCE)) lafComboBox.setSelectedItem(LAF_SUBSTANCE); lafWhenLoaded = (String) lafComboBox.getSelectedItem(); updateThemeComboBox(); if (!NotificationIcon.isSupported()) { notificationAreaCheckBox.setSelected(false); } fullyInicialized = true; } /** Update theme according to L&F */ private void updateThemeComboBox() { themeComboBox.setEnabled(false); String laf = (String) lafComboBox.getSelectedItem(); if (laf.equals(LAF_JGOODIES)) { ArrayList<String> themes = new ArrayList<String>(); for (Object o : PlasticLookAndFeel.getInstalledThemes()) themes.add(((PlasticTheme)o).getName()); themeComboBox.setModel(new DefaultComboBoxModel(themes.toArray())); themeComboBox.setSelectedItem(config.getLafJGoodiesTheme()); themeComboBox.setEnabled(true); } else if (laf.equals(LAF_SUBSTANCE)) { ArrayList<String> themes = new ArrayList<String>(); new SubstanceLookAndFeel(); for (SkinInfo skinInfo : SubstanceLookAndFeel.getAllSkins().values()) themes.add(skinInfo.getDisplayName()); themeComboBox.setModel(new DefaultComboBoxModel(themes.toArray())); themeComboBox.setSelectedItem(config.getLafSubstanceSkin()); themeComboBox.setEnabled(true); } } /** Update country code according to country */ private void updateCountryCode() { String countryPrefix = countryPrefixTextField.getText(); String countryCode = CountryPrefix.getCountryCode(countryPrefix); if (Nullator.isEmpty(countryCode)) { countryCodeLabel.setText("(neznámý stát)"); } else { countryCodeLabel.setText("(stát: " + countryCode + ")"); } } /** Reaction for operator key (login, password) change */ private void updateKeyring() { Operator operator = operatorComboBox.getSelectedOperator(); if (operator == null) return; String[] key = new String[]{loginTextField.getText(), new String(passwordField.getPassword())}; if (Nullator.isEmpty(key[0]) && Nullator.isEmpty(key[1])) { //if both empty, remove the key keyring.removeKey(operator.getName()); } else { //else update/set the key keyring.putKey(operator.getName(), key); } } /** Reaction to proxy configuration change */ private void updateProxy() { boolean useProxy = useProxyCheckBox.isSelected(); boolean sameProxy = sameProxyCheckBox.isSelected(); if (useProxy) { if (sameProxy) { ProxyManager.setProxy(httpProxyTextField.getText()); } else { ProxyManager.setProxy(httpProxyTextField.getText(), httpsProxyTextField.getText(), socksProxyTextField.getText()); } } else { ProxyManager.setProxy(null); } } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); config = PersistenceManager.getConfig(); develPanel = new javax.swing.JPanel(); rememberLayoutCheckBox = new javax.swing.JCheckBox(); tabbedPane = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); removeAccentsCheckBox = new javax.swing.JCheckBox(); checkUpdatesCheckBox = new javax.swing.JCheckBox(); jPanel3 = new javax.swing.JPanel(); lafComboBox = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); themeComboBox = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); windowDecorationsCheckBox = new javax.swing.JCheckBox(); windowCenteredCheckBox = new javax.swing.JCheckBox(); toolbarVisibleCheckBox = new javax.swing.JCheckBox(); jLabel5 = new javax.swing.JLabel(); notificationAreaCheckBox = new javax.swing.JCheckBox(); tipsCheckBox = new javax.swing.JCheckBox(); startMinimizedCheckBox = new javax.swing.JCheckBox(); jPanel2 = new javax.swing.JPanel(); useSenderIDCheckBox = new javax.swing.JCheckBox(); senderNumberTextField = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); senderNameTextField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); countryPrefixTextField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); operatorFilterTextField = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); countryCodeLabel = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); operatorComboBox = new esmska.gui.OperatorComboBox(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); loginTextField = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); passwordField = new javax.swing.JPasswordField(); jLabel12 = new javax.swing.JLabel(); clearKeyringButton = new javax.swing.JButton(); jLabel13 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); reducedHistoryCheckBox = new javax.swing.JCheckBox(); reducedHistorySpinner = new javax.swing.JSpinner(); jLabel18 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); useProxyCheckBox = new javax.swing.JCheckBox(); httpProxyTextField = new javax.swing.JTextField(); sameProxyCheckBox = new javax.swing.JCheckBox(); httpsProxyTextField = new javax.swing.JTextField(); socksProxyTextField = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); closeButton = new javax.swing.JButton(); rememberLayoutCheckBox.setMnemonic('r'); rememberLayoutCheckBox.setText("Pamatovat rozvržení formuláře"); rememberLayoutCheckBox.setToolTipText("<html>\nPoužije aktuální rozměry programu a prvků formuláře při příštím spuštění programu\n</html>"); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${rememberLayout}"), rememberLayoutCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); javax.swing.GroupLayout develPanelLayout = new javax.swing.GroupLayout(develPanel); develPanel.setLayout(develPanelLayout); develPanelLayout.setHorizontalGroup( develPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(develPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(rememberLayoutCheckBox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); develPanelLayout.setVerticalGroup( develPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(develPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(rememberLayoutCheckBox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Nastavení - Esmska"); setIconImage(new ImageIcon(getClass().getResource(RES + "config-48.png")).getImage()); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } }); removeAccentsCheckBox.setMnemonic('d'); removeAccentsCheckBox.setText("Ze zpráv odstraňovat diakritiku"); removeAccentsCheckBox.setToolTipText("<html>\nPřed odesláním zprávy z ní odstraní všechna diakritická znaménka\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${removeAccents}"), removeAccentsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); checkUpdatesCheckBox.setMnemonic('n'); checkUpdatesCheckBox.setText("Kontrolovat po startu novou verzi programu"); checkUpdatesCheckBox.setToolTipText("<html>\nPo spuštění programu zkontrolovat, zda nevyšla novější<br>\nverze programu, a případně upozornit ve stavovém řádku\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${checkForUpdates}"), checkUpdatesCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(removeAccentsCheckBox) .addComponent(checkUpdatesCheckBox)) .addContainerGap(352, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(removeAccentsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(checkUpdatesCheckBox) - .addContainerGap(297, Short.MAX_VALUE)) + .addContainerGap(339, Short.MAX_VALUE)) ); tabbedPane.addTab("Obecné", jPanel1); lafComboBox.setToolTipText("<html>\nUmožní vám změnit vzhled programu\n</html>"); lafComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lafComboBoxActionPerformed(evt); } }); jLabel4.setDisplayedMnemonic('d'); jLabel4.setLabelFor(lafComboBox); jLabel4.setText("Vzhled:"); jLabel4.setToolTipText(lafComboBox.getToolTipText()); jLabel7.setText("<html><i>\n* Pro projevení změn je nutný restart programu!\n</i></html>"); themeComboBox.setToolTipText("<html>\nBarevná schémata pro zvolený vzhled\n</html>"); themeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { themeComboBoxActionPerformed(evt); } }); jLabel6.setDisplayedMnemonic('m'); jLabel6.setLabelFor(themeComboBox); jLabel6.setText("Motiv:"); jLabel6.setToolTipText(themeComboBox.getToolTipText()); windowDecorationsCheckBox.setMnemonic('k'); windowDecorationsCheckBox.setText("Použít vzhled i na okraje oken *"); windowDecorationsCheckBox.setToolTipText("<html>\nZda má místo operačního systému vykreslovat<br>\nrámečky oken zvolený vzhled\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${lafWindowDecorated}"), windowDecorationsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); windowCenteredCheckBox.setMnemonic('u'); windowCenteredCheckBox.setText("Spustit program uprostřed obrazovky"); windowCenteredCheckBox.setToolTipText("<html>Zda-li nechat umístění okna programu na operačním systému,<br>\nnebo ho umístit vždy doprostřed obrazovky</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${startCentered}"), windowCenteredCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); toolbarVisibleCheckBox.setMnemonic('n'); toolbarVisibleCheckBox.setText("Zobrazit panel nástrojů"); toolbarVisibleCheckBox.setToolTipText("<html>\nZobrazit panel nástrojů, který umožňuje rychlejší ovládání myší některých akcí\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${toolbarVisible}"), toolbarVisibleCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); jLabel5.setText("*"); notificationAreaCheckBox.setMnemonic('o'); notificationAreaCheckBox.setText("Umístit ikonu do oznamovací oblasti"); notificationAreaCheckBox.setToolTipText("<html>\nZobrazit ikonu v oznamovací oblasti správce oken (tzv. <i>system tray</i>).<br>\n<br>\nPozor, u moderních kompozitních správců oken (Compiz, Beryl, ...) je<br>\ntato funkce dostupná až od Java 6 Update 10.\n</html>"); notificationAreaCheckBox.setEnabled(NotificationIcon.isSupported()); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${notificationIconVisible}"), notificationAreaCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); notificationAreaCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { notificationAreaCheckBoxActionPerformed(evt); } }); tipsCheckBox.setMnemonic('t'); tipsCheckBox.setText("Po spuštění zobrazit tip programu"); tipsCheckBox.setToolTipText("<html>\nPo spuštění programu zobrazit ve stavovém řádku<br>\nnáhodný tip ohledně práce s programem\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${showTips}"), tipsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); startMinimizedCheckBox.setMnemonic('y'); startMinimizedCheckBox.setText("Po startu skrýt program do ikony"); startMinimizedCheckBox.setToolTipText("<html>\nProgram bude okamžitě po spuštění schován<br>\ndo ikony v oznamovací oblasti\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${startMinimized}"), startMinimizedCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, notificationAreaCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected && enabled}"), startMinimizedCheckBox, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(windowCenteredCheckBox) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(startMinimizedCheckBox)) .addComponent(tipsCheckBox) .addComponent(notificationAreaCheckBox) .addComponent(toolbarVisibleCheckBox) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(themeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(lafComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5)))) .addComponent(windowDecorationsCheckBox) .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)) .addContainerGap()) ); jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lafComboBox, themeComboBox}); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(lafComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(themeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(windowDecorationsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(windowCenteredCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(toolbarVisibleCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(notificationAreaCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(startMinimizedCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tipsCheckBox) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 118, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 160, Short.MAX_VALUE) .addComponent(jLabel7) .addContainerGap()) ); jPanel3Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {lafComboBox, themeComboBox}); tabbedPane.addTab("Vzhled", jPanel3); useSenderIDCheckBox.setMnemonic('d'); useSenderIDCheckBox.setText("Připojovat ke zprávě podpis odesilatele"); useSenderIDCheckBox.setToolTipText("<html>\nPři připojení podpisu přijde SMS adresátovi ze zadaného čísla<br>\na podepsaná daným jménem. Tuto funkci podporují pouze někteří operátoři.\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${useSenderID}"), useSenderIDCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); senderNumberTextField.setColumns(13); senderNumberTextField.setToolTipText("Číslo odesilatele v mezinárodním formátu (začínající na znak \"+\")"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${senderNumber}"), senderNumberTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useSenderIDCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), senderNumberTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); jLabel1.setDisplayedMnemonic('l'); jLabel1.setLabelFor(senderNumberTextField); jLabel1.setText("Číslo:"); jLabel1.setToolTipText(senderNumberTextField.getToolTipText()); senderNameTextField.setColumns(13); senderNameTextField.setToolTipText("<html>\nVyplněné jméno zabírá ve zprávě místo, avšak není vidět,<br>\ntakže obarvování textu zprávy a ukazatel počtu sms<br>\nnebudou zdánlivě spolu souhlasit\n</html>\n\n"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${senderName}"), senderNameTextField, org.jdesktop.beansbinding.BeanProperty.create("text_ON_ACTION_OR_FOCUS_LOST")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useSenderIDCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), senderNameTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); jLabel3.setDisplayedMnemonic('m'); jLabel3.setLabelFor(senderNameTextField); jLabel3.setText("Jméno:"); jLabel3.setToolTipText(senderNameTextField.getToolTipText()); countryPrefixTextField.setColumns(5); countryPrefixTextField.setToolTipText("<html>\nMezinárodní předčíslí země, začínající na znak \"+\".<br>\nPři vyplnění se dané předčíslí bude předpokládat u všech čísel, které nebudou<br>\nzadány v mezinárodním formátu. Taktéž se zkrátí zobrazení těchto čísel v mnoha popiscích.\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${countryPrefix}"), countryPrefixTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); countryPrefixTextField.setInputVerifier(new InputVerifier() { @Override public boolean verify(JComponent input) { String prefix = countryPrefixTextField.getText(); return prefix.length() == 0 || FormChecker.checkCountryPrefix(prefix); } }); countryPrefixTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateCountryCode(); } }); jLabel2.setDisplayedMnemonic('d'); jLabel2.setLabelFor(countryPrefixTextField); jLabel2.setText("Výchozí předčíslí země:"); jLabel2.setToolTipText(countryPrefixTextField.getToolTipText()); operatorFilterTextField.setColumns(13); operatorFilterTextField.setToolTipText("<html>\nV seznamu operátorů budou zobrazeni pouze ti, kteří budou<br>\nobsahovat ve svém názvu vzor zadaný v tomto poli. Jednoduše tak<br>\nlze například zobrazit pouze operátory pro zemi XX zadáním vzoru [XX].<br>\nLze zadat více vzorů oddělených čárkou. Bere se ohled na velikost písmen.\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${operatorFilter}"), operatorFilterTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jLabel8.setDisplayedMnemonic('t'); jLabel8.setLabelFor(operatorFilterTextField); jLabel8.setText("Zobrazovat pouze brány operátorů mající v názvu:"); jLabel8.setToolTipText(operatorFilterTextField.getToolTipText()); countryCodeLabel.setText("(stát: XX)"); countryCodeLabel.setToolTipText("Kód státu, pro který jste vyplnili telefonní předčíslí"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(useSenderIDCheckBox) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(countryPrefixTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(countryCodeLabel)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(operatorFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(senderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(senderNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel3}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(countryPrefixTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(countryCodeLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(operatorFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(useSenderIDCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(senderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(senderNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) - .addContainerGap(224, Short.MAX_VALUE)) + .addContainerGap(266, Short.MAX_VALUE)) ); tabbedPane.addTab("Operátoři", jPanel2); operatorComboBoxItemStateChanged(null); operatorComboBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { operatorComboBoxItemStateChanged(evt); } }); jLabel9.setText("<html>\nZde si můžete nastavit své přihlašovací údaje pro operátory, kteří to vyžadují.\n</html>"); jLabel10.setDisplayedMnemonic('r'); jLabel10.setLabelFor(operatorComboBox); jLabel10.setText("Operátor:"); jLabel10.setToolTipText(operatorComboBox.getToolTipText()); loginTextField.setColumns(15); loginTextField.setToolTipText("Uživatelské jméno potřebné k přihlášení k webové bráně operátora"); loginTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateKeyring(); } }); jLabel11.setDisplayedMnemonic('u'); jLabel11.setLabelFor(loginTextField); jLabel11.setText("Uživatelské jméno:"); jLabel11.setToolTipText(loginTextField.getToolTipText()); passwordField.setColumns(15); passwordField.setToolTipText("Heslo příslušející k danému uživatelskému jménu"); passwordField.enableInputMethods(true); passwordField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateKeyring(); } }); jLabel12.setDisplayedMnemonic('s'); jLabel12.setLabelFor(passwordField); jLabel12.setText("Heslo:"); jLabel12.setToolTipText(passwordField.getToolTipText()); clearKeyringButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/esmska/resources/clear-22.png"))); // NOI18N clearKeyringButton.setMnemonic('d'); clearKeyringButton.setText("Odstranit všechny přihlašovací údaje"); clearKeyringButton.setToolTipText("Vymaže uživatelské jména a hesla u všech operátorů"); clearKeyringButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearKeyringButtonActionPerformed(evt); } }); jLabel13.setText("<html><i>\nAčkoliv se hesla ukládají šifrovaně, lze se k původnímu obsahu dostat. Důrazně doporučujeme nastavit si přístupová práva tak, aby k <u>adresáři s konfiguračními soubory programu</u> neměl přístup žádný jiný uživatel.\n</i></html>"); jLabel13.setToolTipText("<html>Uživatelský adresář programu:<br>" + PersistenceManager.getUserDir().getAbsolutePath() + "</html>"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(passwordField)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(operatorComboBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(loginTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(clearKeyringButton) .addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)) .addContainerGap()) ); jPanel4Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel10, jLabel11, jLabel12}); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(operatorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(loginTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(clearKeyringButton) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 161, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 173, Short.MAX_VALUE) .addComponent(jLabel13) .addContainerGap()) ); tabbedPane.addTab("Přihlašovací údaje", jPanel4); reducedHistoryCheckBox.setMnemonic('m'); reducedHistoryCheckBox.setText("Omezit historii odeslaných zpráv pouze na posledních"); reducedHistoryCheckBox.setToolTipText("<html>\nPři ukončení programu se uloží historie odeslaných zpráv<BR>\npouze za zvolené poslední období\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${reducedHistory}"), reducedHistoryCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); reducedHistorySpinner.setToolTipText(reducedHistoryCheckBox.getToolTipText()); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${reducedHistoryCount}"), reducedHistorySpinner, org.jdesktop.beansbinding.BeanProperty.create("value")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, reducedHistoryCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), reducedHistorySpinner, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); ((SpinnerNumberModel)reducedHistorySpinner.getModel()).setMinimum(new Integer(0)); jLabel18.setText("dní."); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addComponent(reducedHistoryCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(reducedHistorySpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel18) .addContainerGap(188, Short.MAX_VALUE)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(reducedHistoryCheckBox) .addComponent(reducedHistorySpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18)) .addContainerGap()) ); tabbedPane.addTab("Soukromí", jPanel6); useProxyCheckBox.setMnemonic('x'); useProxyCheckBox.setText("Používat proxy server *"); useProxyCheckBox.setToolTipText("Zda pro připojení používat proxy server"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${useProxy}"), useProxyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); useProxyCheckBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { useProxyCheckBoxItemStateChanged(evt); } }); httpProxyTextField.setColumns(20); httpProxyTextField.setToolTipText("<html>\nAdresa HTTP proxy serveru ve formátu \"host\" nebo \"host:port\".\nNapříklad: proxy.firma.com:80\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${httpProxy}"), httpProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), httpProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); httpProxyTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateProxy(); } }); sameProxyCheckBox.setMnemonic('t'); sameProxyCheckBox.setText("Pro všechny protokoly použít tuto proxy"); sameProxyCheckBox.setToolTipText("Pro všechny protokoly se použije adresa zadaná v políčku \"HTTP proxy\"."); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${sameProxy}"), sameProxyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), sameProxyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); sameProxyCheckBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { sameProxyCheckBoxItemStateChanged(evt); } }); httpsProxyTextField.setToolTipText("<html>\nAdresa HTTPS proxy serveru ve formátu \"host\" nebo \"host:port\".\nNapříklad: proxy.firma.com:443\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${httpsProxy}"), httpsProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, sameProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${enabled && !selected}"), httpsProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); httpsProxyTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateProxy(); } }); socksProxyTextField.setToolTipText("<html>\nAdresa SOCKS proxy serveru ve formátu \"host\" nebo \"host:port\".\nNapříklad: proxy.firma.com:1080\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${socksProxy}"), socksProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, sameProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${enabled && !selected}"), socksProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); socksProxyTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateProxy(); } }); jLabel14.setDisplayedMnemonic('t'); jLabel14.setLabelFor(httpProxyTextField); jLabel14.setText("HTTP proxy:"); jLabel14.setToolTipText(httpProxyTextField.getToolTipText()); jLabel15.setDisplayedMnemonic('s'); jLabel15.setLabelFor(httpsProxyTextField); jLabel15.setText("HTTPS proxy:"); jLabel15.setToolTipText(httpsProxyTextField.getToolTipText()); jLabel16.setDisplayedMnemonic('c'); jLabel16.setLabelFor(socksProxyTextField); jLabel16.setText("SOCKS proxy:"); jLabel16.setToolTipText(socksProxyTextField.getToolTipText()); jLabel17.setText("<html><i>\n* Pokud nejste k Internetu připojeni přímo, je nutné, aby vaše proxy fungovala jako SOCKS proxy server.\n</i></html>"); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(useProxyCheckBox) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(sameProxyCheckBox)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(httpProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel15) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(httpsProxyTextField)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(socksProxyTextField)))) .addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)) .addContainerGap()) ); jPanel5Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel14, jLabel15, jLabel16}); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(useProxyCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(httpProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sameProxyCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(httpsProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel16) .addComponent(socksProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 201, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 228, Short.MAX_VALUE) .addComponent(jLabel17) .addContainerGap()) ); tabbedPane.addTab("Připojení", jPanel5); closeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/esmska/resources/close-22.png"))); // NOI18N closeButton.setMnemonic('z'); closeButton.setText("Zavřít"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(tabbedPane) .addComponent(closeButton)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() - .addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) - .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton) .addContainerGap()) ); bindingGroup.bind(); pack(); }// </editor-fold>//GEN-END:initComponents private void themeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_themeComboBoxActionPerformed String laf = (String) lafComboBox.getSelectedItem(); if (laf.equals(LAF_JGOODIES)) { config.setLafJGoodiesTheme((String) themeComboBox.getSelectedItem()); } else if (laf.equals(LAF_SUBSTANCE)) { config.setLafSubstanceSkin((String) themeComboBox.getSelectedItem()); } //update skin in realtime if (fullyInicialized && lafWhenLoaded.equals(lafComboBox.getSelectedItem())) { try { ThemeManager.setLaF(); SwingUtilities.updateComponentTreeUI(MainFrame.getInstance()); SwingUtilities.updateComponentTreeUI(this); } catch (Throwable ex) { logger.log(Level.SEVERE, "Problem while live-updating the look&feel skin", ex); } } }//GEN-LAST:event_themeComboBoxActionPerformed private void lafComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_lafComboBoxActionPerformed if (!fullyInicialized) return; String laf = (String) lafComboBox.getSelectedItem(); if (laf.equals(LAF_SYSTEM)) config.setLookAndFeel(ThemeManager.LAF_SYSTEM); else if (laf.equals(LAF_CROSSPLATFORM)) config.setLookAndFeel(ThemeManager.LAF_CROSSPLATFORM); else if (laf.equals(LAF_GTK)) config.setLookAndFeel(ThemeManager.LAF_GTK); else if (laf.equals(LAF_JGOODIES)) config.setLookAndFeel(ThemeManager.LAF_JGOODIES); else if (laf.equals(LAF_SUBSTANCE)) config.setLookAndFeel(ThemeManager.LAF_SUBSTANCE); updateThemeComboBox(); }//GEN-LAST:event_lafComboBoxActionPerformed private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed this.setVisible(false); this.dispose(); }//GEN-LAST:event_closeButtonActionPerformed private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed //check validity of country prefix String prefix = countryPrefixTextField.getText(); if (prefix.length() > 0 && !FormChecker.checkCountryPrefix(prefix)) { config.setCountryPrefix(""); } }//GEN-LAST:event_formWindowClosed private void operatorComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_operatorComboBoxItemStateChanged Operator operator = operatorComboBox.getSelectedOperator(); String[] key = keyring.getKey(operator != null ? operator.getName() : null); if (key == null) { loginTextField.setText(null); passwordField.setText(null); } else { loginTextField.setText(key[0]); passwordField.setText(key[1]); } }//GEN-LAST:event_operatorComboBoxItemStateChanged private void clearKeyringButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearKeyringButtonActionPerformed keyring.clearKeys(); operatorComboBoxItemStateChanged(null); }//GEN-LAST:event_clearKeyringButtonActionPerformed private void useProxyCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_useProxyCheckBoxItemStateChanged updateProxy(); }//GEN-LAST:event_useProxyCheckBoxItemStateChanged private void sameProxyCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_sameProxyCheckBoxItemStateChanged updateProxy(); }//GEN-LAST:event_sameProxyCheckBoxItemStateChanged private void notificationAreaCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_notificationAreaCheckBoxActionPerformed if (notificationAreaCheckBox.isSelected()) { NotificationIcon.install(); } else { NotificationIcon.uninstall(); } }//GEN-LAST:event_notificationAreaCheckBoxActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JCheckBox checkUpdatesCheckBox; private javax.swing.JButton clearKeyringButton; private javax.swing.JButton closeButton; private esmska.data.Config config; private javax.swing.JLabel countryCodeLabel; private javax.swing.JTextField countryPrefixTextField; private javax.swing.JPanel develPanel; private javax.swing.JTextField httpProxyTextField; private javax.swing.JTextField httpsProxyTextField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel15; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JComboBox lafComboBox; private javax.swing.JTextField loginTextField; private javax.swing.JCheckBox notificationAreaCheckBox; private esmska.gui.OperatorComboBox operatorComboBox; private javax.swing.JTextField operatorFilterTextField; private javax.swing.JPasswordField passwordField; private javax.swing.JCheckBox reducedHistoryCheckBox; private javax.swing.JSpinner reducedHistorySpinner; private javax.swing.JCheckBox rememberLayoutCheckBox; private javax.swing.JCheckBox removeAccentsCheckBox; private javax.swing.JCheckBox sameProxyCheckBox; private javax.swing.JTextField senderNameTextField; private javax.swing.JTextField senderNumberTextField; private javax.swing.JTextField socksProxyTextField; private javax.swing.JCheckBox startMinimizedCheckBox; private javax.swing.JTabbedPane tabbedPane; private javax.swing.JComboBox themeComboBox; private javax.swing.JCheckBox tipsCheckBox; private javax.swing.JCheckBox toolbarVisibleCheckBox; private javax.swing.JCheckBox useProxyCheckBox; private javax.swing.JCheckBox useSenderIDCheckBox; private javax.swing.JCheckBox windowCenteredCheckBox; private javax.swing.JCheckBox windowDecorationsCheckBox; private org.jdesktop.beansbinding.BindingGroup bindingGroup; // End of variables declaration//GEN-END:variables }
false
true
private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); config = PersistenceManager.getConfig(); develPanel = new javax.swing.JPanel(); rememberLayoutCheckBox = new javax.swing.JCheckBox(); tabbedPane = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); removeAccentsCheckBox = new javax.swing.JCheckBox(); checkUpdatesCheckBox = new javax.swing.JCheckBox(); jPanel3 = new javax.swing.JPanel(); lafComboBox = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); themeComboBox = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); windowDecorationsCheckBox = new javax.swing.JCheckBox(); windowCenteredCheckBox = new javax.swing.JCheckBox(); toolbarVisibleCheckBox = new javax.swing.JCheckBox(); jLabel5 = new javax.swing.JLabel(); notificationAreaCheckBox = new javax.swing.JCheckBox(); tipsCheckBox = new javax.swing.JCheckBox(); startMinimizedCheckBox = new javax.swing.JCheckBox(); jPanel2 = new javax.swing.JPanel(); useSenderIDCheckBox = new javax.swing.JCheckBox(); senderNumberTextField = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); senderNameTextField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); countryPrefixTextField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); operatorFilterTextField = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); countryCodeLabel = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); operatorComboBox = new esmska.gui.OperatorComboBox(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); loginTextField = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); passwordField = new javax.swing.JPasswordField(); jLabel12 = new javax.swing.JLabel(); clearKeyringButton = new javax.swing.JButton(); jLabel13 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); reducedHistoryCheckBox = new javax.swing.JCheckBox(); reducedHistorySpinner = new javax.swing.JSpinner(); jLabel18 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); useProxyCheckBox = new javax.swing.JCheckBox(); httpProxyTextField = new javax.swing.JTextField(); sameProxyCheckBox = new javax.swing.JCheckBox(); httpsProxyTextField = new javax.swing.JTextField(); socksProxyTextField = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); closeButton = new javax.swing.JButton(); rememberLayoutCheckBox.setMnemonic('r'); rememberLayoutCheckBox.setText("Pamatovat rozvržení formuláře"); rememberLayoutCheckBox.setToolTipText("<html>\nPoužije aktuální rozměry programu a prvků formuláře při příštím spuštění programu\n</html>"); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${rememberLayout}"), rememberLayoutCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); javax.swing.GroupLayout develPanelLayout = new javax.swing.GroupLayout(develPanel); develPanel.setLayout(develPanelLayout); develPanelLayout.setHorizontalGroup( develPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(develPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(rememberLayoutCheckBox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); develPanelLayout.setVerticalGroup( develPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(develPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(rememberLayoutCheckBox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Nastavení - Esmska"); setIconImage(new ImageIcon(getClass().getResource(RES + "config-48.png")).getImage()); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } }); removeAccentsCheckBox.setMnemonic('d'); removeAccentsCheckBox.setText("Ze zpráv odstraňovat diakritiku"); removeAccentsCheckBox.setToolTipText("<html>\nPřed odesláním zprávy z ní odstraní všechna diakritická znaménka\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${removeAccents}"), removeAccentsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); checkUpdatesCheckBox.setMnemonic('n'); checkUpdatesCheckBox.setText("Kontrolovat po startu novou verzi programu"); checkUpdatesCheckBox.setToolTipText("<html>\nPo spuštění programu zkontrolovat, zda nevyšla novější<br>\nverze programu, a případně upozornit ve stavovém řádku\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${checkForUpdates}"), checkUpdatesCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(removeAccentsCheckBox) .addComponent(checkUpdatesCheckBox)) .addContainerGap(352, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(removeAccentsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(checkUpdatesCheckBox) .addContainerGap(297, Short.MAX_VALUE)) ); tabbedPane.addTab("Obecné", jPanel1); lafComboBox.setToolTipText("<html>\nUmožní vám změnit vzhled programu\n</html>"); lafComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lafComboBoxActionPerformed(evt); } }); jLabel4.setDisplayedMnemonic('d'); jLabel4.setLabelFor(lafComboBox); jLabel4.setText("Vzhled:"); jLabel4.setToolTipText(lafComboBox.getToolTipText()); jLabel7.setText("<html><i>\n* Pro projevení změn je nutný restart programu!\n</i></html>"); themeComboBox.setToolTipText("<html>\nBarevná schémata pro zvolený vzhled\n</html>"); themeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { themeComboBoxActionPerformed(evt); } }); jLabel6.setDisplayedMnemonic('m'); jLabel6.setLabelFor(themeComboBox); jLabel6.setText("Motiv:"); jLabel6.setToolTipText(themeComboBox.getToolTipText()); windowDecorationsCheckBox.setMnemonic('k'); windowDecorationsCheckBox.setText("Použít vzhled i na okraje oken *"); windowDecorationsCheckBox.setToolTipText("<html>\nZda má místo operačního systému vykreslovat<br>\nrámečky oken zvolený vzhled\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${lafWindowDecorated}"), windowDecorationsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); windowCenteredCheckBox.setMnemonic('u'); windowCenteredCheckBox.setText("Spustit program uprostřed obrazovky"); windowCenteredCheckBox.setToolTipText("<html>Zda-li nechat umístění okna programu na operačním systému,<br>\nnebo ho umístit vždy doprostřed obrazovky</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${startCentered}"), windowCenteredCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); toolbarVisibleCheckBox.setMnemonic('n'); toolbarVisibleCheckBox.setText("Zobrazit panel nástrojů"); toolbarVisibleCheckBox.setToolTipText("<html>\nZobrazit panel nástrojů, který umožňuje rychlejší ovládání myší některých akcí\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${toolbarVisible}"), toolbarVisibleCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); jLabel5.setText("*"); notificationAreaCheckBox.setMnemonic('o'); notificationAreaCheckBox.setText("Umístit ikonu do oznamovací oblasti"); notificationAreaCheckBox.setToolTipText("<html>\nZobrazit ikonu v oznamovací oblasti správce oken (tzv. <i>system tray</i>).<br>\n<br>\nPozor, u moderních kompozitních správců oken (Compiz, Beryl, ...) je<br>\ntato funkce dostupná až od Java 6 Update 10.\n</html>"); notificationAreaCheckBox.setEnabled(NotificationIcon.isSupported()); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${notificationIconVisible}"), notificationAreaCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); notificationAreaCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { notificationAreaCheckBoxActionPerformed(evt); } }); tipsCheckBox.setMnemonic('t'); tipsCheckBox.setText("Po spuštění zobrazit tip programu"); tipsCheckBox.setToolTipText("<html>\nPo spuštění programu zobrazit ve stavovém řádku<br>\nnáhodný tip ohledně práce s programem\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${showTips}"), tipsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); startMinimizedCheckBox.setMnemonic('y'); startMinimizedCheckBox.setText("Po startu skrýt program do ikony"); startMinimizedCheckBox.setToolTipText("<html>\nProgram bude okamžitě po spuštění schován<br>\ndo ikony v oznamovací oblasti\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${startMinimized}"), startMinimizedCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, notificationAreaCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected && enabled}"), startMinimizedCheckBox, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(windowCenteredCheckBox) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(startMinimizedCheckBox)) .addComponent(tipsCheckBox) .addComponent(notificationAreaCheckBox) .addComponent(toolbarVisibleCheckBox) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(themeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(lafComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5)))) .addComponent(windowDecorationsCheckBox) .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)) .addContainerGap()) ); jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lafComboBox, themeComboBox}); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(lafComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(themeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(windowDecorationsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(windowCenteredCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(toolbarVisibleCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(notificationAreaCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(startMinimizedCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tipsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 118, Short.MAX_VALUE) .addComponent(jLabel7) .addContainerGap()) ); jPanel3Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {lafComboBox, themeComboBox}); tabbedPane.addTab("Vzhled", jPanel3); useSenderIDCheckBox.setMnemonic('d'); useSenderIDCheckBox.setText("Připojovat ke zprávě podpis odesilatele"); useSenderIDCheckBox.setToolTipText("<html>\nPři připojení podpisu přijde SMS adresátovi ze zadaného čísla<br>\na podepsaná daným jménem. Tuto funkci podporují pouze někteří operátoři.\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${useSenderID}"), useSenderIDCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); senderNumberTextField.setColumns(13); senderNumberTextField.setToolTipText("Číslo odesilatele v mezinárodním formátu (začínající na znak \"+\")"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${senderNumber}"), senderNumberTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useSenderIDCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), senderNumberTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); jLabel1.setDisplayedMnemonic('l'); jLabel1.setLabelFor(senderNumberTextField); jLabel1.setText("Číslo:"); jLabel1.setToolTipText(senderNumberTextField.getToolTipText()); senderNameTextField.setColumns(13); senderNameTextField.setToolTipText("<html>\nVyplněné jméno zabírá ve zprávě místo, avšak není vidět,<br>\ntakže obarvování textu zprávy a ukazatel počtu sms<br>\nnebudou zdánlivě spolu souhlasit\n</html>\n\n"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${senderName}"), senderNameTextField, org.jdesktop.beansbinding.BeanProperty.create("text_ON_ACTION_OR_FOCUS_LOST")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useSenderIDCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), senderNameTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); jLabel3.setDisplayedMnemonic('m'); jLabel3.setLabelFor(senderNameTextField); jLabel3.setText("Jméno:"); jLabel3.setToolTipText(senderNameTextField.getToolTipText()); countryPrefixTextField.setColumns(5); countryPrefixTextField.setToolTipText("<html>\nMezinárodní předčíslí země, začínající na znak \"+\".<br>\nPři vyplnění se dané předčíslí bude předpokládat u všech čísel, které nebudou<br>\nzadány v mezinárodním formátu. Taktéž se zkrátí zobrazení těchto čísel v mnoha popiscích.\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${countryPrefix}"), countryPrefixTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); countryPrefixTextField.setInputVerifier(new InputVerifier() { @Override public boolean verify(JComponent input) { String prefix = countryPrefixTextField.getText(); return prefix.length() == 0 || FormChecker.checkCountryPrefix(prefix); } }); countryPrefixTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateCountryCode(); } }); jLabel2.setDisplayedMnemonic('d'); jLabel2.setLabelFor(countryPrefixTextField); jLabel2.setText("Výchozí předčíslí země:"); jLabel2.setToolTipText(countryPrefixTextField.getToolTipText()); operatorFilterTextField.setColumns(13); operatorFilterTextField.setToolTipText("<html>\nV seznamu operátorů budou zobrazeni pouze ti, kteří budou<br>\nobsahovat ve svém názvu vzor zadaný v tomto poli. Jednoduše tak<br>\nlze například zobrazit pouze operátory pro zemi XX zadáním vzoru [XX].<br>\nLze zadat více vzorů oddělených čárkou. Bere se ohled na velikost písmen.\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${operatorFilter}"), operatorFilterTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jLabel8.setDisplayedMnemonic('t'); jLabel8.setLabelFor(operatorFilterTextField); jLabel8.setText("Zobrazovat pouze brány operátorů mající v názvu:"); jLabel8.setToolTipText(operatorFilterTextField.getToolTipText()); countryCodeLabel.setText("(stát: XX)"); countryCodeLabel.setToolTipText("Kód státu, pro který jste vyplnili telefonní předčíslí"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(useSenderIDCheckBox) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(countryPrefixTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(countryCodeLabel)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(operatorFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(senderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(senderNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel3}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(countryPrefixTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(countryCodeLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(operatorFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(useSenderIDCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(senderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(senderNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(224, Short.MAX_VALUE)) ); tabbedPane.addTab("Operátoři", jPanel2); operatorComboBoxItemStateChanged(null); operatorComboBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { operatorComboBoxItemStateChanged(evt); } }); jLabel9.setText("<html>\nZde si můžete nastavit své přihlašovací údaje pro operátory, kteří to vyžadují.\n</html>"); jLabel10.setDisplayedMnemonic('r'); jLabel10.setLabelFor(operatorComboBox); jLabel10.setText("Operátor:"); jLabel10.setToolTipText(operatorComboBox.getToolTipText()); loginTextField.setColumns(15); loginTextField.setToolTipText("Uživatelské jméno potřebné k přihlášení k webové bráně operátora"); loginTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateKeyring(); } }); jLabel11.setDisplayedMnemonic('u'); jLabel11.setLabelFor(loginTextField); jLabel11.setText("Uživatelské jméno:"); jLabel11.setToolTipText(loginTextField.getToolTipText()); passwordField.setColumns(15); passwordField.setToolTipText("Heslo příslušející k danému uživatelskému jménu"); passwordField.enableInputMethods(true); passwordField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateKeyring(); } }); jLabel12.setDisplayedMnemonic('s'); jLabel12.setLabelFor(passwordField); jLabel12.setText("Heslo:"); jLabel12.setToolTipText(passwordField.getToolTipText()); clearKeyringButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/esmska/resources/clear-22.png"))); // NOI18N clearKeyringButton.setMnemonic('d'); clearKeyringButton.setText("Odstranit všechny přihlašovací údaje"); clearKeyringButton.setToolTipText("Vymaže uživatelské jména a hesla u všech operátorů"); clearKeyringButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearKeyringButtonActionPerformed(evt); } }); jLabel13.setText("<html><i>\nAčkoliv se hesla ukládají šifrovaně, lze se k původnímu obsahu dostat. Důrazně doporučujeme nastavit si přístupová práva tak, aby k <u>adresáři s konfiguračními soubory programu</u> neměl přístup žádný jiný uživatel.\n</i></html>"); jLabel13.setToolTipText("<html>Uživatelský adresář programu:<br>" + PersistenceManager.getUserDir().getAbsolutePath() + "</html>"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(passwordField)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(operatorComboBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(loginTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(clearKeyringButton) .addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)) .addContainerGap()) ); jPanel4Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel10, jLabel11, jLabel12}); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(operatorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(loginTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(clearKeyringButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 161, Short.MAX_VALUE) .addComponent(jLabel13) .addContainerGap()) ); tabbedPane.addTab("Přihlašovací údaje", jPanel4); reducedHistoryCheckBox.setMnemonic('m'); reducedHistoryCheckBox.setText("Omezit historii odeslaných zpráv pouze na posledních"); reducedHistoryCheckBox.setToolTipText("<html>\nPři ukončení programu se uloží historie odeslaných zpráv<BR>\npouze za zvolené poslední období\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${reducedHistory}"), reducedHistoryCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); reducedHistorySpinner.setToolTipText(reducedHistoryCheckBox.getToolTipText()); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${reducedHistoryCount}"), reducedHistorySpinner, org.jdesktop.beansbinding.BeanProperty.create("value")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, reducedHistoryCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), reducedHistorySpinner, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); ((SpinnerNumberModel)reducedHistorySpinner.getModel()).setMinimum(new Integer(0)); jLabel18.setText("dní."); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addComponent(reducedHistoryCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(reducedHistorySpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel18) .addContainerGap(188, Short.MAX_VALUE)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(reducedHistoryCheckBox) .addComponent(reducedHistorySpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18)) .addContainerGap()) ); tabbedPane.addTab("Soukromí", jPanel6); useProxyCheckBox.setMnemonic('x'); useProxyCheckBox.setText("Používat proxy server *"); useProxyCheckBox.setToolTipText("Zda pro připojení používat proxy server"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${useProxy}"), useProxyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); useProxyCheckBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { useProxyCheckBoxItemStateChanged(evt); } }); httpProxyTextField.setColumns(20); httpProxyTextField.setToolTipText("<html>\nAdresa HTTP proxy serveru ve formátu \"host\" nebo \"host:port\".\nNapříklad: proxy.firma.com:80\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${httpProxy}"), httpProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), httpProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); httpProxyTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateProxy(); } }); sameProxyCheckBox.setMnemonic('t'); sameProxyCheckBox.setText("Pro všechny protokoly použít tuto proxy"); sameProxyCheckBox.setToolTipText("Pro všechny protokoly se použije adresa zadaná v políčku \"HTTP proxy\"."); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${sameProxy}"), sameProxyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), sameProxyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); sameProxyCheckBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { sameProxyCheckBoxItemStateChanged(evt); } }); httpsProxyTextField.setToolTipText("<html>\nAdresa HTTPS proxy serveru ve formátu \"host\" nebo \"host:port\".\nNapříklad: proxy.firma.com:443\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${httpsProxy}"), httpsProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, sameProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${enabled && !selected}"), httpsProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); httpsProxyTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateProxy(); } }); socksProxyTextField.setToolTipText("<html>\nAdresa SOCKS proxy serveru ve formátu \"host\" nebo \"host:port\".\nNapříklad: proxy.firma.com:1080\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${socksProxy}"), socksProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, sameProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${enabled && !selected}"), socksProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); socksProxyTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateProxy(); } }); jLabel14.setDisplayedMnemonic('t'); jLabel14.setLabelFor(httpProxyTextField); jLabel14.setText("HTTP proxy:"); jLabel14.setToolTipText(httpProxyTextField.getToolTipText()); jLabel15.setDisplayedMnemonic('s'); jLabel15.setLabelFor(httpsProxyTextField); jLabel15.setText("HTTPS proxy:"); jLabel15.setToolTipText(httpsProxyTextField.getToolTipText()); jLabel16.setDisplayedMnemonic('c'); jLabel16.setLabelFor(socksProxyTextField); jLabel16.setText("SOCKS proxy:"); jLabel16.setToolTipText(socksProxyTextField.getToolTipText()); jLabel17.setText("<html><i>\n* Pokud nejste k Internetu připojeni přímo, je nutné, aby vaše proxy fungovala jako SOCKS proxy server.\n</i></html>"); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(useProxyCheckBox) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(sameProxyCheckBox)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(httpProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel15) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(httpsProxyTextField)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(socksProxyTextField)))) .addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)) .addContainerGap()) ); jPanel5Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel14, jLabel15, jLabel16}); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(useProxyCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(httpProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sameProxyCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(httpsProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel16) .addComponent(socksProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 201, Short.MAX_VALUE) .addComponent(jLabel17) .addContainerGap()) ); tabbedPane.addTab("Připojení", jPanel5); closeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/esmska/resources/close-22.png"))); // NOI18N closeButton.setMnemonic('z'); closeButton.setText("Zavřít"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(tabbedPane) .addComponent(closeButton)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(tabbedPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(closeButton) .addContainerGap()) ); bindingGroup.bind(); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { bindingGroup = new org.jdesktop.beansbinding.BindingGroup(); config = PersistenceManager.getConfig(); develPanel = new javax.swing.JPanel(); rememberLayoutCheckBox = new javax.swing.JCheckBox(); tabbedPane = new javax.swing.JTabbedPane(); jPanel1 = new javax.swing.JPanel(); removeAccentsCheckBox = new javax.swing.JCheckBox(); checkUpdatesCheckBox = new javax.swing.JCheckBox(); jPanel3 = new javax.swing.JPanel(); lafComboBox = new javax.swing.JComboBox(); jLabel4 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); themeComboBox = new javax.swing.JComboBox(); jLabel6 = new javax.swing.JLabel(); windowDecorationsCheckBox = new javax.swing.JCheckBox(); windowCenteredCheckBox = new javax.swing.JCheckBox(); toolbarVisibleCheckBox = new javax.swing.JCheckBox(); jLabel5 = new javax.swing.JLabel(); notificationAreaCheckBox = new javax.swing.JCheckBox(); tipsCheckBox = new javax.swing.JCheckBox(); startMinimizedCheckBox = new javax.swing.JCheckBox(); jPanel2 = new javax.swing.JPanel(); useSenderIDCheckBox = new javax.swing.JCheckBox(); senderNumberTextField = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); senderNameTextField = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); countryPrefixTextField = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); operatorFilterTextField = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); countryCodeLabel = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); operatorComboBox = new esmska.gui.OperatorComboBox(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); loginTextField = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); passwordField = new javax.swing.JPasswordField(); jLabel12 = new javax.swing.JLabel(); clearKeyringButton = new javax.swing.JButton(); jLabel13 = new javax.swing.JLabel(); jPanel6 = new javax.swing.JPanel(); reducedHistoryCheckBox = new javax.swing.JCheckBox(); reducedHistorySpinner = new javax.swing.JSpinner(); jLabel18 = new javax.swing.JLabel(); jPanel5 = new javax.swing.JPanel(); useProxyCheckBox = new javax.swing.JCheckBox(); httpProxyTextField = new javax.swing.JTextField(); sameProxyCheckBox = new javax.swing.JCheckBox(); httpsProxyTextField = new javax.swing.JTextField(); socksProxyTextField = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); jLabel15 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); closeButton = new javax.swing.JButton(); rememberLayoutCheckBox.setMnemonic('r'); rememberLayoutCheckBox.setText("Pamatovat rozvržení formuláře"); rememberLayoutCheckBox.setToolTipText("<html>\nPoužije aktuální rozměry programu a prvků formuláře při příštím spuštění programu\n</html>"); org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${rememberLayout}"), rememberLayoutCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); javax.swing.GroupLayout develPanelLayout = new javax.swing.GroupLayout(develPanel); develPanel.setLayout(develPanelLayout); develPanelLayout.setHorizontalGroup( develPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(develPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(rememberLayoutCheckBox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); develPanelLayout.setVerticalGroup( develPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(develPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(rememberLayoutCheckBox) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Nastavení - Esmska"); setIconImage(new ImageIcon(getClass().getResource(RES + "config-48.png")).getImage()); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } }); removeAccentsCheckBox.setMnemonic('d'); removeAccentsCheckBox.setText("Ze zpráv odstraňovat diakritiku"); removeAccentsCheckBox.setToolTipText("<html>\nPřed odesláním zprávy z ní odstraní všechna diakritická znaménka\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${removeAccents}"), removeAccentsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); checkUpdatesCheckBox.setMnemonic('n'); checkUpdatesCheckBox.setText("Kontrolovat po startu novou verzi programu"); checkUpdatesCheckBox.setToolTipText("<html>\nPo spuštění programu zkontrolovat, zda nevyšla novější<br>\nverze programu, a případně upozornit ve stavovém řádku\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${checkForUpdates}"), checkUpdatesCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(removeAccentsCheckBox) .addComponent(checkUpdatesCheckBox)) .addContainerGap(352, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(removeAccentsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(checkUpdatesCheckBox) .addContainerGap(339, Short.MAX_VALUE)) ); tabbedPane.addTab("Obecné", jPanel1); lafComboBox.setToolTipText("<html>\nUmožní vám změnit vzhled programu\n</html>"); lafComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { lafComboBoxActionPerformed(evt); } }); jLabel4.setDisplayedMnemonic('d'); jLabel4.setLabelFor(lafComboBox); jLabel4.setText("Vzhled:"); jLabel4.setToolTipText(lafComboBox.getToolTipText()); jLabel7.setText("<html><i>\n* Pro projevení změn je nutný restart programu!\n</i></html>"); themeComboBox.setToolTipText("<html>\nBarevná schémata pro zvolený vzhled\n</html>"); themeComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { themeComboBoxActionPerformed(evt); } }); jLabel6.setDisplayedMnemonic('m'); jLabel6.setLabelFor(themeComboBox); jLabel6.setText("Motiv:"); jLabel6.setToolTipText(themeComboBox.getToolTipText()); windowDecorationsCheckBox.setMnemonic('k'); windowDecorationsCheckBox.setText("Použít vzhled i na okraje oken *"); windowDecorationsCheckBox.setToolTipText("<html>\nZda má místo operačního systému vykreslovat<br>\nrámečky oken zvolený vzhled\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${lafWindowDecorated}"), windowDecorationsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); windowCenteredCheckBox.setMnemonic('u'); windowCenteredCheckBox.setText("Spustit program uprostřed obrazovky"); windowCenteredCheckBox.setToolTipText("<html>Zda-li nechat umístění okna programu na operačním systému,<br>\nnebo ho umístit vždy doprostřed obrazovky</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${startCentered}"), windowCenteredCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); toolbarVisibleCheckBox.setMnemonic('n'); toolbarVisibleCheckBox.setText("Zobrazit panel nástrojů"); toolbarVisibleCheckBox.setToolTipText("<html>\nZobrazit panel nástrojů, který umožňuje rychlejší ovládání myší některých akcí\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${toolbarVisible}"), toolbarVisibleCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); jLabel5.setText("*"); notificationAreaCheckBox.setMnemonic('o'); notificationAreaCheckBox.setText("Umístit ikonu do oznamovací oblasti"); notificationAreaCheckBox.setToolTipText("<html>\nZobrazit ikonu v oznamovací oblasti správce oken (tzv. <i>system tray</i>).<br>\n<br>\nPozor, u moderních kompozitních správců oken (Compiz, Beryl, ...) je<br>\ntato funkce dostupná až od Java 6 Update 10.\n</html>"); notificationAreaCheckBox.setEnabled(NotificationIcon.isSupported()); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${notificationIconVisible}"), notificationAreaCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); notificationAreaCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { notificationAreaCheckBoxActionPerformed(evt); } }); tipsCheckBox.setMnemonic('t'); tipsCheckBox.setText("Po spuštění zobrazit tip programu"); tipsCheckBox.setToolTipText("<html>\nPo spuštění programu zobrazit ve stavovém řádku<br>\nnáhodný tip ohledně práce s programem\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${showTips}"), tipsCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); startMinimizedCheckBox.setMnemonic('y'); startMinimizedCheckBox.setText("Po startu skrýt program do ikony"); startMinimizedCheckBox.setToolTipText("<html>\nProgram bude okamžitě po spuštění schován<br>\ndo ikony v oznamovací oblasti\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${startMinimized}"), startMinimizedCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, notificationAreaCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected && enabled}"), startMinimizedCheckBox, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(windowCenteredCheckBox) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(21, 21, 21) .addComponent(startMinimizedCheckBox)) .addComponent(tipsCheckBox) .addComponent(notificationAreaCheckBox) .addComponent(toolbarVisibleCheckBox) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel6)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(themeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(lafComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5)))) .addComponent(windowDecorationsCheckBox) .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)) .addContainerGap()) ); jPanel3Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {lafComboBox, themeComboBox}); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(lafComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(themeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(windowDecorationsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(windowCenteredCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(toolbarVisibleCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(notificationAreaCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(startMinimizedCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(tipsCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 160, Short.MAX_VALUE) .addComponent(jLabel7) .addContainerGap()) ); jPanel3Layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {lafComboBox, themeComboBox}); tabbedPane.addTab("Vzhled", jPanel3); useSenderIDCheckBox.setMnemonic('d'); useSenderIDCheckBox.setText("Připojovat ke zprávě podpis odesilatele"); useSenderIDCheckBox.setToolTipText("<html>\nPři připojení podpisu přijde SMS adresátovi ze zadaného čísla<br>\na podepsaná daným jménem. Tuto funkci podporují pouze někteří operátoři.\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${useSenderID}"), useSenderIDCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); senderNumberTextField.setColumns(13); senderNumberTextField.setToolTipText("Číslo odesilatele v mezinárodním formátu (začínající na znak \"+\")"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${senderNumber}"), senderNumberTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useSenderIDCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), senderNumberTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); jLabel1.setDisplayedMnemonic('l'); jLabel1.setLabelFor(senderNumberTextField); jLabel1.setText("Číslo:"); jLabel1.setToolTipText(senderNumberTextField.getToolTipText()); senderNameTextField.setColumns(13); senderNameTextField.setToolTipText("<html>\nVyplněné jméno zabírá ve zprávě místo, avšak není vidět,<br>\ntakže obarvování textu zprávy a ukazatel počtu sms<br>\nnebudou zdánlivě spolu souhlasit\n</html>\n\n"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${senderName}"), senderNameTextField, org.jdesktop.beansbinding.BeanProperty.create("text_ON_ACTION_OR_FOCUS_LOST")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useSenderIDCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), senderNameTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); jLabel3.setDisplayedMnemonic('m'); jLabel3.setLabelFor(senderNameTextField); jLabel3.setText("Jméno:"); jLabel3.setToolTipText(senderNameTextField.getToolTipText()); countryPrefixTextField.setColumns(5); countryPrefixTextField.setToolTipText("<html>\nMezinárodní předčíslí země, začínající na znak \"+\".<br>\nPři vyplnění se dané předčíslí bude předpokládat u všech čísel, které nebudou<br>\nzadány v mezinárodním formátu. Taktéž se zkrátí zobrazení těchto čísel v mnoha popiscích.\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${countryPrefix}"), countryPrefixTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); countryPrefixTextField.setInputVerifier(new InputVerifier() { @Override public boolean verify(JComponent input) { String prefix = countryPrefixTextField.getText(); return prefix.length() == 0 || FormChecker.checkCountryPrefix(prefix); } }); countryPrefixTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateCountryCode(); } }); jLabel2.setDisplayedMnemonic('d'); jLabel2.setLabelFor(countryPrefixTextField); jLabel2.setText("Výchozí předčíslí země:"); jLabel2.setToolTipText(countryPrefixTextField.getToolTipText()); operatorFilterTextField.setColumns(13); operatorFilterTextField.setToolTipText("<html>\nV seznamu operátorů budou zobrazeni pouze ti, kteří budou<br>\nobsahovat ve svém názvu vzor zadaný v tomto poli. Jednoduše tak<br>\nlze například zobrazit pouze operátory pro zemi XX zadáním vzoru [XX].<br>\nLze zadat více vzorů oddělených čárkou. Bere se ohled na velikost písmen.\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${operatorFilter}"), operatorFilterTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); jLabel8.setDisplayedMnemonic('t'); jLabel8.setLabelFor(operatorFilterTextField); jLabel8.setText("Zobrazovat pouze brány operátorů mající v názvu:"); jLabel8.setToolTipText(operatorFilterTextField.getToolTipText()); countryCodeLabel.setText("(stát: XX)"); countryCodeLabel.setToolTipText("Kód státu, pro který jste vyplnili telefonní předčíslí"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(useSenderIDCheckBox) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(countryPrefixTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(countryCodeLabel)) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel8) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(operatorFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(17, 17, 17) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(senderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(senderNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))) ); jPanel2Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel3}); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(countryPrefixTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(countryCodeLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(operatorFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(useSenderIDCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(senderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(senderNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(266, Short.MAX_VALUE)) ); tabbedPane.addTab("Operátoři", jPanel2); operatorComboBoxItemStateChanged(null); operatorComboBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { operatorComboBoxItemStateChanged(evt); } }); jLabel9.setText("<html>\nZde si můžete nastavit své přihlašovací údaje pro operátory, kteří to vyžadují.\n</html>"); jLabel10.setDisplayedMnemonic('r'); jLabel10.setLabelFor(operatorComboBox); jLabel10.setText("Operátor:"); jLabel10.setToolTipText(operatorComboBox.getToolTipText()); loginTextField.setColumns(15); loginTextField.setToolTipText("Uživatelské jméno potřebné k přihlášení k webové bráně operátora"); loginTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateKeyring(); } }); jLabel11.setDisplayedMnemonic('u'); jLabel11.setLabelFor(loginTextField); jLabel11.setText("Uživatelské jméno:"); jLabel11.setToolTipText(loginTextField.getToolTipText()); passwordField.setColumns(15); passwordField.setToolTipText("Heslo příslušející k danému uživatelskému jménu"); passwordField.enableInputMethods(true); passwordField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateKeyring(); } }); jLabel12.setDisplayedMnemonic('s'); jLabel12.setLabelFor(passwordField); jLabel12.setText("Heslo:"); jLabel12.setToolTipText(passwordField.getToolTipText()); clearKeyringButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/esmska/resources/clear-22.png"))); // NOI18N clearKeyringButton.setMnemonic('d'); clearKeyringButton.setText("Odstranit všechny přihlašovací údaje"); clearKeyringButton.setToolTipText("Vymaže uživatelské jména a hesla u všech operátorů"); clearKeyringButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearKeyringButtonActionPerformed(evt); } }); jLabel13.setText("<html><i>\nAčkoliv se hesla ukládají šifrovaně, lze se k původnímu obsahu dostat. Důrazně doporučujeme nastavit si přístupová práva tak, aby k <u>adresáři s konfiguračními soubory programu</u> neměl přístup žádný jiný uživatel.\n</i></html>"); jLabel13.setToolTipText("<html>Uživatelský adresář programu:<br>" + PersistenceManager.getUserDir().getAbsolutePath() + "</html>"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addComponent(jLabel12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(passwordField)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(operatorComboBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel4Layout.createSequentialGroup() .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(loginTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(clearKeyringButton) .addComponent(jLabel13, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)) .addContainerGap()) ); jPanel4Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel10, jLabel11, jLabel12}); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(operatorComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel11) .addComponent(loginTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(clearKeyringButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 173, Short.MAX_VALUE) .addComponent(jLabel13) .addContainerGap()) ); tabbedPane.addTab("Přihlašovací údaje", jPanel4); reducedHistoryCheckBox.setMnemonic('m'); reducedHistoryCheckBox.setText("Omezit historii odeslaných zpráv pouze na posledních"); reducedHistoryCheckBox.setToolTipText("<html>\nPři ukončení programu se uloží historie odeslaných zpráv<BR>\npouze za zvolené poslední období\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${reducedHistory}"), reducedHistoryCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); reducedHistorySpinner.setToolTipText(reducedHistoryCheckBox.getToolTipText()); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${reducedHistoryCount}"), reducedHistorySpinner, org.jdesktop.beansbinding.BeanProperty.create("value")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, reducedHistoryCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), reducedHistorySpinner, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); ((SpinnerNumberModel)reducedHistorySpinner.getModel()).setMinimum(new Integer(0)); jLabel18.setText("dní."); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addComponent(reducedHistoryCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(reducedHistorySpinner, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel18) .addContainerGap(188, Short.MAX_VALUE)) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel6Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(reducedHistoryCheckBox) .addComponent(reducedHistorySpinner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel18)) .addContainerGap()) ); tabbedPane.addTab("Soukromí", jPanel6); useProxyCheckBox.setMnemonic('x'); useProxyCheckBox.setText("Používat proxy server *"); useProxyCheckBox.setToolTipText("Zda pro připojení používat proxy server"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${useProxy}"), useProxyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); useProxyCheckBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { useProxyCheckBoxItemStateChanged(evt); } }); httpProxyTextField.setColumns(20); httpProxyTextField.setToolTipText("<html>\nAdresa HTTP proxy serveru ve formátu \"host\" nebo \"host:port\".\nNapříklad: proxy.firma.com:80\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${httpProxy}"), httpProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), httpProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); httpProxyTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateProxy(); } }); sameProxyCheckBox.setMnemonic('t'); sameProxyCheckBox.setText("Pro všechny protokoly použít tuto proxy"); sameProxyCheckBox.setToolTipText("Pro všechny protokoly se použije adresa zadaná v políčku \"HTTP proxy\"."); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${sameProxy}"), sameProxyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, useProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${selected}"), sameProxyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); sameProxyCheckBox.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { sameProxyCheckBoxItemStateChanged(evt); } }); httpsProxyTextField.setToolTipText("<html>\nAdresa HTTPS proxy serveru ve formátu \"host\" nebo \"host:port\".\nNapříklad: proxy.firma.com:443\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${httpsProxy}"), httpsProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, sameProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${enabled && !selected}"), httpsProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); httpsProxyTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateProxy(); } }); socksProxyTextField.setToolTipText("<html>\nAdresa SOCKS proxy serveru ve formátu \"host\" nebo \"host:port\".\nNapříklad: proxy.firma.com:1080\n</html>"); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, config, org.jdesktop.beansbinding.ELProperty.create("${socksProxy}"), socksProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("text")); bindingGroup.addBinding(binding); binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, sameProxyCheckBox, org.jdesktop.beansbinding.ELProperty.create("${enabled && !selected}"), socksProxyTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled")); bindingGroup.addBinding(binding); socksProxyTextField.getDocument().addDocumentListener(new AbstractDocumentListener() { @Override public void onUpdate(DocumentEvent e) { updateProxy(); } }); jLabel14.setDisplayedMnemonic('t'); jLabel14.setLabelFor(httpProxyTextField); jLabel14.setText("HTTP proxy:"); jLabel14.setToolTipText(httpProxyTextField.getToolTipText()); jLabel15.setDisplayedMnemonic('s'); jLabel15.setLabelFor(httpsProxyTextField); jLabel15.setText("HTTPS proxy:"); jLabel15.setToolTipText(httpsProxyTextField.getToolTipText()); jLabel16.setDisplayedMnemonic('c'); jLabel16.setLabelFor(socksProxyTextField); jLabel16.setText("SOCKS proxy:"); jLabel16.setToolTipText(socksProxyTextField.getToolTipText()); jLabel17.setText("<html><i>\n* Pokud nejste k Internetu připojeni přímo, je nutné, aby vaše proxy fungovala jako SOCKS proxy server.\n</i></html>"); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(useProxyCheckBox) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(21, 21, 21) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel5Layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(sameProxyCheckBox)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(httpProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel15) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(httpsProxyTextField)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(jLabel16) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(socksProxyTextField)))) .addComponent(jLabel17, javax.swing.GroupLayout.DEFAULT_SIZE, 638, Short.MAX_VALUE)) .addContainerGap()) ); jPanel5Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel14, jLabel15, jLabel16}); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(useProxyCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel14) .addComponent(httpProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(sameProxyCheckBox) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel15) .addComponent(httpsProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel16) .addComponent(socksProxyTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 228, Short.MAX_VALUE) .addComponent(jLabel17) .addContainerGap()) ); tabbedPane.addTab("Připojení", jPanel5); closeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/esmska/resources/close-22.png"))); // NOI18N closeButton.setMnemonic('z'); closeButton.setText("Zavřít"); closeButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeButtonActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(tabbedPane) .addComponent(closeButton)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(tabbedPane, javax.swing.GroupLayout.DEFAULT_SIZE, 420, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeButton) .addContainerGap()) ); bindingGroup.bind(); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/com/klinker/android/send_message/Transaction.java b/src/com/klinker/android/send_message/Transaction.java index f4c2799..60fcc79 100644 --- a/src/com/klinker/android/send_message/Transaction.java +++ b/src/com/klinker/android/send_message/Transaction.java @@ -1,852 +1,852 @@ /* * Copyright 2013 Jacob Klinker * This code has been modified. Portions copyright (C) 2012, ParanoidAndroid 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.klinker.android.send_message; import android.app.*; import android.content.*; import android.database.Cursor; import android.graphics.Bitmap; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.net.wifi.WifiManager; import android.provider.Telephony; import android.telephony.SmsManager; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.android.mms.transaction.HttpUtils; import com.google.android.mms.APN; import com.google.android.mms.APNHelper; import com.google.android.mms.MMSPart; import com.google.android.mms.pdu_alt.*; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Transaction { public Settings settings; public Context context; public static final String GSM_CHARACTERS_REGEX = "^[A-Za-z0-9 \\r\\n@Ł$ĽčéůěňÇŘřĹĺ\u0394_\u03A6\u0393\u039B\u03A9\u03A0\u03A8\u03A3\u0398\u039EĆćßÉ!\"#$%&'()*+,\\-./:;<=>?ĄÄÖŃܧżäöńüŕ^{}\\\\\\[~\\]|\u20AC]*$"; public Transaction(Context context) { settings = new Settings(); this.context = context; } public Transaction(Context context, String mmsc, String proxy, String port, boolean group, boolean wifiMmsFix) { settings = new Settings(mmsc, proxy, port, group, wifiMmsFix); this.context = context; } public Transaction(Context context, boolean preferVoice, boolean deliveryReports, boolean split) { settings = new Settings(preferVoice, deliveryReports, split); this.context = context; } public Transaction(Context context, String mmsc, String proxy, String port, boolean group, boolean wifiMmsFix, boolean preferVoice, boolean deliveryReports, boolean split) { settings = new Settings(mmsc, proxy, port, group, wifiMmsFix, preferVoice, deliveryReports, split); this.context = context; } public Transaction(Context context, String mmsc, String proxy, String port, boolean group, boolean wifiMmsFix, boolean preferVoice, boolean deliveryReports, boolean split, boolean splitCounter, boolean stripUnicode, String signature, boolean sendLongAsMms, int sendLongAsMmsAfter) { settings = new Settings(mmsc, proxy, port, group, wifiMmsFix, preferVoice, deliveryReports, split, splitCounter, stripUnicode, signature, sendLongAsMms, sendLongAsMmsAfter); this.context = context; } public Transaction(Context context, Settings settings) { this.settings = settings; this.context = context; } public void sendNewMessage(final Message message, final String threadId) { if (message.getImages().length != 0 || (settings.getSendLongAsMms() && getNumPages(settings, message.getText()) > settings.getSendLongAsMmsAfter() && !settings.getPreferVoice()) || (message.getAddresses().length > 1 && settings.getGroup())) { sendMmsMessage(message.getText(), message.getAddresses(), message.getImages(), threadId); } else { if (settings.getPreferVoice()) { sendVoiceMessage(message.getText(), message.getAddresses()); } else { sendSmsMessage(message.getText(), message.getAddresses(), threadId); } } } private void sendSmsMessage(String text, String[] addresses, String threadId) { String SENT = "com.klinker.android.send_message.SMS_SENT"; String DELIVERED = "com.klinker.android.send_message.SMS_DELIVERED"; PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0); PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED), 0); ArrayList<PendingIntent> sPI = new ArrayList<PendingIntent>(); ArrayList<PendingIntent> dPI = new ArrayList<PendingIntent>(); String body = text; if (settings.getStripUnicode()) { body = StripAccents.stripAccents(body); } if (!settings.getSignature().equals("")) { body += "\n" + settings.getSignature(); } SmsManager smsManager = SmsManager.getDefault(); if (settings.getSplit()) { int length = 160; String patternStr = "[^" + GSM_CHARACTERS_REGEX + "]"; Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(body); if (matcher.find()) { length = 70; } boolean counter = false; if (settings.getSplitCounter()) { counter = true; length -= 7; } String[] textToSend = splitByLength(body, length, counter); for (int i = 0; i < textToSend.length; i++) { ArrayList<String> parts = smsManager.divideMessage(textToSend[i]); for (int j = 0; j < parts.size(); j++) { sPI.add(sentPI); - dPI.add(deliveredPI); + dPI.add(settings.getDeliveryReports() ? deliveredPI : null); } for (int j = 0; j < addresses.length; j++) { - smsManager.sendMultipartTextMessage(addresses[j], null, parts, sPI, settings.getDeliveryReports() ? dPI : null); + smsManager.sendMultipartTextMessage(addresses[j], null, parts, sPI, dPI); } } } else { ArrayList<String> parts = smsManager.divideMessage(body); for (int i = 0; i < parts.size(); i++) { sPI.add(sentPI); - dPI.add(deliveredPI); + dPI.add(settings.getDeliveryReports() ? deliveredPI : null); } try { for (int i = 0; i < addresses.length; i++) { - smsManager.sendMultipartTextMessage(addresses[i], null, parts, sPI, settings.getDeliveryReports() ? dPI : null); + smsManager.sendMultipartTextMessage(addresses[i], null, parts, sPI, dPI); } } catch (Exception e) { e.printStackTrace(); try { ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content).post(new Runnable() { @Override public void run() { Toast.makeText(context, "Error, check the \"Split SMS\" option in advanced settings and retry.", Toast.LENGTH_LONG).show(); } }); } catch (Exception f) { } } } if (!settings.getSignature().equals("")) { text += "\n" + settings.getSignature(); } for (int i = 0; i < addresses.length; i++) { Calendar cal = Calendar.getInstance(); ContentValues values = new ContentValues(); values.put("address", addresses[i]); values.put("body", settings.getStripUnicode() ? StripAccents.stripAccents(text) : text); values.put("date", cal.getTimeInMillis() + ""); values.put("read", 1); if (threadId == null || addresses.length > 1) { threadId = Telephony.Threads.getOrCreateThreadId(context, addresses[i]) + ""; } values.put("thread_id", threadId); context.getContentResolver().insert(Uri.parse("content://sms/outbox"), values); } } private void sendMmsMessage(String text, String[] addresses, Bitmap[] image, String threadId) { String address = ""; for (int i = 0; i < addresses.length; i++) { address += addresses[i] + " "; } address = address.trim(); if (image.length <= 1) { insert(("insert-address-token " + address).split(" "), "", image.length != 0 ? Message.bitmapToByteArray(image[0]) : null, text, threadId); MMSPart[] parts = new MMSPart[2]; if (image.length != 0) { parts[0] = new MMSPart(); parts[0].Name = "Image"; parts[0].MimeType = "image/png"; parts[0].Data = Message.bitmapToByteArray(image[0]); if (!text.equals("")) { parts[1] = new MMSPart(); parts[1].Name = "Text"; parts[1].MimeType = "text/plain"; parts[1].Data = text.getBytes(); } } else { parts[0] = new MMSPart(); parts[0].Name = "Text"; parts[0].MimeType = "text/plain"; parts[0].Data = text.getBytes(); } sendMMS(address.split(" "), parts); } else { ArrayList<MMSPart> data = new ArrayList<MMSPart>(); ArrayList<byte[]> bytes = new ArrayList<byte[]>(); ArrayList<String> mimes = new ArrayList<String>(); for (int i = 0; i < image.length; i++) { byte[] imageBytes = Message.bitmapToByteArray(image[i]); bytes.add(imageBytes); mimes.add("image/png"); MMSPart part = new MMSPart(); part.MimeType = "image/png"; part.Name = "Image"; part.Data = imageBytes; data.add(part); } insert(("insert-address-token " + address).split(" "), "", bytes, mimes, text, threadId); MMSPart part = new MMSPart(); part.Name = "Text"; part.MimeType = "text/plain"; part.Data = text.getBytes(); data.add(part); sendMMS(address.split(" "), data.toArray(new MMSPart[data.size()])); } } private void sendVoiceMessage(String text, String[] addresses) { } public static int getNumPages(Settings settings, String text) { int length = text.length(); if (!settings.getSignature().equals("")) { length += ("\n" + settings.getSignature()).length(); } String patternStr = "[^" + GSM_CHARACTERS_REGEX + "]"; Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(text); int size = 160; if (matcher.find() && !settings.getStripUnicode()) { size = 70; } int pages = 1; while (length > size) { length-=size; pages++; } return pages; } private String[] splitByLength(String s, int chunkSize, boolean counter) { int arraySize = (int) Math.ceil((double) s.length() / chunkSize); String[] returnArray = new String[arraySize]; int index = 0; for(int i = 0; i < s.length(); i = i+chunkSize) { if(s.length() - i < chunkSize) { returnArray[index++] = s.substring(i); } else { returnArray[index++] = s.substring(i, i+chunkSize); } } if (counter && returnArray.length > 1) { for (int i = 0; i < returnArray.length; i++) { returnArray[i] = "(" + (i+1) + "/" + returnArray.length + ") " + returnArray[i]; } } return returnArray; } public Uri insert(String[] to, String subject, byte[] imageBytes, String text, String threadId) { try { Uri destUri = Uri.parse("content://mms"); // Get thread id String thread_id = threadId; if (thread_id == null) { Set<String> recipients = new HashSet<String>(); recipients.addAll(Arrays.asList(to)); thread_id = Telephony.Threads.getOrCreateThreadId(context, recipients) + ""; } // Create a dummy sms ContentValues dummyValues = new ContentValues(); dummyValues.put("thread_id", thread_id); dummyValues.put("body", " "); Uri dummySms = context.getContentResolver().insert(Uri.parse("content://sms/sent"), dummyValues); // Create a new message entry long now = System.currentTimeMillis(); ContentValues mmsValues = new ContentValues(); mmsValues.put("thread_id", thread_id); mmsValues.put("date", now/1000L); mmsValues.put("msg_box", 4); //mmsValues.put("m_id", System.currentTimeMillis()); mmsValues.put("read", true); mmsValues.put("sub", subject); mmsValues.put("sub_cs", 106); mmsValues.put("ct_t", "application/vnd.wap.multipart.related"); if (imageBytes != null) { mmsValues.put("exp", imageBytes.length); } else { mmsValues.put("exp", 0); } mmsValues.put("m_cls", "personal"); mmsValues.put("m_type", 128); // 132 (RETRIEVE CONF) 130 (NOTIF IND) 128 (SEND REQ) mmsValues.put("v", 19); mmsValues.put("pri", 129); mmsValues.put("tr_id", "T"+ Long.toHexString(now)); mmsValues.put("resp_st", 128); // Insert message Uri res = context.getContentResolver().insert(destUri, mmsValues); String messageId = res.getLastPathSegment().trim(); // Create part if (imageBytes != null) { createPartImage(messageId, imageBytes, "image/png"); } createPartText(messageId, text); // Create addresses for (String addr : to) { createAddr(messageId, addr); } //res = Uri.parse(destUri + "/" + messageId); // Delete dummy sms context.getContentResolver().delete(dummySms, null, null); return res; } catch (Exception e) { e.printStackTrace(); } return null; } public Uri insert(String[] to, String subject, ArrayList<byte[]> imageBytes, ArrayList<String> mimeTypes, String text, String threadId) { try { Uri destUri = Uri.parse("content://mms"); // Get thread id String thread_id = threadId; if (thread_id == null) { Set<String> recipients = new HashSet<String>(); recipients.addAll(Arrays.asList(to)); thread_id = Telephony.Threads.getOrCreateThreadId(context, recipients) + ""; } // Create a dummy sms ContentValues dummyValues = new ContentValues(); dummyValues.put("thread_id", thread_id); dummyValues.put("body", " "); Uri dummySms = context.getContentResolver().insert(Uri.parse("content://sms/sent"), dummyValues); // Create a new message entry long now = System.currentTimeMillis(); ContentValues mmsValues = new ContentValues(); mmsValues.put("thread_id", thread_id); mmsValues.put("date", now/1000L); mmsValues.put("msg_box", 4); //mmsValues.put("m_id", System.currentTimeMillis()); mmsValues.put("read", true); mmsValues.put("sub", subject); mmsValues.put("sub_cs", 106); mmsValues.put("ct_t", "application/vnd.wap.multipart.related"); if (imageBytes != null) { mmsValues.put("exp", imageBytes.get(0).length); } else { mmsValues.put("exp", 0); } mmsValues.put("m_cls", "personal"); mmsValues.put("m_type", 128); // 132 (RETRIEVE CONF) 130 (NOTIF IND) 128 (SEND REQ) mmsValues.put("v", 19); mmsValues.put("pri", 129); mmsValues.put("tr_id", "T"+ Long.toHexString(now)); mmsValues.put("resp_st", 128); // Insert message Uri res = context.getContentResolver().insert(destUri, mmsValues); String messageId = res.getLastPathSegment().trim(); // Create part for (int i = 0; i < imageBytes.size(); i++) { createPartImage(messageId, imageBytes.get(i), mimeTypes.get(i)); } createPartText(messageId, text); // Create addresses for (String addr : to) { createAddr(messageId, addr); } //res = Uri.parse(destUri + "/" + messageId); // Delete dummy sms context.getContentResolver().delete(dummySms, null, null); return res; } catch (Exception e) { e.printStackTrace(); } return null; } private Uri createPartImage(String id, byte[] imageBytes, String mimeType) throws Exception { ContentValues mmsPartValue = new ContentValues(); mmsPartValue.put("mid", id); mmsPartValue.put("ct", mimeType); mmsPartValue.put("cid", "<" + System.currentTimeMillis() + ">"); Uri partUri = Uri.parse("content://mms/" + id + "/part"); Uri res = context.getContentResolver().insert(partUri, mmsPartValue); // Add data to part OutputStream os = context.getContentResolver().openOutputStream(res); ByteArrayInputStream is = new ByteArrayInputStream(imageBytes); byte[] buffer = new byte[256]; for (int len=0; (len=is.read(buffer)) != -1;) { os.write(buffer, 0, len); } os.close(); is.close(); return res; } private Uri createPartText(String id, String text) throws Exception { ContentValues mmsPartValue = new ContentValues(); mmsPartValue.put("mid", id); mmsPartValue.put("ct", "text/plain"); mmsPartValue.put("cid", "<" + System.currentTimeMillis() + ">"); mmsPartValue.put("text", text); Uri partUri = Uri.parse("content://mms/" + id + "/part"); Uri res = context.getContentResolver().insert(partUri, mmsPartValue); return res; } private Uri createAddr(String id, String addr) throws Exception { ContentValues addrValues = new ContentValues(); addrValues.put("address", addr); addrValues.put("charset", "106"); addrValues.put("type", 151); // TO Uri addrUri = Uri.parse("content://mms/"+ id +"/addr"); Uri res = context.getContentResolver().insert(addrUri, addrValues); return res; } public static void setMobileDataEnabled(Context context, boolean enabled) { try { final ConnectivityManager conman = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); final Class conmanClass = Class.forName(conman.getClass().getName()); final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService"); iConnectivityManagerField.setAccessible(true); final Object iConnectivityManager = iConnectivityManagerField.get(conman); final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName()); final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE); setMobileDataEnabledMethod.setAccessible(true); setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled); } catch (Exception e) { e.printStackTrace(); } } public static Boolean isMobileDataEnabled(Context context){ Object connectivityService = context.getSystemService(Context.CONNECTIVITY_SERVICE); ConnectivityManager cm = (ConnectivityManager) connectivityService; try { Class<?> c = Class.forName(cm.getClass().getName()); Method m = c.getDeclaredMethod("getMobileDataEnabled"); m.setAccessible(true); return (Boolean)m.invoke(cm); } catch (Exception e) { e.printStackTrace(); return null; } } private void ensureRouteToHost(String url, String proxy) throws IOException { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); int inetAddr; if (!proxy.equals("")) { String proxyAddr = proxy; inetAddr = lookupHost(proxyAddr); if (inetAddr == -1) { throw new IOException("Cannot establish route for " + url + ": Unknown host"); } else { if (!connMgr.requestRouteToHost( ConnectivityManager.TYPE_MOBILE_MMS, inetAddr)) { throw new IOException("Cannot establish route to proxy " + inetAddr); } } } else { Uri uri = Uri.parse(url); inetAddr = lookupHost(uri.getHost()); if (inetAddr == -1) { throw new IOException("Cannot establish route for " + url + ": Unknown host"); } else { if (!connMgr.requestRouteToHost( ConnectivityManager.TYPE_MOBILE_MMS, inetAddr)) { throw new IOException("Cannot establish route to " + inetAddr + " for " + url); } } } } public static int lookupHost(String hostname) { InetAddress inetAddress; try { inetAddress = InetAddress.getByName(hostname); } catch (UnknownHostException e) { return -1; } byte[] addrBytes; int addr; addrBytes = inetAddress.getAddress(); addr = ((addrBytes[3] & 0xff) << 24) | ((addrBytes[2] & 0xff) << 16) | ((addrBytes[1] & 0xff) << 8) | (addrBytes[0] & 0xff); return addr; } public void sendMMS(final String[] recipient, final MMSPart[] parts) { if (settings.getWifiMmsFix()) { WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); settings.currentWifiState = wifi.isWifiEnabled(); settings.currentWifi = wifi.getConnectionInfo(); wifi.disconnect(); settings.discon = new DisconnectWifi(); context.registerReceiver(settings.discon, new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)); settings.currentDataState = isMobileDataEnabled(context); setMobileDataEnabled(context, true); } ConnectivityManager mConnMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); final int result = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS"); if (result != 0) { IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context1, Intent intent) { String action = intent.getAction(); if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) { return; } @SuppressWarnings("deprecation") NetworkInfo mNetworkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if ((mNetworkInfo == null) || (mNetworkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) { return; } if (!mNetworkInfo.isConnected()) { return; } else { sendData(recipient, parts); context.unregisterReceiver(this); } } }; context.registerReceiver(receiver, filter); } else { sendData(recipient, parts); } } public void sendData(final String[] recipients, final MMSPart[] parts) { new Thread(new Runnable() { @Override public void run() { final SendReq sendRequest = new SendReq(); for (int i = 0; i < recipients.length; i++) { final EncodedStringValue[] phoneNumbers = EncodedStringValue.extract(recipients[i]); if (phoneNumbers != null && phoneNumbers.length > 0) { sendRequest.addTo(phoneNumbers[0]); } } final PduBody pduBody = new PduBody(); if (parts != null) { for (MMSPart part : parts) { if (part != null) { try { final PduPart partPdu = new PduPart(); partPdu.setName(part.Name.getBytes()); partPdu.setContentType(part.MimeType.getBytes()); partPdu.setData(part.Data); pduBody.addPart(partPdu); } catch (Exception e) { } } } } sendRequest.setBody(pduBody); final PduComposer composer = new PduComposer(context, sendRequest); final byte[] bytesToSend = composer.make(); List<APN> apns = new ArrayList<APN>(); try { APNHelper helper = new APNHelper(context); apns = helper.getMMSApns(); } catch (Exception e) { Log.v("apn_error", "could not retrieve system apns, using manual values instead"); APN apn = new APN(settings.getMmsc(), settings.getPort(), settings.getProxy()); apns.add(apn); String mmscUrl = apns.get(0).MMSCenterUrl != null ? apns.get(0).MMSCenterUrl.trim() : null; apns.get(0).MMSCenterUrl = mmscUrl; } trySending(apns.get(0), bytesToSend, false); } }).start(); } private void trySending(APN apns, byte[] bytesToSend, boolean retrying) { try { Log.v("apns_to_use", apns.MMSCenterUrl + " " + apns.MMSPort + " " + apns.MMSProxy); ensureRouteToHost(apns.MMSCenterUrl, apns.MMSProxy); HttpUtils.httpConnection(context, -1L, apns.MMSCenterUrl, bytesToSend, HttpUtils.HTTP_POST_METHOD, !TextUtils.isEmpty(apns.MMSProxy), apns.MMSProxy, Integer.parseInt(apns.MMSPort)); IntentFilter filter = new IntentFilter(); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Cursor query = context.getContentResolver().query(Uri.parse("content://mms"), new String[] {"_id"}, null, null, "date desc"); query.moveToFirst(); String id = query.getString(query.getColumnIndex("_id")); query.close(); ContentValues values = new ContentValues(); values.put("msg_box", 2); String where = "_id" + " = '" + id + "'"; context.getContentResolver().update(Uri.parse("content://mms"), values, where, null); context.sendBroadcast(new Intent("com.klinker.android.send_message.REFRESH")); context.unregisterReceiver(this); if (settings.getWifiMmsFix()) { try { context.unregisterReceiver(settings.discon); } catch (Exception e) { } WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(false); wifi.setWifiEnabled(settings.currentWifiState); wifi.reconnect(); setMobileDataEnabled(context, settings.currentDataState); } } }; context.registerReceiver(receiver, filter); } catch (IOException e) { e.printStackTrace(); if (!retrying) { // sleep and try again in three seconds to see if that give wifi and mobile data a chance to toggle in time try { Thread.sleep(3000); } catch (Exception f) { } trySending(apns, bytesToSend, true); } else { if (settings.getWifiMmsFix()) { try { context.unregisterReceiver(settings.discon); } catch (Exception f) { } WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); wifi.setWifiEnabled(false); wifi.setWifiEnabled(settings.currentWifiState); wifi.reconnect(); setMobileDataEnabled(context, settings.currentDataState); } Cursor query = context.getContentResolver().query(Uri.parse("content://mms"), new String[] {"_id"}, null, null, "date desc"); query.moveToFirst(); String id = query.getString(query.getColumnIndex("_id")); query.close(); ContentValues values = new ContentValues(); values.put("msg_box", 5); String where = "_id" + " = '" + id + "'"; context.getContentResolver().update(Uri.parse("content://mms"), values, where, null); ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content).post(new Runnable() { @Override public void run() { context.sendBroadcast(new Intent("com.klinker.android.send_message.REFRESH")); context.sendBroadcast(new Intent("com.klinker.android.send_message.MMS_ERROR")); } }); } } } }
false
true
private void sendSmsMessage(String text, String[] addresses, String threadId) { String SENT = "com.klinker.android.send_message.SMS_SENT"; String DELIVERED = "com.klinker.android.send_message.SMS_DELIVERED"; PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0); PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED), 0); ArrayList<PendingIntent> sPI = new ArrayList<PendingIntent>(); ArrayList<PendingIntent> dPI = new ArrayList<PendingIntent>(); String body = text; if (settings.getStripUnicode()) { body = StripAccents.stripAccents(body); } if (!settings.getSignature().equals("")) { body += "\n" + settings.getSignature(); } SmsManager smsManager = SmsManager.getDefault(); if (settings.getSplit()) { int length = 160; String patternStr = "[^" + GSM_CHARACTERS_REGEX + "]"; Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(body); if (matcher.find()) { length = 70; } boolean counter = false; if (settings.getSplitCounter()) { counter = true; length -= 7; } String[] textToSend = splitByLength(body, length, counter); for (int i = 0; i < textToSend.length; i++) { ArrayList<String> parts = smsManager.divideMessage(textToSend[i]); for (int j = 0; j < parts.size(); j++) { sPI.add(sentPI); dPI.add(deliveredPI); } for (int j = 0; j < addresses.length; j++) { smsManager.sendMultipartTextMessage(addresses[j], null, parts, sPI, settings.getDeliveryReports() ? dPI : null); } } } else { ArrayList<String> parts = smsManager.divideMessage(body); for (int i = 0; i < parts.size(); i++) { sPI.add(sentPI); dPI.add(deliveredPI); } try { for (int i = 0; i < addresses.length; i++) { smsManager.sendMultipartTextMessage(addresses[i], null, parts, sPI, settings.getDeliveryReports() ? dPI : null); } } catch (Exception e) { e.printStackTrace(); try { ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content).post(new Runnable() { @Override public void run() { Toast.makeText(context, "Error, check the \"Split SMS\" option in advanced settings and retry.", Toast.LENGTH_LONG).show(); } }); } catch (Exception f) { } } } if (!settings.getSignature().equals("")) { text += "\n" + settings.getSignature(); } for (int i = 0; i < addresses.length; i++) { Calendar cal = Calendar.getInstance(); ContentValues values = new ContentValues(); values.put("address", addresses[i]); values.put("body", settings.getStripUnicode() ? StripAccents.stripAccents(text) : text); values.put("date", cal.getTimeInMillis() + ""); values.put("read", 1); if (threadId == null || addresses.length > 1) { threadId = Telephony.Threads.getOrCreateThreadId(context, addresses[i]) + ""; } values.put("thread_id", threadId); context.getContentResolver().insert(Uri.parse("content://sms/outbox"), values); } }
private void sendSmsMessage(String text, String[] addresses, String threadId) { String SENT = "com.klinker.android.send_message.SMS_SENT"; String DELIVERED = "com.klinker.android.send_message.SMS_DELIVERED"; PendingIntent sentPI = PendingIntent.getBroadcast(context, 0, new Intent(SENT), 0); PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0, new Intent(DELIVERED), 0); ArrayList<PendingIntent> sPI = new ArrayList<PendingIntent>(); ArrayList<PendingIntent> dPI = new ArrayList<PendingIntent>(); String body = text; if (settings.getStripUnicode()) { body = StripAccents.stripAccents(body); } if (!settings.getSignature().equals("")) { body += "\n" + settings.getSignature(); } SmsManager smsManager = SmsManager.getDefault(); if (settings.getSplit()) { int length = 160; String patternStr = "[^" + GSM_CHARACTERS_REGEX + "]"; Pattern pattern = Pattern.compile(patternStr); Matcher matcher = pattern.matcher(body); if (matcher.find()) { length = 70; } boolean counter = false; if (settings.getSplitCounter()) { counter = true; length -= 7; } String[] textToSend = splitByLength(body, length, counter); for (int i = 0; i < textToSend.length; i++) { ArrayList<String> parts = smsManager.divideMessage(textToSend[i]); for (int j = 0; j < parts.size(); j++) { sPI.add(sentPI); dPI.add(settings.getDeliveryReports() ? deliveredPI : null); } for (int j = 0; j < addresses.length; j++) { smsManager.sendMultipartTextMessage(addresses[j], null, parts, sPI, dPI); } } } else { ArrayList<String> parts = smsManager.divideMessage(body); for (int i = 0; i < parts.size(); i++) { sPI.add(sentPI); dPI.add(settings.getDeliveryReports() ? deliveredPI : null); } try { for (int i = 0; i < addresses.length; i++) { smsManager.sendMultipartTextMessage(addresses[i], null, parts, sPI, dPI); } } catch (Exception e) { e.printStackTrace(); try { ((Activity) context).getWindow().getDecorView().findViewById(android.R.id.content).post(new Runnable() { @Override public void run() { Toast.makeText(context, "Error, check the \"Split SMS\" option in advanced settings and retry.", Toast.LENGTH_LONG).show(); } }); } catch (Exception f) { } } } if (!settings.getSignature().equals("")) { text += "\n" + settings.getSignature(); } for (int i = 0; i < addresses.length; i++) { Calendar cal = Calendar.getInstance(); ContentValues values = new ContentValues(); values.put("address", addresses[i]); values.put("body", settings.getStripUnicode() ? StripAccents.stripAccents(text) : text); values.put("date", cal.getTimeInMillis() + ""); values.put("read", 1); if (threadId == null || addresses.length > 1) { threadId = Telephony.Threads.getOrCreateThreadId(context, addresses[i]) + ""; } values.put("thread_id", threadId); context.getContentResolver().insert(Uri.parse("content://sms/outbox"), values); } }
diff --git a/src/main/java/kr/co/vcnc/haeinsa/HaeinsaTransactionManager.java b/src/main/java/kr/co/vcnc/haeinsa/HaeinsaTransactionManager.java index 13fc6f8..f8982a8 100644 --- a/src/main/java/kr/co/vcnc/haeinsa/HaeinsaTransactionManager.java +++ b/src/main/java/kr/co/vcnc/haeinsa/HaeinsaTransactionManager.java @@ -1,230 +1,230 @@ /** * Copyright (C) 2013 VCNC, 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 kr.co.vcnc.haeinsa; import java.io.IOException; import java.nio.ByteBuffer; import javax.annotation.Nullable; import kr.co.vcnc.haeinsa.exception.DanglingRowLockException; import kr.co.vcnc.haeinsa.thrift.TRowLocks; import kr.co.vcnc.haeinsa.thrift.generated.TRowKey; import kr.co.vcnc.haeinsa.thrift.generated.TRowLock; import kr.co.vcnc.haeinsa.thrift.generated.TRowLockState; import com.google.common.base.Objects; /** * Manager class of {@link HaeinsaTransaction}. * This class contains {@link HaeinsaTablePool} inside to provide tablePool when user want to access * HBase through {@link HaeinsaTransaction} with {@link HaeinsaTable} and execute transaction. * <p> * HaeinsaTransactionManager also provides method to recover failed transaction from TRowLock in HBase * which can be used to clear it up or complete it. */ public class HaeinsaTransactionManager { private final HaeinsaTablePool tablePool; /** * Constructor for TransactionManager * * @param tablePool HaeinsaTablePool to access HBase. */ public HaeinsaTransactionManager(HaeinsaTablePool tablePool) { this.tablePool = tablePool; } /** * Get {@link HaeinsaTransaction} instance which can be used to start new * transaction. * <p> * This method is thread-safe. * * @return new Transaction instance have reference to this manager instance. */ public HaeinsaTransaction begin() { return new HaeinsaTransaction(this); } /** * Make new {@link HaeinsaTransaction} instance which can be used to recover * other failed/uncompleted transaction. Also read and recover primaryRowKey and primaryRowLock * from failed transaction on HBase. * <p> * This method is thread-safe. * * @param tableName TableName of Transaction to recover. * @param row Row of Transaction to recover. * @return Transaction instance if there is any ongoing Transaction on row, * return null otherwise. * @throws IOException */ @Nullable protected HaeinsaTransaction getTransaction(byte[] tableName, byte[] row) throws IOException { TRowLock unstableRowLock = getUnstableRowLock(tableName, row); if (unstableRowLock == null) { // There is no on-going transaction on the row. return null; } TRowLock primaryRowLock = null; TRowKey primaryRowKey = null; - if (!TRowLocks.isPrimary(unstableRowLock)) { + if (TRowLocks.isPrimary(unstableRowLock)) { // this row is primary row, because primary field is not set. primaryRowKey = new TRowKey(ByteBuffer.wrap(tableName), ByteBuffer.wrap(row)); primaryRowLock = unstableRowLock; } else { primaryRowKey = unstableRowLock.getPrimary(); primaryRowLock = getRowLock(primaryRowKey.getTableName(), primaryRowKey.getRow()); TRowKey rowKey = new TRowKey().setTableName(tableName).setRow(row); if (!TRowLocks.isSecondaryOf(primaryRowLock, rowKey, unstableRowLock)) { checkDanglingRowLock(tableName, row, unstableRowLock); return null; } } return getTransactionFromPrimary(primaryRowKey, primaryRowLock); } /** * Get Unstable state of {@link TRowLock} from given row. Returns null if * {@link TRowLock} is {@link TRowLockState#STABLE}. * * @param tableName Table name of the row * @param row Row key of the row * @return null if TRowLock is {@link TRowLockState#STABLE}, otherwise * return rowLock from HBase. * @throws IOException When error occurs in HBase. */ private TRowLock getUnstableRowLock(byte[] tableName, byte[] row) throws IOException { TRowLock rowLock = getRowLock(tableName, row); if (rowLock.getState() == TRowLockState.STABLE) { return null; } else { return rowLock; } } /** * Get {@link TRowLock} from given row. * * @param tableName Table name of the row * @param row Row key of the row * @return RowLock of given row from HBase * @throws IOException When error occurs in HBase. */ private TRowLock getRowLock(byte[] tableName, byte[] row) throws IOException { TRowLock rowLock = null; try (HaeinsaTableIfaceInternal table = tablePool.getTableInternal(tableName)) { // access to HBase rowLock = table.getRowLock(row); } return rowLock; } /** * Check if given {@link TRowLock} is dangling RowLock. RowLock is in * dangling if the RowLock is secondary lock and the primary of the RowLock * doesn't have the RowLock as secondary. * * @param tableName TableName of Transaction to check dangling RowLock. * @param row Row of Transaction to check dangling RowLock. * @param rowLock RowLock to check if it is dangling * @throws IOException When error occurs. Especially throw * {@link DanglingRowLockException}if given RowLock is dangling. */ private void checkDanglingRowLock(byte[] tableName, byte[] row, TRowLock rowLock) throws IOException { TRowLock previousRowLock = rowLock; TRowLock currentRowLock = getRowLock(tableName, row); // It is not a dangling RowLock if RowLock is changed. if (Objects.equal(previousRowLock, currentRowLock)) { if (!TRowLocks.isPrimary(currentRowLock)) { TRowKey primaryRowKey = currentRowLock.getPrimary(); TRowLock primaryRowLock = getRowLock(primaryRowKey.getTableName(), primaryRowKey.getRow()); TRowKey secondaryRowKey = new TRowKey().setTableName(tableName).setRow(row); if (!TRowLocks.isSecondaryOf(primaryRowLock, secondaryRowKey, currentRowLock)) { throw new DanglingRowLockException(secondaryRowKey, "Primary lock doesn't have rowLock as secondary."); } } } } /** * Recover TRowLocks of failed HaeinsaTransaction from primary row on HBase. * Transaction information about secondary rows are recovered with {@link #addSecondaryRowLock()}. * HaeinsaTransaction made by this method do not assign proper values on mutations variable. * * @param rowKey * @param primaryRowLock * @return * @throws IOException */ private HaeinsaTransaction getTransactionFromPrimary(TRowKey rowKey, TRowLock primaryRowLock) throws IOException { HaeinsaTransaction transaction = new HaeinsaTransaction(this); transaction.setPrimary(rowKey); transaction.setCommitTimestamp(primaryRowLock.getCommitTimestamp()); HaeinsaTableTransaction primaryTableTxState = transaction.createOrGetTableState(rowKey.getTableName()); HaeinsaRowTransaction primaryRowTxState = primaryTableTxState.createOrGetRowState(rowKey.getRow()); primaryRowTxState.setCurrent(primaryRowLock); if (primaryRowLock.getSecondariesSize() > 0) { for (TRowKey secondaryRow : primaryRowLock.getSecondaries()) { addSecondaryRowLock(transaction, secondaryRow); } } return transaction; } /** * Recover TRowLock of secondary row inferred from {@link TRowLock#secondaries} field of primary row lock. * <p> * If target secondary row is in stable state, the row does not included in recovered HaeinsaTransaction * because it suggest that this secondary row is already stabled by previous failed transaction. * <p> * Secondary row is not included in recovered transaction neither when commitTimestamp is different with primary row's, * because it implicates that the row is locked by other transaction. * <p> * As similar to {@link #getTransactionFromPrimary()}, rowTransaction added by this method do not have * proper mutations variable. * * @param transaction * @param rowKey * @throws IOException */ private void addSecondaryRowLock(HaeinsaTransaction transaction, TRowKey rowKey) throws IOException { TRowLock unstableRowLock = getUnstableRowLock(rowKey.getTableName(), rowKey.getRow()); if (unstableRowLock == null) { return; } // commitTimestamp가 다르면, 다른 Transaction 이므로 추가하면 안됨 if (unstableRowLock.getCommitTimestamp() != transaction.getCommitTimestamp()) { return; } HaeinsaTableTransaction tableState = transaction.createOrGetTableState(rowKey.getTableName()); HaeinsaRowTransaction rowState = tableState.createOrGetRowState(rowKey.getRow()); rowState.setCurrent(unstableRowLock); } /** * @return HaeinsaTablePool contained in TransactionManager */ public HaeinsaTablePool getTablePool() { return tablePool; } }
true
true
protected HaeinsaTransaction getTransaction(byte[] tableName, byte[] row) throws IOException { TRowLock unstableRowLock = getUnstableRowLock(tableName, row); if (unstableRowLock == null) { // There is no on-going transaction on the row. return null; } TRowLock primaryRowLock = null; TRowKey primaryRowKey = null; if (!TRowLocks.isPrimary(unstableRowLock)) { // this row is primary row, because primary field is not set. primaryRowKey = new TRowKey(ByteBuffer.wrap(tableName), ByteBuffer.wrap(row)); primaryRowLock = unstableRowLock; } else { primaryRowKey = unstableRowLock.getPrimary(); primaryRowLock = getRowLock(primaryRowKey.getTableName(), primaryRowKey.getRow()); TRowKey rowKey = new TRowKey().setTableName(tableName).setRow(row); if (!TRowLocks.isSecondaryOf(primaryRowLock, rowKey, unstableRowLock)) { checkDanglingRowLock(tableName, row, unstableRowLock); return null; } } return getTransactionFromPrimary(primaryRowKey, primaryRowLock); }
protected HaeinsaTransaction getTransaction(byte[] tableName, byte[] row) throws IOException { TRowLock unstableRowLock = getUnstableRowLock(tableName, row); if (unstableRowLock == null) { // There is no on-going transaction on the row. return null; } TRowLock primaryRowLock = null; TRowKey primaryRowKey = null; if (TRowLocks.isPrimary(unstableRowLock)) { // this row is primary row, because primary field is not set. primaryRowKey = new TRowKey(ByteBuffer.wrap(tableName), ByteBuffer.wrap(row)); primaryRowLock = unstableRowLock; } else { primaryRowKey = unstableRowLock.getPrimary(); primaryRowLock = getRowLock(primaryRowKey.getTableName(), primaryRowKey.getRow()); TRowKey rowKey = new TRowKey().setTableName(tableName).setRow(row); if (!TRowLocks.isSecondaryOf(primaryRowLock, rowKey, unstableRowLock)) { checkDanglingRowLock(tableName, row, unstableRowLock); return null; } } return getTransactionFromPrimary(primaryRowKey, primaryRowLock); }
diff --git a/src/org/sump/analyzer/Label.java b/src/org/sump/analyzer/Label.java index 9458c34..192f6ce 100644 --- a/src/org/sump/analyzer/Label.java +++ b/src/org/sump/analyzer/Label.java @@ -1,91 +1,91 @@ /* * Copyright (C) 2012 John Pritchard * * 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 2 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, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110, USA * */ package org.sump.analyzer; import java.awt.event.ActionEvent; import java.util.Map; import java.util.HashMap; import javax.swing.AbstractButton; import javax.swing.ImageIcon; /** * @see MainWindow * @version 0.8 * @author John Pritchard */ public enum Label { Open("Open"), SaveAs("Save as"), OpenProject("Open Project"), SaveProjectAs("Save Project as"), Capture("Capture"), RepeatCapture("Repeat Capture"), Exit("Exit"), ZoomIn("Zoom In"), ZoomOut("Zoom Out"), DefaultZoom("Default Zoom"), ZoomFit("Zoom Fit"), GotoTrigger("Goto Trigger"), GotoA("Goto A"), GotoB("Goto B"), DiagramSettings("Diagram Settings"), Labels("Labels"), Cursors("Cursors"), About("About"), ComboBoxChanged("Combo box changed"), Controller("Controller"), UNKNOWN("UNKNOWN"); private final static Map<String,Label> LabelMap = new HashMap(); static { for (Label label: Label.values()){ LabelMap.put(label.label,label); } } public final static Label For(String name){ Label label = LabelMap.get(name); if (null != label) return label; else return Label.UNKNOWN; } public final static String For(ActionEvent evt){ String label = evt.getActionCommand(); - if (null == Label.For(label)){ + if (Label.UNKNOWN == Label.For(label)){ Object source = evt.getSource(); if (source instanceof AbstractButton){ return ((ImageIcon)((AbstractButton)source).getIcon()).getDescription(); } } return label; } public final String label; private Label(String label){ this.label = label; } }
true
true
public final static String For(ActionEvent evt){ String label = evt.getActionCommand(); if (null == Label.For(label)){ Object source = evt.getSource(); if (source instanceof AbstractButton){ return ((ImageIcon)((AbstractButton)source).getIcon()).getDescription(); } } return label; }
public final static String For(ActionEvent evt){ String label = evt.getActionCommand(); if (Label.UNKNOWN == Label.For(label)){ Object source = evt.getSource(); if (source instanceof AbstractButton){ return ((ImageIcon)((AbstractButton)source).getIcon()).getDescription(); } } return label; }
diff --git a/Courseworks/201011/Two/Game.java b/Courseworks/201011/Two/Game.java index be293a2..b8e7907 100644 --- a/Courseworks/201011/Two/Game.java +++ b/Courseworks/201011/Two/Game.java @@ -1,254 +1,257 @@ // Oliver Kullmann, 6.12.2010 (Swansea) /* After construction, an object G of type Game offers G.get_move_sequence(), a copy of the array of valid half-moves (null iff the move-sequence was syntactically invalid), plus the input data via constant data members. */ class Game { public final String white_won = "1-0", black_won = "0-1", draw = "1/2-1/2", unknown = "*"; public final String event, site, date, name_w, name_b, result, movetext, fen; public final int round; public final boolean monitor; private int num_halfmoves; // -1 iff invalid movetext private int num_valid_halfmoves; private String simplified_movetext; private final Board B; private final Moves M; private char[][] move_seq; /* A single move is a char-array of length 6, 3 or 4, where the first char is 'w' or 'b' ("white" or "black"), followed by 'c' for "check" or 'm' for "mate" or '-' for neither, followed either - by the initial field and the target field (each as (file, rank)) - or by 'k' or 'q' for the kingside resp. queenside castling - or by file and figure for a pawn promotion. If an invalid move is found, then from this move on all array-pointers will be null. If the move-sequence was syntactically invalid, then move_seq is null. */ public Game(final String ev, final String si, final String da, final int ro, final String nw, final String nb, final String re, final String mo, final String fe, final boolean mon) { assert(!ev.isEmpty()); assert(!si.isEmpty()); assert(!da.isEmpty()); assert(!nw.isEmpty()); assert(!nb.isEmpty()); assert(re.equals(white_won) || re.equals(black_won) || re.equals(draw) || re.equals(unknown)); assert(fe.isEmpty() || Board.validFEN(fe)); // if fen is empty then the standard position is used event = ev; site = si; date = da; round = ro; name_w = nw; name_b = nb; result = re; movetext = mo; fen = fe; monitor = mon; if (fen.isEmpty()) B = new Board(); else B = new Board(fen); num_halfmoves = -1; valid_move_sequence(); M = new Moves(B); num_valid_halfmoves = 0; move_seq = null; if (num_halfmoves != -1) fill_move_seq(); if (monitor) System.out.println(this); } // checks for syntactical correctness (only!); sets num_halfmoves and // simplified_movetext, where num_halfmoves == -1 in case of // a syntactical error: private void valid_move_sequence() { simplified_movetext = remove_comments(movetext); if (simplified_movetext.isEmpty()) return; final String[] parts = simplified_movetext.split("\\s+"); boolean white_current_colour = (B.get_active_colour() == 'w'); int fullmoves = B.get_fullmoves(); String new_movetext = ""; boolean read_number = true; for (int i = 0; i < parts.length; ++i) { if (white_current_colour) { if (read_number) { if (convert(parts[i],true) != fullmoves) { num_halfmoves = -1; return; } else read_number = false; } else { if (! valid_movement(parts[i])) { num_halfmoves = -1; return; } else { ++num_halfmoves; new_movetext += parts[i] + " "; white_current_colour = false; read_number = true; } } } else { if (read_number) if (convert(parts[i],false) == fullmoves) { read_number = false; continue; } if (! valid_movement(parts[i])) { num_halfmoves = -1; return; } else { ++num_halfmoves; new_movetext += parts[i] + " "; white_current_colour = true; read_number = true; ++fullmoves; } } } simplified_movetext = new_movetext; } // removes comments, returning the empty string in case of error; assumes // that "{" or "}" are not used in comments opened by ";": private static String remove_comments(String seq) { // first removing comments of the form "{...}": for (int opening_bracket = seq.indexOf("{"); opening_bracket != -1; opening_bracket = seq.indexOf("{")) { final int closing_bracket = seq.indexOf("}"); if (closing_bracket < opening_bracket) return ""; seq = seq.substring(0,opening_bracket) + seq.substring(closing_bracket+1); } if (seq.contains("}")) return ""; // now removing comments of the form ";... EOL": for (int semicolon = seq.indexOf(";"); semicolon != -1; semicolon = seq.indexOf(";")) { final int eol = seq.indexOf("\n",semicolon); if (eol == -1) return ""; seq = seq.substring(0,semicolon) + seq.substring(eol+1); } return seq; } // converts for example "32." into 32 (for white) and "4..." into 4 (for // black), while invalid move-numbers result in -1: private static int convert(final String s, final boolean white) { assert(!s.contains(" ")); final int index = s.indexOf("."); if (index == -1) return -1; if (white) { if (index+1 != s.length()) return -1; } else { if (s.length() - index != 3) return -1; if (s.charAt(index+1) != '.' || s.charAt(index+2) != '.') return -1; } int result; try { result = Integer.parseInt(s.substring(0,index)); } catch (RuntimeException e) { return -1; } if (result < 1) return -1; return result; } // checks whether m represents a valid SAN (like "e4" or "Bb5xa6+"): private static boolean valid_movement(final String m) { // XXX return true; } // computing the move-sequence from the from simplified_movetext, determining // num_valid_halfmoves and move_seq: private void fill_move_seq() { move_seq = new char[num_halfmoves][]; // XXX fill move_seq with the moves while (num_valid_halfmoves < num_halfmoves) { if (move_seq[num_valid_halfmoves] != null) ++num_valid_halfmoves; else break; } } public char[][] get_move_sequence() { if (move_seq == null) return null; assert(num_valid_halfmoves >= 0); final char[][] result = new char[num_valid_halfmoves][]; for (int i = 0; i < num_valid_halfmoves; ++i) { final int items_move = move_seq[i].length; result[i] = new char[items_move]; for (int j = 0; j < items_move; ++j) result[i][j] = move_seq[i][j]; } return move_seq; } public String toString() { String s = ""; s += "Event: " + event + "\n"; s += "Site: " + site + "\n"; s += "Date: " + date + "\n"; s += "Round: " + round + "\n"; s += "White: " + name_w + "\n"; s += "Black: " + name_b + "\n"; s += "Result: " + result + "\n"; s += B; if (num_halfmoves == -1) s += "Invalid move sequence.\n"; return s; } // unit testing: public static void main(final String[] args) { // construction { final String ev1 = "F/S Return Match", si1 = "Belgrade, Serbia Yugoslavia|JUG", da1 = "1992.11.04", nw1 = "Fischer, Robert J.", nb1 = "Spassky, Boris V.", re1 = "1/2-1/2", mo1_0 = "1. e4 e5 2. Nf3 Nc6 3. Bb5 {This opening is called Ruy Lopez.} 3... a6 4. Ba4 Nf6 5. 0-0 Be7 6. Re1 b5 7. Bb3 d6 8. c3 0-0 9. h3 Nb8 10. d4 Nbd7 11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5 Nxe4 18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21. Nc4 Nxc4 22. Bxc4 Nb6 23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3 Qg5 28. Qxg5 hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5 33. f3 Bc8 34. Kfe Bf5 35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3 Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6 Nf2 42. g4 Bd3 43. Re6", mo1_1 = " 1/2-1/2", mo1 = mo1_0 + mo1_1, fe1 = ""; final int ro1 = 29; final Game g1 = new Game(ev1,si1,da1,ro1,nw1,nb1,re1,mo1,fe1,true); assert(g1.event == ev1); assert(g1.site == si1); assert(g1.date == da1); assert(g1.round == ro1); assert(g1.name_w == nw1); assert(g1.name_b == nb1); assert(g1.result == re1); assert(g1.movetext == mo1); assert(g1.fen == fe1); final char[][] ms1 = g1.get_move_sequence(); assert(ms1 != null); assert(ms1.length == 85); final String ev2="x",si2="x",da2="x",nw2="x",nb2="x",re2="1/2-1/2",mo2="1. 1/2-1/2",fe2=""; final int ro2 = 0; final Game g2 = new Game(ev2,si2,da2,ro2,nw2,nb2,re2,mo2,fe2,true); final char[][] ms2 = g2.get_move_sequence(); assert(ms2 != null); assert(ms2.length == 0); + final Game g3 = new Game(ev2,si2,da2,ro2,nw2,nb2,re2,"1. e4",fe2,true); + final char[][] ms3 = g3.get_move_sequence(); + assert(ms3 == null); } // syntax check { assert(remove_comments("").equals("")); assert(remove_comments("{").equals("")); assert(remove_comments("}").equals("")); assert(remove_comments("{}").equals("")); assert(remove_comments("xyz { jyt } kjh { bvc po5 } ").equals("xyz kjh ")); assert(remove_comments("; \nabc\nxyz;333\n").equals("abc\nxyz")); assert(remove_comments("sdjd{,,l;}; djsks\n{ ]}sjfdk ").equals("sdjdsjfdk ")); assert(remove_comments(";abc").equals("")); assert(remove_comments(";]\na").equals("a")); assert(remove_comments(";}\na").equals("")); assert(convert("",true) == -1); assert(convert("",false) == -1); assert(convert("x",true) == -1); assert(convert("x",false) == -1); assert(convert(".",true) == -1); assert(convert(".",false) == -1); assert(convert("44..",true) == -1); assert(convert("44..",false) == -1); assert(convert("33.",true) == 33); assert(convert("33.",false) == -1); assert(convert("13...",true) == -1); assert(convert("13...",false) == 13); assert(convert("0.",true) == -1); assert(convert("0.",false) == -1); assert(convert("-2.",true) == -1); assert(convert("-2.",false) == -1); assert(convert("3[3.",true) == -1); assert(convert("3[3.",false) == -1); } } }
true
true
public static void main(final String[] args) { // construction { final String ev1 = "F/S Return Match", si1 = "Belgrade, Serbia Yugoslavia|JUG", da1 = "1992.11.04", nw1 = "Fischer, Robert J.", nb1 = "Spassky, Boris V.", re1 = "1/2-1/2", mo1_0 = "1. e4 e5 2. Nf3 Nc6 3. Bb5 {This opening is called Ruy Lopez.} 3... a6 4. Ba4 Nf6 5. 0-0 Be7 6. Re1 b5 7. Bb3 d6 8. c3 0-0 9. h3 Nb8 10. d4 Nbd7 11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5 Nxe4 18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21. Nc4 Nxc4 22. Bxc4 Nb6 23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3 Qg5 28. Qxg5 hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5 33. f3 Bc8 34. Kfe Bf5 35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3 Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6 Nf2 42. g4 Bd3 43. Re6", mo1_1 = " 1/2-1/2", mo1 = mo1_0 + mo1_1, fe1 = ""; final int ro1 = 29; final Game g1 = new Game(ev1,si1,da1,ro1,nw1,nb1,re1,mo1,fe1,true); assert(g1.event == ev1); assert(g1.site == si1); assert(g1.date == da1); assert(g1.round == ro1); assert(g1.name_w == nw1); assert(g1.name_b == nb1); assert(g1.result == re1); assert(g1.movetext == mo1); assert(g1.fen == fe1); final char[][] ms1 = g1.get_move_sequence(); assert(ms1 != null); assert(ms1.length == 85); final String ev2="x",si2="x",da2="x",nw2="x",nb2="x",re2="1/2-1/2",mo2="1. 1/2-1/2",fe2=""; final int ro2 = 0; final Game g2 = new Game(ev2,si2,da2,ro2,nw2,nb2,re2,mo2,fe2,true); final char[][] ms2 = g2.get_move_sequence(); assert(ms2 != null); assert(ms2.length == 0); } // syntax check { assert(remove_comments("").equals("")); assert(remove_comments("{").equals("")); assert(remove_comments("}").equals("")); assert(remove_comments("{}").equals("")); assert(remove_comments("xyz { jyt } kjh { bvc po5 } ").equals("xyz kjh ")); assert(remove_comments("; \nabc\nxyz;333\n").equals("abc\nxyz")); assert(remove_comments("sdjd{,,l;}; djsks\n{ ]}sjfdk ").equals("sdjdsjfdk ")); assert(remove_comments(";abc").equals("")); assert(remove_comments(";]\na").equals("a")); assert(remove_comments(";}\na").equals("")); assert(convert("",true) == -1); assert(convert("",false) == -1); assert(convert("x",true) == -1); assert(convert("x",false) == -1); assert(convert(".",true) == -1); assert(convert(".",false) == -1); assert(convert("44..",true) == -1); assert(convert("44..",false) == -1); assert(convert("33.",true) == 33); assert(convert("33.",false) == -1); assert(convert("13...",true) == -1); assert(convert("13...",false) == 13); assert(convert("0.",true) == -1); assert(convert("0.",false) == -1); assert(convert("-2.",true) == -1); assert(convert("-2.",false) == -1); assert(convert("3[3.",true) == -1); assert(convert("3[3.",false) == -1); } }
public static void main(final String[] args) { // construction { final String ev1 = "F/S Return Match", si1 = "Belgrade, Serbia Yugoslavia|JUG", da1 = "1992.11.04", nw1 = "Fischer, Robert J.", nb1 = "Spassky, Boris V.", re1 = "1/2-1/2", mo1_0 = "1. e4 e5 2. Nf3 Nc6 3. Bb5 {This opening is called Ruy Lopez.} 3... a6 4. Ba4 Nf6 5. 0-0 Be7 6. Re1 b5 7. Bb3 d6 8. c3 0-0 9. h3 Nb8 10. d4 Nbd7 11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5 Nxe4 18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21. Nc4 Nxc4 22. Bxc4 Nb6 23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3 Qg5 28. Qxg5 hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5 33. f3 Bc8 34. Kfe Bf5 35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3 Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6 Nf2 42. g4 Bd3 43. Re6", mo1_1 = " 1/2-1/2", mo1 = mo1_0 + mo1_1, fe1 = ""; final int ro1 = 29; final Game g1 = new Game(ev1,si1,da1,ro1,nw1,nb1,re1,mo1,fe1,true); assert(g1.event == ev1); assert(g1.site == si1); assert(g1.date == da1); assert(g1.round == ro1); assert(g1.name_w == nw1); assert(g1.name_b == nb1); assert(g1.result == re1); assert(g1.movetext == mo1); assert(g1.fen == fe1); final char[][] ms1 = g1.get_move_sequence(); assert(ms1 != null); assert(ms1.length == 85); final String ev2="x",si2="x",da2="x",nw2="x",nb2="x",re2="1/2-1/2",mo2="1. 1/2-1/2",fe2=""; final int ro2 = 0; final Game g2 = new Game(ev2,si2,da2,ro2,nw2,nb2,re2,mo2,fe2,true); final char[][] ms2 = g2.get_move_sequence(); assert(ms2 != null); assert(ms2.length == 0); final Game g3 = new Game(ev2,si2,da2,ro2,nw2,nb2,re2,"1. e4",fe2,true); final char[][] ms3 = g3.get_move_sequence(); assert(ms3 == null); } // syntax check { assert(remove_comments("").equals("")); assert(remove_comments("{").equals("")); assert(remove_comments("}").equals("")); assert(remove_comments("{}").equals("")); assert(remove_comments("xyz { jyt } kjh { bvc po5 } ").equals("xyz kjh ")); assert(remove_comments("; \nabc\nxyz;333\n").equals("abc\nxyz")); assert(remove_comments("sdjd{,,l;}; djsks\n{ ]}sjfdk ").equals("sdjdsjfdk ")); assert(remove_comments(";abc").equals("")); assert(remove_comments(";]\na").equals("a")); assert(remove_comments(";}\na").equals("")); assert(convert("",true) == -1); assert(convert("",false) == -1); assert(convert("x",true) == -1); assert(convert("x",false) == -1); assert(convert(".",true) == -1); assert(convert(".",false) == -1); assert(convert("44..",true) == -1); assert(convert("44..",false) == -1); assert(convert("33.",true) == 33); assert(convert("33.",false) == -1); assert(convert("13...",true) == -1); assert(convert("13...",false) == 13); assert(convert("0.",true) == -1); assert(convert("0.",false) == -1); assert(convert("-2.",true) == -1); assert(convert("-2.",false) == -1); assert(convert("3[3.",true) == -1); assert(convert("3[3.",false) == -1); } }
diff --git a/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/services/FileSystemServiceImpl.java b/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/services/FileSystemServiceImpl.java index 00729d5..ef13f9c 100644 --- a/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/services/FileSystemServiceImpl.java +++ b/integrar-t-android/src/main/java/org/utn/proyecto/helpful/integrart/integrar_t_android/services/FileSystemServiceImpl.java @@ -1,290 +1,288 @@ package org.utn.proyecto.helpful.integrart.integrar_t_android.services; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.utn.proyecto.helpful.integrart.integrar_t_android.domain.Resource; import org.utn.proyecto.helpful.integrart.integrar_t_android.domain.ResourceType; import org.utn.proyecto.helpful.integrart.integrar_t_android.domain.User; import roboguice.inject.ContextSingleton; import android.content.Context; import android.graphics.drawable.Drawable; import android.media.MediaPlayer; import android.util.Log; import com.google.inject.Inject; @ContextSingleton public class FileSystemServiceImpl implements FileSystemService { private final static String MAIN_PACKAGE = "main"; private Context context; private final FileSystemDataStorage db; private final DataStorageService dbService; private final String userName; @Inject public FileSystemServiceImpl(Context context, DataStorageService db, User user){ this.context = context; this.dbService = db; this.db = new FileSystemDataStorage(db); this.userName = user.getUserName(); } @Override public <T> Resource<T> getResource(String activityName, String resourceName) { return getResource(activityName, MAIN_PACKAGE,resourceName); } @Override public <T> Resource<T> getResource(String activityName, String packageName, String resourceName) { Resource<?>[] resources = db.getResources(userName, activityName, packageName); Resource<?> resource = findByName(resourceName, resources); return buildResourceByType(activityName, packageName, resource); } private Resource<?> findByName(String name, Resource<?>[] resources){ for(Resource<?> resource : resources){ if(resource.getName().equals(name)) return resource; } return null; } @SuppressWarnings("unchecked") protected <T> Resource<T> buildResourceByType(String activityName, String packageName, Resource<?> resource){ if(resource.getType() == ResourceType.IMAGE) return (Resource<T>)buildImageResource(activityName, packageName, (Resource<Drawable>)resource); if(resource.getType() == ResourceType.SOUND) return (Resource<T>)buildSoundResource(activityName, packageName, (Resource<MediaPlayer>)resource); return null; } private FileInputStream buildResourceInputStream(String activityName, String packageName, Resource<?> resource){ String path = getFullPath(activityName, packageName) + "." + resource.getName(); FileInputStream io = null; try { io = context.openFileInput(path); } catch (FileNotFoundException e) { throw new RuntimeException(e); } return io; } protected Resource<Drawable> buildImageResource(String activityName, String packageName, Resource<Drawable> resource){ InputStream io = buildResourceInputStream(activityName, packageName, resource); Drawable d = Drawable.createFromStream(io, "src"); resource.setResource(d); return resource; } protected Resource<MediaPlayer> buildSoundResource(String activityName, String packageName, Resource<MediaPlayer> resource){ FileInputStream io = buildResourceInputStream(activityName, packageName, resource); MediaPlayer sound = new MediaPlayer(); try { sound.setDataSource(io.getFD()); } catch (Exception e) { throw new RuntimeException(e); } resource.setResource(sound); return resource; } protected Resource<?>[] buildResources(String activityName, String packageName, Resource<?>[] resources){ for(Resource<?> resource : resources){ buildResourceByType(activityName, packageName, resource); } return resources; } protected Resource<?>[] buildResourcesByType(String activityName, String packageName, ResourceType type, Resource<?>[] resources){ List<Resource<?>> list = new ArrayList<Resource<?>>(); for(Resource<?> resource : resources){ if(resource.getType().equals(type)){ buildResourceByType(activityName, packageName, resource); list.add(resource); } } return list.toArray(new Resource[0]); } @Override public Resource<?>[] getResources(String activityName, String packageName) { Resource<?>[] resources = db.getResources(userName, activityName, packageName); return buildResources(activityName, packageName, resources); } @Override public Resource<?>[] getResources(String activityName, String packageName, ResourceType type) { Resource<?>[] resources = db.getResources(userName, activityName, packageName); return buildResourcesByType(activityName, packageName, type, resources); } @Override public Resource<?>[] getResources(String activityName) { Resource<?>[] resources = db.getResources(userName, activityName); return buildResources(activityName, MAIN_PACKAGE, resources); } @Override public Resource<?>[] getResources(String activityName, ResourceType type) { Resource<?>[] resources = db.getResources(userName, activityName); return buildResourcesByType(activityName, MAIN_PACKAGE, type, resources); } @Override public String[] getResourcesNames(String activityName, String packageName) { Resource<?>[] resources = db.getResources(userName, activityName); String[] names = new String[resources.length]; for(int i=0;i<resources.length;i++){ names[i] = resources[i].getName(); } return names; } @Override public String[] getResourcesNames(String activityName, String packageName, ResourceType type) { Resource<?>[] resources = db.getResources(userName, activityName); List<String> names = new ArrayList<String>(); for(Resource<?> resource : resources){ if(resource.getType().equals(type)) names.add(resource.getName()); } return names.toArray(new String[0]); } @Override public String[] getResourcesNames(String activityName) { return getResourcesNames(activityName, MAIN_PACKAGE); } @Override public String[] getResourcesNames(String activityName, ResourceType type) { return getResourcesNames(activityName, MAIN_PACKAGE, type); } @Override public void addPackage(String activityName, String packageName) { db.addPackage(userName, activityName, packageName); String activityPackageName = getFullPath(activityName); String fullPackageName = getFullPath(activityName, packageName); File activityDir = context.getDir(activityPackageName, Context.MODE_PRIVATE); File fullDir = context.getDir(fullPackageName, Context.MODE_PRIVATE); if(activityDir == null || fullDir == null){ throw new CanNotCreatePackageException("The package can�t be crated"); } Log.d("FileService", activityDir.getAbsolutePath()); } @Override public void addResource(String activityName, String packageName, Resource<InputStream> resource) { db.addResource(userName, activityName, packageName, resource); String fullPath = getFullPath(activityName, packageName); try { FileOutputStream output = context.openFileOutput(fullPath + "." + resource.getName(),Context.MODE_PRIVATE); - byte[] bytes = new byte[1000]; + InputStream io = resource.getResource(); + byte[] bytes = new byte[1024]; int end = 0; - do{ - end = resource.getResource().read(bytes,0,1000); - output.write(bytes); - }while(end >= 0); - output.flush(); + while((end = io.read(bytes)) != -1 ) + output.write(bytes, 0, end); output.close(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void addResource(String activityName, String packageName, String name, ResourceType type, InputStream io) { Resource<InputStream> resource = new Resource<InputStream>(name, type, io); addResource(activityName, packageName, resource); } @Override public void addResource(String activityName, String packageName, String name, ResourceType type, byte[] bytes) { Resource<Void> resource = new Resource<Void>(name, type); db.addResource(userName, activityName, packageName, resource); String fullPath = getFullPath(activityName, packageName); try { FileOutputStream output = context.openFileOutput(fullPath + "." + resource.getName(),Context.MODE_PRIVATE); output.write(bytes); output.flush(); output.close(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void addResource(String activityName, String packageName, String name, ResourceType type, String data) { Resource<Void> resource = new Resource<Void>(name, type); db.addResource(userName, activityName, packageName, resource); String fullPath = getFullPath(activityName, packageName); dbService.put(fullPath + "." + resource.getName(), data); } @Override public void addResource(String activityName, Resource<InputStream> resource) { addResource(activityName, MAIN_PACKAGE ,resource); } @Override public void addResource(String activityName, String name, ResourceType type, InputStream io) { addResource(activityName, MAIN_PACKAGE, name, type, io); } @Override public void addResource(String activityName, String name, ResourceType type, byte[] bytes) { addResource(activityName, MAIN_PACKAGE, name, type, bytes); } @Override public void addResource(String activityName, String name, ResourceType type, String data) { addResource(activityName, MAIN_PACKAGE, name, type, data); } private String getFullPath(String activityName){ return getFullPath(activityName, null); } private String getFullPath(String activityName, String packageName){ StringBuffer s = new StringBuffer(userName + "." + activityName); if(packageName != null) s.append("." + packageName); return s.toString(); } }
false
true
public void addResource(String activityName, String packageName, Resource<InputStream> resource) { db.addResource(userName, activityName, packageName, resource); String fullPath = getFullPath(activityName, packageName); try { FileOutputStream output = context.openFileOutput(fullPath + "." + resource.getName(),Context.MODE_PRIVATE); byte[] bytes = new byte[1000]; int end = 0; do{ end = resource.getResource().read(bytes,0,1000); output.write(bytes); }while(end >= 0); output.flush(); output.close(); } catch (Exception e) { throw new RuntimeException(e); } }
public void addResource(String activityName, String packageName, Resource<InputStream> resource) { db.addResource(userName, activityName, packageName, resource); String fullPath = getFullPath(activityName, packageName); try { FileOutputStream output = context.openFileOutput(fullPath + "." + resource.getName(),Context.MODE_PRIVATE); InputStream io = resource.getResource(); byte[] bytes = new byte[1024]; int end = 0; while((end = io.read(bytes)) != -1 ) output.write(bytes, 0, end); output.close(); } catch (Exception e) { throw new RuntimeException(e); } }
diff --git a/src/com/studentersamfundet/app/ui/JoinUsActivity.java b/src/com/studentersamfundet/app/ui/JoinUsActivity.java index cc0703e..fb2c944 100644 --- a/src/com/studentersamfundet/app/ui/JoinUsActivity.java +++ b/src/com/studentersamfundet/app/ui/JoinUsActivity.java @@ -1,17 +1,17 @@ package com.studentersamfundet.app.ui; import android.os.Bundle; import android.text.util.Linkify; import android.widget.TextView; import com.studentersamfundet.app.R; public class JoinUsActivity extends BaseDnsActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.join_us); TextView tv = (TextView)findViewById(R.id.join_us_textview); - Linkify.addLinks(tv, Linkify.EMAIL_ADDRESSES); + Linkify.addLinks(tv, Linkify.ALL); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.join_us); TextView tv = (TextView)findViewById(R.id.join_us_textview); Linkify.addLinks(tv, Linkify.EMAIL_ADDRESSES); }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.join_us); TextView tv = (TextView)findViewById(R.id.join_us_textview); Linkify.addLinks(tv, Linkify.ALL); }
diff --git a/src/java/jp/gihyo/jenkinsbook/action/SampleAction.java b/src/java/jp/gihyo/jenkinsbook/action/SampleAction.java index 835e33e..cd2ef79 100755 --- a/src/java/jp/gihyo/jenkinsbook/action/SampleAction.java +++ b/src/java/jp/gihyo/jenkinsbook/action/SampleAction.java @@ -1,71 +1,71 @@ package jp.gihyo.jenkinsbook.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import jp.gihyo.jenkinsbook.dto.SampleDTO; /** * DTO class for SampleServlet. */ public class SampleAction { /** * First name of the user. */ private String firstName; /** * Last name of the user. */ private String lastName; /** * Constructor of SampleAction. */ public SampleAction() { this(null, null); } /** * Constructor of SampleAction. * @param firstName first name of the user * @param lastName last name of the user */ public SampleAction(final String firstName, final String lastName) { this.firstName = firstName; this.lastName = lastName; } /** * Check parameter of http servlet request. * @param request HttpServletRequest * @return check result */ public final boolean checkParameter(final HttpServletRequest request) { firstName = request.getParameter("FirstName"); if ((firstName == null) || ("".equals(firstName))) { return false; } lastName = request.getParameter("LastName"); if ((lastName == null) || ("".equals(lastName))) { - return true; + return false; } return true; } /** * Execute action. * @param request HttpServletRequest * @return result jsp file path */ public final String execute(final HttpServletRequest request) { SampleDTO dto = new SampleDTO(firstName, lastName); HttpSession session = request.getSession(true); session.setAttribute("dto", dto); return "./WEB-INF/result.jsp"; } }
true
true
public final boolean checkParameter(final HttpServletRequest request) { firstName = request.getParameter("FirstName"); if ((firstName == null) || ("".equals(firstName))) { return false; } lastName = request.getParameter("LastName"); if ((lastName == null) || ("".equals(lastName))) { return true; } return true; }
public final boolean checkParameter(final HttpServletRequest request) { firstName = request.getParameter("FirstName"); if ((firstName == null) || ("".equals(firstName))) { return false; } lastName = request.getParameter("LastName"); if ((lastName == null) || ("".equals(lastName))) { return false; } return true; }
diff --git a/src/be/ibridge/kettle/trans/step/sql/ExecSQL.java b/src/be/ibridge/kettle/trans/step/sql/ExecSQL.java index 93964d75..980b0ffe 100644 --- a/src/be/ibridge/kettle/trans/step/sql/ExecSQL.java +++ b/src/be/ibridge/kettle/trans/step/sql/ExecSQL.java @@ -1,257 +1,257 @@ /********************************************************************** ** ** ** This code belongs to the KETTLE project. ** ** ** ** Kettle, from version 2.2 on, is released into the public domain ** ** under the Lesser GNU Public License (LGPL). ** ** ** ** For more details, please read the document LICENSE.txt, included ** ** in this project ** ** ** ** http://www.kettle.be ** ** [email protected] ** ** ** **********************************************************************/ package be.ibridge.kettle.trans.step.sql; import java.util.ArrayList; import be.ibridge.kettle.core.Const; import be.ibridge.kettle.core.Result; import be.ibridge.kettle.core.Row; import be.ibridge.kettle.core.database.Database; import be.ibridge.kettle.core.exception.KettleDatabaseException; import be.ibridge.kettle.core.exception.KettleException; import be.ibridge.kettle.core.exception.KettleStepException; import be.ibridge.kettle.core.value.Value; import be.ibridge.kettle.trans.Trans; import be.ibridge.kettle.trans.TransMeta; import be.ibridge.kettle.trans.step.BaseStep; import be.ibridge.kettle.trans.step.StepDataInterface; import be.ibridge.kettle.trans.step.StepInterface; import be.ibridge.kettle.trans.step.StepMeta; import be.ibridge.kettle.trans.step.StepMetaInterface; /** * Execute one or more SQL statements in a script, one time or parameterised (for every row) * * @author Matt * @since 10-sep-2005 */ public class ExecSQL extends BaseStep implements StepInterface { private ExecSQLMeta meta; private ExecSQLData data; public ExecSQL(StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr, TransMeta transMeta, Trans trans) { super(stepMeta, stepDataInterface, copyNr, transMeta, trans); } public static final Row getResultRow(Result result, String upd, String ins, String del, String read) { Row row = new Row(); if (upd!=null && upd.length()>0) { Value rowsUpdated = new Value(upd, result.getNrLinesUpdated()); rowsUpdated.setLength(9); row.addValue(rowsUpdated); } if (upd!=null && upd.length()>0) { Value rowsInserted = new Value(ins, result.getNrLinesOutput()); rowsInserted.setLength(9); row.addValue(rowsInserted); } if (upd!=null && upd.length()>0) { Value rowsDeleted = new Value(del, result.getNrLinesDeleted()); rowsDeleted.setLength(9); row.addValue(rowsDeleted); } if (upd!=null && upd.length()>0) { Value rowsRead = new Value(read, result.getNrLinesRead()); rowsRead.setLength(9); row.addValue(rowsRead); } return row; } public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(ExecSQLMeta)smi; data=(ExecSQLData)sdi; debug = "execute SQ start"; Row row = null; if (!meta.isExecutedEachInputRow()) { debug = "exec once: return result"; row = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); putRow(row); setOutputDone(); // Stop processing, this is all we do! return false; } row = getRow(); if (row==null) // no more input to be expected... { setOutputDone(); return false; } StringBuffer sql = new StringBuffer( meta.getSql() ); if (first) // we just got started { first=false; debug = "Find the indexes of the arguments"; // Find the indexes of the arguments data.argumentIndexes = new int[meta.getArguments().length]; for (int i=0;i<meta.getArguments().length;i++) { data.argumentIndexes[i] = row.searchValueIndex(meta.getArguments()[i]); if (data.argumentIndexes[i]<0) { logError("Error finding field: "+meta.getArguments()[i]+"]"); throw new KettleStepException("Couldn't find field '"+meta.getArguments()[i]+"' in row!"); } } debug = "Find the locations of the question marks in the String..."; // Find the locations of the question marks in the String... // We replace the question marks with the values... // We ignore quotes etc. to make inserts easier... data.markerPositions = new ArrayList(); int len = sql.length(); int pos = len-1; while (pos>=0) { if (sql.charAt(pos)=='?') data.markerPositions.add(new Integer(pos)); // save the marker position pos--; } } debug = "Replace the values in the SQL string..."; // Replace the values in the SQL string... for (int i=0;i<data.markerPositions.size();i++) { Value value = row.getValue( data.argumentIndexes[data.markerPositions.size()-i-1]); int pos = ((Integer)data.markerPositions.get(i)).intValue(); sql.replace(pos, pos+1, value.getString()); // replace the '?' with the String in the row. } debug = "Execute sql: "+sql; if (log.isRowLevel()) logRowlevel("Executing SQL script:"+Const.CR+sql); data.result = data.db.execStatements(sql.toString()); debug = "Get result"; Row add = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); row.addRow(add); - data.db.commit(); + if (!data.db.isAutoCommit()) data.db.commit(); putRow(row); // send it out! if ((linesWritten>0) && (linesWritten%Const.ROWS_UPDATE)==0) logBasic("linenr "+linesWritten); return true; } public void dispose(StepMetaInterface smi, StepDataInterface sdi) { meta=(ExecSQLMeta)smi; data=(ExecSQLData)sdi; logBasic("Finished reading query, closing connection."); data.db.disconnect(); super.dispose(smi, sdi); } /** Stop the running query */ public void stopRunning() { try { if (data.db!=null) data.db.cancelQuery(); } catch(KettleDatabaseException e) { } } public boolean init(StepMetaInterface smi, StepDataInterface sdi) { meta=(ExecSQLMeta)smi; data=(ExecSQLData)sdi; if (super.init(smi, sdi)) { data.db=new Database(meta.getDatabaseMeta()); // Connect to the database try { data.db.connect(); if (log.isDetailed()) logDetailed("Connected to database..."); // If the SQL needs to be executed once, this is a starting step somewhere. if (!meta.isExecutedEachInputRow()) { data.result = data.db.execStatements(meta.getSql()); } return true; } catch(KettleException e) { logError("An error occurred, processing will be stopped: "+e.getMessage()); setErrors(1); stopAll(); } } return false; } // // Run is were the action happens! // public void run() { try { logBasic("Starting to run..."); while (!isStopped() && processRow(meta, data) ); } catch(Exception e) { logError("Unexpected error in '"+debug+"' : "+e.toString()); setErrors(1); stopAll(); } finally { dispose(meta, data); logSummary(); markStop(); } } }
true
true
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(ExecSQLMeta)smi; data=(ExecSQLData)sdi; debug = "execute SQ start"; Row row = null; if (!meta.isExecutedEachInputRow()) { debug = "exec once: return result"; row = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); putRow(row); setOutputDone(); // Stop processing, this is all we do! return false; } row = getRow(); if (row==null) // no more input to be expected... { setOutputDone(); return false; } StringBuffer sql = new StringBuffer( meta.getSql() ); if (first) // we just got started { first=false; debug = "Find the indexes of the arguments"; // Find the indexes of the arguments data.argumentIndexes = new int[meta.getArguments().length]; for (int i=0;i<meta.getArguments().length;i++) { data.argumentIndexes[i] = row.searchValueIndex(meta.getArguments()[i]); if (data.argumentIndexes[i]<0) { logError("Error finding field: "+meta.getArguments()[i]+"]"); throw new KettleStepException("Couldn't find field '"+meta.getArguments()[i]+"' in row!"); } } debug = "Find the locations of the question marks in the String..."; // Find the locations of the question marks in the String... // We replace the question marks with the values... // We ignore quotes etc. to make inserts easier... data.markerPositions = new ArrayList(); int len = sql.length(); int pos = len-1; while (pos>=0) { if (sql.charAt(pos)=='?') data.markerPositions.add(new Integer(pos)); // save the marker position pos--; } } debug = "Replace the values in the SQL string..."; // Replace the values in the SQL string... for (int i=0;i<data.markerPositions.size();i++) { Value value = row.getValue( data.argumentIndexes[data.markerPositions.size()-i-1]); int pos = ((Integer)data.markerPositions.get(i)).intValue(); sql.replace(pos, pos+1, value.getString()); // replace the '?' with the String in the row. } debug = "Execute sql: "+sql; if (log.isRowLevel()) logRowlevel("Executing SQL script:"+Const.CR+sql); data.result = data.db.execStatements(sql.toString()); debug = "Get result"; Row add = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); row.addRow(add); data.db.commit(); putRow(row); // send it out! if ((linesWritten>0) && (linesWritten%Const.ROWS_UPDATE)==0) logBasic("linenr "+linesWritten); return true; }
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta=(ExecSQLMeta)smi; data=(ExecSQLData)sdi; debug = "execute SQ start"; Row row = null; if (!meta.isExecutedEachInputRow()) { debug = "exec once: return result"; row = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); putRow(row); setOutputDone(); // Stop processing, this is all we do! return false; } row = getRow(); if (row==null) // no more input to be expected... { setOutputDone(); return false; } StringBuffer sql = new StringBuffer( meta.getSql() ); if (first) // we just got started { first=false; debug = "Find the indexes of the arguments"; // Find the indexes of the arguments data.argumentIndexes = new int[meta.getArguments().length]; for (int i=0;i<meta.getArguments().length;i++) { data.argumentIndexes[i] = row.searchValueIndex(meta.getArguments()[i]); if (data.argumentIndexes[i]<0) { logError("Error finding field: "+meta.getArguments()[i]+"]"); throw new KettleStepException("Couldn't find field '"+meta.getArguments()[i]+"' in row!"); } } debug = "Find the locations of the question marks in the String..."; // Find the locations of the question marks in the String... // We replace the question marks with the values... // We ignore quotes etc. to make inserts easier... data.markerPositions = new ArrayList(); int len = sql.length(); int pos = len-1; while (pos>=0) { if (sql.charAt(pos)=='?') data.markerPositions.add(new Integer(pos)); // save the marker position pos--; } } debug = "Replace the values in the SQL string..."; // Replace the values in the SQL string... for (int i=0;i<data.markerPositions.size();i++) { Value value = row.getValue( data.argumentIndexes[data.markerPositions.size()-i-1]); int pos = ((Integer)data.markerPositions.get(i)).intValue(); sql.replace(pos, pos+1, value.getString()); // replace the '?' with the String in the row. } debug = "Execute sql: "+sql; if (log.isRowLevel()) logRowlevel("Executing SQL script:"+Const.CR+sql); data.result = data.db.execStatements(sql.toString()); debug = "Get result"; Row add = getResultRow(data.result, meta.getUpdateField(), meta.getInsertField(), meta.getDeleteField(), meta.getReadField()); row.addRow(add); if (!data.db.isAutoCommit()) data.db.commit(); putRow(row); // send it out! if ((linesWritten>0) && (linesWritten%Const.ROWS_UPDATE)==0) logBasic("linenr "+linesWritten); return true; }
diff --git a/src/BinaryTreeMaxPath.java b/src/BinaryTreeMaxPath.java index 3275f92..c7b22a7 100644 --- a/src/BinaryTreeMaxPath.java +++ b/src/BinaryTreeMaxPath.java @@ -1,70 +1,72 @@ /* * Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example: Given the below binary tree, 1 / \ 2 3 Return 6. * */ public class BinaryTreeMaxPath { public class TreeNode { private int val; private TreeNode left; private TreeNode right; TreeNode(int x) { val = x; } } public class TreeVal { private int self; private int export; TreeVal() { self = Integer.MIN_VALUE; export = 0; } } public int getMaxSub(TreeVal left, int root, TreeVal right) { int c1 = Math.max(left.self, right.self); int c2 = root; if (left.export > 0) c2 += left.export; if (right.export > 0) c2 += right.export; int out = Math.max(c1, c2); return out; } public TreeVal getTreeVal(TreeNode node) { TreeVal out = new TreeVal(); if (node == null) return out; TreeVal left = getTreeVal(node.left); TreeVal right = getTreeVal(node.right); int childExport = Math.max(left.export, right.export); - out.export = node.val + childExport; + out.export = node.val; + if (childExport > 0) + out.export += childExport; out.self = getMaxSub(left, node.val, right); return out; } public int maxPathSum(TreeNode root) { if (root == null) return 0; TreeVal left = getTreeVal(root.left); TreeVal right = getTreeVal(root.right); return getMaxSub(left, root.val, right); } }
true
true
public TreeVal getTreeVal(TreeNode node) { TreeVal out = new TreeVal(); if (node == null) return out; TreeVal left = getTreeVal(node.left); TreeVal right = getTreeVal(node.right); int childExport = Math.max(left.export, right.export); out.export = node.val + childExport; out.self = getMaxSub(left, node.val, right); return out; }
public TreeVal getTreeVal(TreeNode node) { TreeVal out = new TreeVal(); if (node == null) return out; TreeVal left = getTreeVal(node.left); TreeVal right = getTreeVal(node.right); int childExport = Math.max(left.export, right.export); out.export = node.val; if (childExport > 0) out.export += childExport; out.self = getMaxSub(left, node.val, right); return out; }
diff --git a/src/BotClientSender.java b/src/BotClientSender.java index fe14314..e37be3f 100644 --- a/src/BotClientSender.java +++ b/src/BotClientSender.java @@ -1,40 +1,40 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author geza */ import maslab.telemetry.*; import maslab.telemetry.channel.*; import java.util.*; import javax.swing.*; import java.awt.*; import java.awt.image.*; public class BotClientSender extends java.lang.Thread { public ImageChannel origim = new ImageChannel("origim"); public ImageChannel procim = new ImageChannel("procim"); public BufferedImage origI = null; public BufferedImage procI = null; public boolean running = true; public void start() { while (running) { try { java.lang.Thread.sleep(1000); origim.publish(origI); - origim.publish(procI); + procim.publish(procI); } catch (Exception e) { e.printStackTrace(); } } } public void bye() { running = false; } }
true
true
public void start() { while (running) { try { java.lang.Thread.sleep(1000); origim.publish(origI); origim.publish(procI); } catch (Exception e) { e.printStackTrace(); } } }
public void start() { while (running) { try { java.lang.Thread.sleep(1000); origim.publish(origI); procim.publish(procI); } catch (Exception e) { e.printStackTrace(); } } }
diff --git a/server/src/org/bedework/caldav/server/CaldavComponentNode.java b/server/src/org/bedework/caldav/server/CaldavComponentNode.java index 81ea0cf..28d033e 100644 --- a/server/src/org/bedework/caldav/server/CaldavComponentNode.java +++ b/server/src/org/bedework/caldav/server/CaldavComponentNode.java @@ -1,518 +1,518 @@ /* Copyright (c) 2000-2005 University of Washington. All rights reserved. Redistribution and use of this distribution in source and binary forms, with or without modification, are permitted provided that: The above copyright notice and this permission notice appear in all copies and supporting documentation; The name, identifiers, and trademarks of the University of Washington are not used in advertising or publicity without the express prior written permission of the University of Washington; Recipients acknowledge that this distribution is made available as a research courtesy, "as is", potentially with defects, without any obligation on the part of the University of Washington to provide support, services, or repair; THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ /* ********************************************************************** Copyright 2005 Rensselaer Polytechnic Institute. All worldwide rights reserved. Redistribution and use of this distribution in source and binary forms, with or without modification, are permitted provided that: The above copyright notice and this permission notice appear in all copies and supporting documentation; The name, identifiers, and trademarks of Rensselaer Polytechnic Institute are not used in advertising or publicity without the express prior written permission of Rensselaer Polytechnic Institute; DISCLAIMER: The software is distributed" AS IS" without any express or implied warranty, including but not limited to, any implied warranties of merchantability or fitness for a particular purpose or any warrant)' of non-infringement of any current or pending patent rights. The authors of the software make no representations about the suitability of this software for any particular purpose. The entire risk as to the quality and performance of the software is with the user. Should the software prove defective, the user assumes the cost of all necessary servicing, repair or correction. In particular, neither Rensselaer Polytechnic Institute, nor the authors of the software are liable for any indirect, special, consequential, or incidental damages related to the software, to the maximum extent the law permits. */ package org.bedework.caldav.server; import org.bedework.caldav.server.calquery.CalendarData; import org.bedework.calfacade.BwCalendar; import org.bedework.calfacade.BwEvent; import org.bedework.calfacade.svc.EventInfo; import org.bedework.davdefs.CaldavDefs; import org.bedework.davdefs.CaldavTags; import org.bedework.davdefs.WebdavTags; import org.bedework.icalendar.ComponentWrapper; import org.w3c.dom.Element; import edu.rpi.cct.webdav.servlet.shared.WebdavIntfException; import edu.rpi.cct.webdav.servlet.shared.WebdavProperty; import edu.rpi.cmt.access.Acl.CurrentAccess; import edu.rpi.sss.util.xml.QName; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.Component; import net.fortuna.ical4j.model.component.VEvent; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; /** Class to represent an entity such as events in caldav. * * @author Mike Douglass [email protected] */ public class CaldavComponentNode extends CaldavBwNode { /* The only event or the master */ // private BwEvent event; private EventInfo eventInfo; /* Collection of BwEvent for this node * Only 1 for non-recurring */ private Collection events; /** The Component object */ private VEvent vevent; private Calendar ical; private String veventString; private ComponentWrapper comp; private final static Collection propertyNames = new ArrayList(); static { propertyNames.add(CaldavTags.calendarData); propertyNames.add(ICalTags.dtend); propertyNames.add(ICalTags.dtstart); propertyNames.add(ICalTags.due); propertyNames.add(ICalTags.duration); propertyNames.add(ICalTags.hasAlarm); propertyNames.add(ICalTags.hasAttachment); propertyNames.add(ICalTags.hasRecurrence); propertyNames.add(ICalTags.sequence); propertyNames.add(ICalTags.summary); propertyNames.add(ICalTags.status); propertyNames.add(ICalTags.transp); propertyNames.add(ICalTags.uid); propertyNames.add(WebdavTags.collection); } /** Constructor * * @param cdURI * @param sysi * @param debug */ public CaldavComponentNode(CaldavURI cdURI, SysIntf sysi, boolean debug) { super(cdURI, sysi, debug); collection = false; allowsGet = true; contentLang = "en"; contentLen = -1; contentType = "text/calendar"; } public boolean removeProperty(Element val) throws WebdavIntfException { warn("Unimplemented - removeProperty"); return false; } public boolean setProperty(Element val) throws WebdavIntfException { warn("Unimplemented - setProperty"); return false; } /** Get a vevent form of the only or master event. Mainly for property * filters. * * @return Component * @throws WebdavIntfException */ public Component getVevent() throws WebdavIntfException { init(true); try { if ((eventInfo != null) && (vevent == null)) { Calendar ical = getSysi().toCalendar(eventInfo.getEvent()); if (events.size() == 1) { this.ical = ical; // Save doing it again } vevent = (VEvent)ical.getComponents().getComponent(Component.VEVENT); /* vevent = trans.toIcalEvent(event); ical = trans.newIcal(); IcalUtil.addComponent(ical, vevent); */ // XXX Add the timezones if needed comp = new ComponentWrapper(vevent); } } catch (Throwable t) { throw new WebdavIntfException(t); } return vevent; } /* ==================================================================== * Property methods * ==================================================================== */ /** Get the value for the given property. * * @param pr WebdavProperty defining property * @return PropVal value * @throws WebdavIntfException */ public PropVal generatePropertyValue(WebdavProperty pr) throws WebdavIntfException { PropVal pv = new PropVal(); QName tag = pr.getTag(); String ns = tag.getNamespaceURI(); BwCalendar cal = getCDURI().getCal(); /* Deal with webdav properties */ if ((!ns.equals(CaldavDefs.caldavNamespace) && !ns.equals(CaldavDefs.icalNamespace))) { // Not ours return super.generatePropertyValue(pr); } BwEvent ev = checkEv(pv); if (ev == null) { return pv; } if (tag.equals(ICalTags.summary)) { pv.val = ev.getSummary(); return pv; } if (tag.equals(ICalTags.dtstart)) { - pv.val = ev.getDtstart().toString(); + pv.val = ev.getDtstart().getDate(); return pv; } if (tag.equals(ICalTags.dtend)) { - pv.val = ev.getDtend().toString(); + pv.val = ev.getDtend().getDate(); return pv; } if (tag.equals(ICalTags.duration)) { pv.val = ev.getDuration(); return pv; } if (tag.equals(ICalTags.transp)) { pv.val = ev.getTransparency(); return pv; } /* TODO if (tag.equals(ICalTags.due)) { pv.val = ev. return pv; } */ if (tag.equals(ICalTags.status)) { pv.val = ev.getStatus(); return pv; } if (tag.equals(ICalTags.uid)) { pv.val = ev.getGuid(); return pv; } if (tag.equals(ICalTags.sequence)) { pv.val = String.valueOf(ev.getSequence()); return pv; } /* if (tag.equals(ICalTags.hasRecurrence)) { pv.val = ev return pv; } if (tag.equals(ICalTags.hasAlarm)) { pv.val = ev return pv; } if (tag.equals(ICalTags.hasAttachment)) { pv.val = ev return pv; }*/ pv.notFound = true; return pv; } public void init(boolean content) throws WebdavIntfException { if (!content) { return; } try { if ((eventInfo == null) && exists) { String entityName = cdURI.getEntityName(); if (entityName == null) { return; } if (debug) { debugMsg("SEARCH: compNode retrieve event on path " + cdURI.getCal().getPath() + " with name " + entityName); } if (events == null) { events = getSysi().findEventsByName(cdURI.getCal(), entityName); } if ((events == null) || (events.size() == 0)) { exists = false; } else { if (events.size() == 1) { /* Non recurring or no overrides */ eventInfo = (EventInfo)events.iterator().next(); } else { /* Find the master */ // XXX Check the guids here? Iterator it = events.iterator(); while (it.hasNext()) { EventInfo ei = (EventInfo)it.next(); if (ei.getEvent().getRecurring()) { eventInfo = ei; } } if (eventInfo == null) { throw new WebdavIntfException("Missing master for " + cdURI); } } } } if (eventInfo != null) { BwEvent event = eventInfo.getEvent(); creDate = event.getCreated(); lastmodDate = event.getLastmod(); } name = cdURI.getEntityName(); } catch (WebdavIntfException wie) { throw wie; } catch (Throwable t) { throw new WebdavIntfException(t); } } /** Return a set o QName defining properties this node supports. * * @return * @throws WebdavIntfException */ public Collection getPropertyNames()throws WebdavIntfException { Collection res = new ArrayList(); res.addAll(super.getPropertyNames()); res.addAll(propertyNames); return res; } /** Add an event to our collection. * * @param val */ public void addEvent(BwEvent val) { if (events == null) { events = new ArrayList(); } EventInfo ei = new EventInfo(val); ei.setRecurrenceId(val.getRecurrence().getRecurrenceId()); events.add(ei); } /** Returns the only event or the master event for a recurrence * * @return EventInfo * @throws WebdavIntfException */ public EventInfo getEventInfo() throws WebdavIntfException { init(true); return eventInfo; } /** * @return Calendar * @throws WebdavIntfException */ public Calendar getIcal() throws WebdavIntfException { init(true); try { if (ical == null) { if (events.size() == 1) { ical = getSysi().toCalendar(eventInfo.getEvent()); } else { // recurring ical = getSysi().toCalendar(events); } } if ((veventString == null)) { veventString = ical.toString(); contentLen = veventString.length(); } } catch (Throwable t) { throw new WebdavIntfException(t); } return ical; } public Collection getProperties(String ns) throws WebdavIntfException { init(true); ArrayList al = new ArrayList(); getVevent(); // init comp if (comp == null) { throw new WebdavIntfException("getProperties, comp == null"); } addProp(al, ICalTags.summary, name); addProp(al, ICalTags.dtstart, comp.getDtstart()); addProp(al, ICalTags.dtend, comp.getDtend()); addProp(al, ICalTags.duration, comp.getDuration()); addProp(al, ICalTags.transp, comp.getTransp()); addProp(al, ICalTags.due, comp.getDue()); // addProp(v, ICalTags.completed, | date-time from RFC2518 addProp(al, ICalTags.status, comp.getStatus()); // addProp(v, ICalTags.priority, | integer // addProp(v, ICalTags.percentComplete, | integer addProp(al, ICalTags.uid, comp.getUid()); addProp(al, ICalTags.sequence, comp.getSequence()); // addProp(v, ICalTags.recurrenceId, | date-time from RFC2518 // addProp(v, ICalTags.trigger, | see below TODO // FIXME FIX FIX addProp(al, ICalTags.hasRecurrence, "0"); addProp(al, ICalTags.hasAlarm, "0"); addProp(al, ICalTags.hasAttachment, "0"); /* Default property calendar-data returns all of the object */ al.add(new CalendarData(CaldavTags.calendarData, debug)); return al; } public String getContentString() throws WebdavIntfException { getIcal(); // init content return veventString; } /* ==================================================================== * Overridden property methods * ==================================================================== */ public CurrentAccess getCurrentAccess() throws WebdavIntfException { if (eventInfo == null) { return null; } return eventInfo.getCurrentAccess(); } public void setLastmodDate(String val) throws WebdavIntfException { init(true); super.setLastmodDate(val); } public String getLastmodDate() throws WebdavIntfException { init(true); return super.getLastmodDate(); } public int getContentLen() throws WebdavIntfException { getIcal(); // init length return contentLen; } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("CaldavComponentNode{cduri="); sb.append(getCDURI()); sb.append("}"); return sb.toString(); } /* ==================================================================== * Private methods * ==================================================================== */ private BwEvent getEvent() throws WebdavIntfException { EventInfo ei = getEventInfo(); if (ei == null) { return null; } return ei.getEvent(); } private BwEvent checkEv(PropVal pv) throws WebdavIntfException { BwEvent ev = getEvent(); if (ev == null) { pv.notFound = true; return null; } return ev; } private void addProp(Collection c, QName tag, Object val) { if (val != null) { c.add(new WebdavProperty(tag, String.valueOf(val))); } } }
false
true
public PropVal generatePropertyValue(WebdavProperty pr) throws WebdavIntfException { PropVal pv = new PropVal(); QName tag = pr.getTag(); String ns = tag.getNamespaceURI(); BwCalendar cal = getCDURI().getCal(); /* Deal with webdav properties */ if ((!ns.equals(CaldavDefs.caldavNamespace) && !ns.equals(CaldavDefs.icalNamespace))) { // Not ours return super.generatePropertyValue(pr); } BwEvent ev = checkEv(pv); if (ev == null) { return pv; } if (tag.equals(ICalTags.summary)) { pv.val = ev.getSummary(); return pv; } if (tag.equals(ICalTags.dtstart)) { pv.val = ev.getDtstart().toString(); return pv; } if (tag.equals(ICalTags.dtend)) { pv.val = ev.getDtend().toString(); return pv; } if (tag.equals(ICalTags.duration)) { pv.val = ev.getDuration(); return pv; } if (tag.equals(ICalTags.transp)) { pv.val = ev.getTransparency(); return pv; } /* TODO if (tag.equals(ICalTags.due)) { pv.val = ev. return pv; } */ if (tag.equals(ICalTags.status)) { pv.val = ev.getStatus(); return pv; } if (tag.equals(ICalTags.uid)) { pv.val = ev.getGuid(); return pv; } if (tag.equals(ICalTags.sequence)) { pv.val = String.valueOf(ev.getSequence()); return pv; } /* if (tag.equals(ICalTags.hasRecurrence)) { pv.val = ev return pv; } if (tag.equals(ICalTags.hasAlarm)) { pv.val = ev return pv; } if (tag.equals(ICalTags.hasAttachment)) { pv.val = ev return pv; }*/ pv.notFound = true; return pv; }
public PropVal generatePropertyValue(WebdavProperty pr) throws WebdavIntfException { PropVal pv = new PropVal(); QName tag = pr.getTag(); String ns = tag.getNamespaceURI(); BwCalendar cal = getCDURI().getCal(); /* Deal with webdav properties */ if ((!ns.equals(CaldavDefs.caldavNamespace) && !ns.equals(CaldavDefs.icalNamespace))) { // Not ours return super.generatePropertyValue(pr); } BwEvent ev = checkEv(pv); if (ev == null) { return pv; } if (tag.equals(ICalTags.summary)) { pv.val = ev.getSummary(); return pv; } if (tag.equals(ICalTags.dtstart)) { pv.val = ev.getDtstart().getDate(); return pv; } if (tag.equals(ICalTags.dtend)) { pv.val = ev.getDtend().getDate(); return pv; } if (tag.equals(ICalTags.duration)) { pv.val = ev.getDuration(); return pv; } if (tag.equals(ICalTags.transp)) { pv.val = ev.getTransparency(); return pv; } /* TODO if (tag.equals(ICalTags.due)) { pv.val = ev. return pv; } */ if (tag.equals(ICalTags.status)) { pv.val = ev.getStatus(); return pv; } if (tag.equals(ICalTags.uid)) { pv.val = ev.getGuid(); return pv; } if (tag.equals(ICalTags.sequence)) { pv.val = String.valueOf(ev.getSequence()); return pv; } /* if (tag.equals(ICalTags.hasRecurrence)) { pv.val = ev return pv; } if (tag.equals(ICalTags.hasAlarm)) { pv.val = ev return pv; } if (tag.equals(ICalTags.hasAttachment)) { pv.val = ev return pv; }*/ pv.notFound = true; return pv; }
diff --git a/integration/src/main/java/org/obiba/magma/integration/IntegrationApp.java b/integration/src/main/java/org/obiba/magma/integration/IntegrationApp.java index a374630f..4a794a3b 100644 --- a/integration/src/main/java/org/obiba/magma/integration/IntegrationApp.java +++ b/integration/src/main/java/org/obiba/magma/integration/IntegrationApp.java @@ -1,199 +1,199 @@ package org.obiba.magma.integration; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.Properties; import org.obiba.magma.Datasource; import org.obiba.magma.MagmaEngine; import org.obiba.magma.Value; import org.obiba.magma.ValueSequence; import org.obiba.magma.ValueSet; import org.obiba.magma.ValueTable; import org.obiba.magma.Variable; import org.obiba.magma.crypt.support.GeneratedKeyPairProvider; import org.obiba.magma.datasource.crypt.EncryptedSecretKeyDatasourceEncryptionStrategy; import org.obiba.magma.datasource.crypt.GeneratedSecretKeyDatasourceEncryptionStrategy; import org.obiba.magma.datasource.csv.CsvDatasource; import org.obiba.magma.datasource.excel.ExcelDatasource; import org.obiba.magma.datasource.fs.FsDatasource; import org.obiba.magma.datasource.hibernate.SessionFactoryProvider; import org.obiba.magma.datasource.hibernate.support.HibernateDatasourceFactory; import org.obiba.magma.datasource.hibernate.support.LocalSessionFactoryProvider; import org.obiba.magma.datasource.jdbc.JdbcDatasourceFactory; import org.obiba.magma.datasource.jdbc.JdbcDatasourceSettings; import org.obiba.magma.integration.service.XStreamIntegrationServiceFactory; import org.obiba.magma.js.MagmaJsExtension; import org.obiba.magma.support.DatasourceCopier; import org.obiba.magma.type.DateTimeType; import org.obiba.magma.type.TextType; import org.obiba.magma.xstream.MagmaXStreamExtension; /** */ public class IntegrationApp { public static void main(String[] args) throws IOException, NoSuchAlgorithmException { new MagmaEngine().extend(new MagmaJsExtension()).extend(new MagmaXStreamExtension()); XStreamIntegrationServiceFactory factory = new XStreamIntegrationServiceFactory(); IntegrationDatasource integrationDatasource = new IntegrationDatasource(factory.buildService(new InputStreamReader(IntegrationApp.class.getResourceAsStream("participants.xml"), "UTF-8"))); MagmaEngine.get().addDatasource(integrationDatasource); File encrypted = new File("target", "output-encrypted.zip"); deleteFile(encrypted); // Generate a new KeyPair. GeneratedKeyPairProvider keyPairProvider = new GeneratedKeyPairProvider(); GeneratedSecretKeyDatasourceEncryptionStrategy generatedEncryptionStrategy = new GeneratedSecretKeyDatasourceEncryptionStrategy(); generatedEncryptionStrategy.setKeyProvider(keyPairProvider); FsDatasource fs = new FsDatasource("export", encrypted, generatedEncryptionStrategy); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource DatasourceCopier copier = DatasourceCopier.Builder.newCopier().build(); copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); // Read it back EncryptedSecretKeyDatasourceEncryptionStrategy encryptedEncryptionStrategy = new EncryptedSecretKeyDatasourceEncryptionStrategy(); encryptedEncryptionStrategy.setKeyProvider(keyPairProvider); MagmaEngine.get().addDatasource(new FsDatasource("imported", encrypted, encryptedEncryptionStrategy)); // Dump its values for(ValueTable table : MagmaEngine.get().getDatasource("imported").getValueTables()) { for(ValueSet valueSet : table.getValueSets()) { for(Variable variable : table.getVariables()) { Value value = table.getValue(variable, valueSet); if(value.isSequence() && value.isNull() == false) { ValueSequence seq = value.asSequence(); int order = 0; for(Value item : seq.getValues()) { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]@" + (order++) + ": " + item); } } else { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]: " + value); } } } } File decrypted = new File("target", "output-decrypted.zip"); deleteFile(decrypted); fs = new FsDatasource("export", decrypted); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); SessionFactoryProvider provider = new LocalSessionFactoryProvider("org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:target/integration-hibernate.db;shutdown=true", "sa", "", "org.hibernate.dialect.HSQLDialect"); HibernateDatasourceFactory hdsFactory = new HibernateDatasourceFactory("integration-hibernate", provider); try { // This is uncool. We have to initialise the DatasourceFactory before passing it to Magma, because we need to // start a transaction before the datasource initialises itself. Starting the transaction requires the // SessionFactory which is created by the DatasourceFactory. Ideally, we would have passed the factory to Magma // directly. hdsFactory.initialise(); // Start a transaction before passing the Datasource to Magma. A tx is required for the Datasource to initialise // correctly. provider.getSessionFactory().getCurrentSession().beginTransaction(); Datasource ds = MagmaEngine.get().addDatasource(hdsFactory.create()); // Add some attributes to the HibernateDatasource. if(!ds.hasAttribute("Created by")) { ds.setAttributeValue("Created by", TextType.get().valueOf("Magma Integration App")); } if(!ds.hasAttribute("Created on")) { ds.setAttributeValue("Created on", DateTimeType.get().valueOf(new Date())); } ds.setAttributeValue("Last connected", DateTimeType.get().valueOf(new Date())); // Copy the data from the IntegrationDatasource to the HibernateDatasource. copier.copy(integrationDatasource, ds); MagmaEngine.get().removeDatasource(ds); provider.getSessionFactory().getCurrentSession().getTransaction().commit(); } catch(RuntimeException e) { try { provider.getSessionFactory().getCurrentSession().getTransaction().rollback(); } catch(Exception ignore) { } e.printStackTrace(); throw e; } // CSV Datasource File csvDataFile = new File("target", "data.csv"); deleteFile(csvDataFile); createFile(csvDataFile); File csvVariablesFile = new File("target", "variables.csv"); deleteFile(csvVariablesFile); - csvVariablesFile.createNewFile(); + createFile(csvVariablesFile); CsvDatasource csvDatasource = new CsvDatasource("csv"); csvDatasource.addValueTable("integration-app", csvVariablesFile, csvDataFile); csvDatasource.setVariablesHeader("integration-app", "name#valueType#entityType#mimeType#unit#occurrenceGroup#repeatable#script".split("#")); MagmaEngine.get().addDatasource(csvDatasource); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, csvDatasource); // Excel Datasource File excelFile = new File("target", "excel-datasource.xls"); deleteFile(excelFile); ExcelDatasource ed = new ExcelDatasource("excel", excelFile); MagmaEngine.get().addDatasource(ed); DatasourceCopier.Builder.newCopier().dontCopyValues().build().copy(integrationDatasource, ed); JdbcDatasourceFactory jdbcDatasourceFactory = new JdbcDatasourceFactory(); jdbcDatasourceFactory.setName("jdbc"); jdbcDatasourceFactory.setJdbcProperties(getJdbcProperties()); jdbcDatasourceFactory.setDatasourceSettings(new JdbcDatasourceSettings("Participant", null, null, true)); Datasource jd = jdbcDatasourceFactory.create(); MagmaEngine.get().addDatasource(jd); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, jd); MagmaEngine.get().shutdown(); } private static Properties getJdbcProperties() { Properties jdbcProperties = new Properties(); jdbcProperties.setProperty(JdbcDatasourceFactory.DRIVER_CLASS_NAME, "org.hsqldb.jdbcDriver"); jdbcProperties.setProperty(JdbcDatasourceFactory.URL, "jdbc:hsqldb:file:target/datasource_jdbc.db;shutdown=true"); jdbcProperties.setProperty(JdbcDatasourceFactory.USERNAME, "sa"); jdbcProperties.setProperty(JdbcDatasourceFactory.PASSWORD, ""); return jdbcProperties; } private static void deleteFile(File file) { if(file.exists()) { if(!file.delete()) { System.err.println("Failed to delete file: " + file.getPath()); } } } private static void createFile(File file) throws IOException { boolean fileDidNotExist = file.createNewFile(); if(fileDidNotExist) { System.out.println("Created file: " + file.getPath()); } else { System.out.println("File already exists: " + file.getPath()); } } }
true
true
public static void main(String[] args) throws IOException, NoSuchAlgorithmException { new MagmaEngine().extend(new MagmaJsExtension()).extend(new MagmaXStreamExtension()); XStreamIntegrationServiceFactory factory = new XStreamIntegrationServiceFactory(); IntegrationDatasource integrationDatasource = new IntegrationDatasource(factory.buildService(new InputStreamReader(IntegrationApp.class.getResourceAsStream("participants.xml"), "UTF-8"))); MagmaEngine.get().addDatasource(integrationDatasource); File encrypted = new File("target", "output-encrypted.zip"); deleteFile(encrypted); // Generate a new KeyPair. GeneratedKeyPairProvider keyPairProvider = new GeneratedKeyPairProvider(); GeneratedSecretKeyDatasourceEncryptionStrategy generatedEncryptionStrategy = new GeneratedSecretKeyDatasourceEncryptionStrategy(); generatedEncryptionStrategy.setKeyProvider(keyPairProvider); FsDatasource fs = new FsDatasource("export", encrypted, generatedEncryptionStrategy); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource DatasourceCopier copier = DatasourceCopier.Builder.newCopier().build(); copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); // Read it back EncryptedSecretKeyDatasourceEncryptionStrategy encryptedEncryptionStrategy = new EncryptedSecretKeyDatasourceEncryptionStrategy(); encryptedEncryptionStrategy.setKeyProvider(keyPairProvider); MagmaEngine.get().addDatasource(new FsDatasource("imported", encrypted, encryptedEncryptionStrategy)); // Dump its values for(ValueTable table : MagmaEngine.get().getDatasource("imported").getValueTables()) { for(ValueSet valueSet : table.getValueSets()) { for(Variable variable : table.getVariables()) { Value value = table.getValue(variable, valueSet); if(value.isSequence() && value.isNull() == false) { ValueSequence seq = value.asSequence(); int order = 0; for(Value item : seq.getValues()) { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]@" + (order++) + ": " + item); } } else { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]: " + value); } } } } File decrypted = new File("target", "output-decrypted.zip"); deleteFile(decrypted); fs = new FsDatasource("export", decrypted); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); SessionFactoryProvider provider = new LocalSessionFactoryProvider("org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:target/integration-hibernate.db;shutdown=true", "sa", "", "org.hibernate.dialect.HSQLDialect"); HibernateDatasourceFactory hdsFactory = new HibernateDatasourceFactory("integration-hibernate", provider); try { // This is uncool. We have to initialise the DatasourceFactory before passing it to Magma, because we need to // start a transaction before the datasource initialises itself. Starting the transaction requires the // SessionFactory which is created by the DatasourceFactory. Ideally, we would have passed the factory to Magma // directly. hdsFactory.initialise(); // Start a transaction before passing the Datasource to Magma. A tx is required for the Datasource to initialise // correctly. provider.getSessionFactory().getCurrentSession().beginTransaction(); Datasource ds = MagmaEngine.get().addDatasource(hdsFactory.create()); // Add some attributes to the HibernateDatasource. if(!ds.hasAttribute("Created by")) { ds.setAttributeValue("Created by", TextType.get().valueOf("Magma Integration App")); } if(!ds.hasAttribute("Created on")) { ds.setAttributeValue("Created on", DateTimeType.get().valueOf(new Date())); } ds.setAttributeValue("Last connected", DateTimeType.get().valueOf(new Date())); // Copy the data from the IntegrationDatasource to the HibernateDatasource. copier.copy(integrationDatasource, ds); MagmaEngine.get().removeDatasource(ds); provider.getSessionFactory().getCurrentSession().getTransaction().commit(); } catch(RuntimeException e) { try { provider.getSessionFactory().getCurrentSession().getTransaction().rollback(); } catch(Exception ignore) { } e.printStackTrace(); throw e; } // CSV Datasource File csvDataFile = new File("target", "data.csv"); deleteFile(csvDataFile); createFile(csvDataFile); File csvVariablesFile = new File("target", "variables.csv"); deleteFile(csvVariablesFile); csvVariablesFile.createNewFile(); CsvDatasource csvDatasource = new CsvDatasource("csv"); csvDatasource.addValueTable("integration-app", csvVariablesFile, csvDataFile); csvDatasource.setVariablesHeader("integration-app", "name#valueType#entityType#mimeType#unit#occurrenceGroup#repeatable#script".split("#")); MagmaEngine.get().addDatasource(csvDatasource); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, csvDatasource); // Excel Datasource File excelFile = new File("target", "excel-datasource.xls"); deleteFile(excelFile); ExcelDatasource ed = new ExcelDatasource("excel", excelFile); MagmaEngine.get().addDatasource(ed); DatasourceCopier.Builder.newCopier().dontCopyValues().build().copy(integrationDatasource, ed); JdbcDatasourceFactory jdbcDatasourceFactory = new JdbcDatasourceFactory(); jdbcDatasourceFactory.setName("jdbc"); jdbcDatasourceFactory.setJdbcProperties(getJdbcProperties()); jdbcDatasourceFactory.setDatasourceSettings(new JdbcDatasourceSettings("Participant", null, null, true)); Datasource jd = jdbcDatasourceFactory.create(); MagmaEngine.get().addDatasource(jd); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, jd); MagmaEngine.get().shutdown(); }
public static void main(String[] args) throws IOException, NoSuchAlgorithmException { new MagmaEngine().extend(new MagmaJsExtension()).extend(new MagmaXStreamExtension()); XStreamIntegrationServiceFactory factory = new XStreamIntegrationServiceFactory(); IntegrationDatasource integrationDatasource = new IntegrationDatasource(factory.buildService(new InputStreamReader(IntegrationApp.class.getResourceAsStream("participants.xml"), "UTF-8"))); MagmaEngine.get().addDatasource(integrationDatasource); File encrypted = new File("target", "output-encrypted.zip"); deleteFile(encrypted); // Generate a new KeyPair. GeneratedKeyPairProvider keyPairProvider = new GeneratedKeyPairProvider(); GeneratedSecretKeyDatasourceEncryptionStrategy generatedEncryptionStrategy = new GeneratedSecretKeyDatasourceEncryptionStrategy(); generatedEncryptionStrategy.setKeyProvider(keyPairProvider); FsDatasource fs = new FsDatasource("export", encrypted, generatedEncryptionStrategy); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource DatasourceCopier copier = DatasourceCopier.Builder.newCopier().build(); copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); // Read it back EncryptedSecretKeyDatasourceEncryptionStrategy encryptedEncryptionStrategy = new EncryptedSecretKeyDatasourceEncryptionStrategy(); encryptedEncryptionStrategy.setKeyProvider(keyPairProvider); MagmaEngine.get().addDatasource(new FsDatasource("imported", encrypted, encryptedEncryptionStrategy)); // Dump its values for(ValueTable table : MagmaEngine.get().getDatasource("imported").getValueTables()) { for(ValueSet valueSet : table.getValueSets()) { for(Variable variable : table.getVariables()) { Value value = table.getValue(variable, valueSet); if(value.isSequence() && value.isNull() == false) { ValueSequence seq = value.asSequence(); int order = 0; for(Value item : seq.getValues()) { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]@" + (order++) + ": " + item); } } else { System.out.println(variable.getName() + "[" + value.getValueType().getName() + "]: " + value); } } } } File decrypted = new File("target", "output-decrypted.zip"); deleteFile(decrypted); fs = new FsDatasource("export", decrypted); MagmaEngine.get().addDatasource(fs); // Export the IntegrationDatasource to the FsDatasource copier.copy(integrationDatasource.getName(), fs.getName()); // Disconnect it from Magma MagmaEngine.get().removeDatasource(fs); SessionFactoryProvider provider = new LocalSessionFactoryProvider("org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:target/integration-hibernate.db;shutdown=true", "sa", "", "org.hibernate.dialect.HSQLDialect"); HibernateDatasourceFactory hdsFactory = new HibernateDatasourceFactory("integration-hibernate", provider); try { // This is uncool. We have to initialise the DatasourceFactory before passing it to Magma, because we need to // start a transaction before the datasource initialises itself. Starting the transaction requires the // SessionFactory which is created by the DatasourceFactory. Ideally, we would have passed the factory to Magma // directly. hdsFactory.initialise(); // Start a transaction before passing the Datasource to Magma. A tx is required for the Datasource to initialise // correctly. provider.getSessionFactory().getCurrentSession().beginTransaction(); Datasource ds = MagmaEngine.get().addDatasource(hdsFactory.create()); // Add some attributes to the HibernateDatasource. if(!ds.hasAttribute("Created by")) { ds.setAttributeValue("Created by", TextType.get().valueOf("Magma Integration App")); } if(!ds.hasAttribute("Created on")) { ds.setAttributeValue("Created on", DateTimeType.get().valueOf(new Date())); } ds.setAttributeValue("Last connected", DateTimeType.get().valueOf(new Date())); // Copy the data from the IntegrationDatasource to the HibernateDatasource. copier.copy(integrationDatasource, ds); MagmaEngine.get().removeDatasource(ds); provider.getSessionFactory().getCurrentSession().getTransaction().commit(); } catch(RuntimeException e) { try { provider.getSessionFactory().getCurrentSession().getTransaction().rollback(); } catch(Exception ignore) { } e.printStackTrace(); throw e; } // CSV Datasource File csvDataFile = new File("target", "data.csv"); deleteFile(csvDataFile); createFile(csvDataFile); File csvVariablesFile = new File("target", "variables.csv"); deleteFile(csvVariablesFile); createFile(csvVariablesFile); CsvDatasource csvDatasource = new CsvDatasource("csv"); csvDatasource.addValueTable("integration-app", csvVariablesFile, csvDataFile); csvDatasource.setVariablesHeader("integration-app", "name#valueType#entityType#mimeType#unit#occurrenceGroup#repeatable#script".split("#")); MagmaEngine.get().addDatasource(csvDatasource); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, csvDatasource); // Excel Datasource File excelFile = new File("target", "excel-datasource.xls"); deleteFile(excelFile); ExcelDatasource ed = new ExcelDatasource("excel", excelFile); MagmaEngine.get().addDatasource(ed); DatasourceCopier.Builder.newCopier().dontCopyValues().build().copy(integrationDatasource, ed); JdbcDatasourceFactory jdbcDatasourceFactory = new JdbcDatasourceFactory(); jdbcDatasourceFactory.setName("jdbc"); jdbcDatasourceFactory.setJdbcProperties(getJdbcProperties()); jdbcDatasourceFactory.setDatasourceSettings(new JdbcDatasourceSettings("Participant", null, null, true)); Datasource jd = jdbcDatasourceFactory.create(); MagmaEngine.get().addDatasource(jd); DatasourceCopier.Builder.newCopier().dontCopyNullValues().build().copy(integrationDatasource, jd); MagmaEngine.get().shutdown(); }
diff --git a/src/com/google/caliper/Parameter.java b/src/com/google/caliper/Parameter.java index 72ff080..7258955 100644 --- a/src/com/google/caliper/Parameter.java +++ b/src/com/google/caliper/Parameter.java @@ -1,171 +1,171 @@ /* * Copyright (C) 2009 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.caliper; import java.lang.reflect.Field; import java.lang.reflect.Member; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.Collection; import java.util.EnumSet; import java.util.Map; import java.util.TreeMap; /** * A parameter in a {@link SimpleBenchmark}. */ abstract class Parameter<T> { private final Field field; private Parameter(Field field) { this.field = field; } /** * Returns all properties for the given class. */ public static Map<String, Parameter<?>> forClass(Class<? extends Benchmark> suiteClass) { Map<String, Parameter<?>> parameters = new TreeMap<String, Parameter<?>>(); for (final Field field : suiteClass.getDeclaredFields()) { if (field.isAnnotationPresent(Param.class)) { field.setAccessible(true); Parameter parameter = Parameter.forField(suiteClass, field); parameters.put(parameter.getName(), parameter); } } return parameters; } public static Parameter forField( Class<? extends Benchmark> suiteClass, final Field field) { // First check for String values on the annotation itself - final String[] defaults = field.getAnnotation(Param.class).value(); + final Object[] defaults = field.getAnnotation(Param.class).value(); if (defaults.length > 0) { return new Parameter<Object>(field) { public Collection<Object> values() throws Exception { return Arrays.<Object>asList(defaults); } }; } Parameter result = null; Type returnType = null; Member member = null; // Now check for a fooValues() method try { final Method valuesMethod = suiteClass.getDeclaredMethod(field.getName() + "Values"); valuesMethod.setAccessible(true); returnType = field.getGenericType(); result = new Parameter<Object>(field) { @SuppressWarnings("unchecked") // guarded below public Collection<Object> values() throws Exception { return (Collection<Object>) valuesMethod.invoke(null); } }; } catch (NoSuchMethodException ignored) { } // Now check for a fooValues field try { final Field valuesField = suiteClass.getDeclaredField(field.getName() + "Values"); valuesField.setAccessible(true); member = valuesField; if (result != null) { throw new ConfigurationException("Two values members defined for " + field); } returnType = valuesField.getGenericType(); result = new Parameter<Object>(field) { @SuppressWarnings("unchecked") // guarded below public Collection<Object> values() throws Exception { return (Collection<Object>) valuesField.get(null); } }; } catch (NoSuchFieldException ignored) { } if (member != null && !Modifier.isStatic(member.getModifiers())) { throw new ConfigurationException("Values member must be static " + member); } // If there isn't a values member but the parameter is an enum, we default // to EnumSet.allOf. if (member == null && field.getType().isEnum()) { returnType = Collection.class; result = new Parameter<Object>(field) { @SuppressWarnings("unchecked") // guarded above public Collection<Object> values() throws Exception { return EnumSet.allOf((Class<Enum>) field.getType()); } }; } if (result == null) { throw new ConfigurationException("No values member defined for " + field); } if (!isValidReturnType(returnType)) { throw new ConfigurationException("Invalid return type " + returnType + " for values member " + member + "; must be Collection"); } return result; } private static boolean isValidReturnType(Type returnType) { if (returnType == Collection.class) { return true; } if (returnType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) returnType; if (type.getRawType() == Collection.class) { return true; } } return false; } /** * Sets the value of this property to the specified value for the given suite. */ public void set(Benchmark suite, Object value) throws Exception { field.set(suite, value); } /** * Returns the available values of the property as specified by the suite. */ public abstract Collection<T> values() throws Exception; /** * Returns the parameter's type, such as double.class. */ public Type getType() { return field.getGenericType(); } /** * Returns the field's name. */ public String getName() { return field.getName(); } }
true
true
public static Parameter forField( Class<? extends Benchmark> suiteClass, final Field field) { // First check for String values on the annotation itself final String[] defaults = field.getAnnotation(Param.class).value(); if (defaults.length > 0) { return new Parameter<Object>(field) { public Collection<Object> values() throws Exception { return Arrays.<Object>asList(defaults); } }; } Parameter result = null; Type returnType = null; Member member = null; // Now check for a fooValues() method try { final Method valuesMethod = suiteClass.getDeclaredMethod(field.getName() + "Values"); valuesMethod.setAccessible(true); returnType = field.getGenericType(); result = new Parameter<Object>(field) { @SuppressWarnings("unchecked") // guarded below public Collection<Object> values() throws Exception { return (Collection<Object>) valuesMethod.invoke(null); } }; } catch (NoSuchMethodException ignored) { } // Now check for a fooValues field try { final Field valuesField = suiteClass.getDeclaredField(field.getName() + "Values"); valuesField.setAccessible(true); member = valuesField; if (result != null) { throw new ConfigurationException("Two values members defined for " + field); } returnType = valuesField.getGenericType(); result = new Parameter<Object>(field) { @SuppressWarnings("unchecked") // guarded below public Collection<Object> values() throws Exception { return (Collection<Object>) valuesField.get(null); } }; } catch (NoSuchFieldException ignored) { } if (member != null && !Modifier.isStatic(member.getModifiers())) { throw new ConfigurationException("Values member must be static " + member); } // If there isn't a values member but the parameter is an enum, we default // to EnumSet.allOf. if (member == null && field.getType().isEnum()) { returnType = Collection.class; result = new Parameter<Object>(field) { @SuppressWarnings("unchecked") // guarded above public Collection<Object> values() throws Exception { return EnumSet.allOf((Class<Enum>) field.getType()); } }; } if (result == null) { throw new ConfigurationException("No values member defined for " + field); } if (!isValidReturnType(returnType)) { throw new ConfigurationException("Invalid return type " + returnType + " for values member " + member + "; must be Collection"); } return result; }
public static Parameter forField( Class<? extends Benchmark> suiteClass, final Field field) { // First check for String values on the annotation itself final Object[] defaults = field.getAnnotation(Param.class).value(); if (defaults.length > 0) { return new Parameter<Object>(field) { public Collection<Object> values() throws Exception { return Arrays.<Object>asList(defaults); } }; } Parameter result = null; Type returnType = null; Member member = null; // Now check for a fooValues() method try { final Method valuesMethod = suiteClass.getDeclaredMethod(field.getName() + "Values"); valuesMethod.setAccessible(true); returnType = field.getGenericType(); result = new Parameter<Object>(field) { @SuppressWarnings("unchecked") // guarded below public Collection<Object> values() throws Exception { return (Collection<Object>) valuesMethod.invoke(null); } }; } catch (NoSuchMethodException ignored) { } // Now check for a fooValues field try { final Field valuesField = suiteClass.getDeclaredField(field.getName() + "Values"); valuesField.setAccessible(true); member = valuesField; if (result != null) { throw new ConfigurationException("Two values members defined for " + field); } returnType = valuesField.getGenericType(); result = new Parameter<Object>(field) { @SuppressWarnings("unchecked") // guarded below public Collection<Object> values() throws Exception { return (Collection<Object>) valuesField.get(null); } }; } catch (NoSuchFieldException ignored) { } if (member != null && !Modifier.isStatic(member.getModifiers())) { throw new ConfigurationException("Values member must be static " + member); } // If there isn't a values member but the parameter is an enum, we default // to EnumSet.allOf. if (member == null && field.getType().isEnum()) { returnType = Collection.class; result = new Parameter<Object>(field) { @SuppressWarnings("unchecked") // guarded above public Collection<Object> values() throws Exception { return EnumSet.allOf((Class<Enum>) field.getType()); } }; } if (result == null) { throw new ConfigurationException("No values member defined for " + field); } if (!isValidReturnType(returnType)) { throw new ConfigurationException("Invalid return type " + returnType + " for values member " + member + "; must be Collection"); } return result; }
diff --git a/shindig/src/main/java/org/jahia/services/shindig/JahiaOAuthDataStore.java b/shindig/src/main/java/org/jahia/services/shindig/JahiaOAuthDataStore.java index 75d01828..601a537b 100644 --- a/shindig/src/main/java/org/jahia/services/shindig/JahiaOAuthDataStore.java +++ b/shindig/src/main/java/org/jahia/services/shindig/JahiaOAuthDataStore.java @@ -1,201 +1,201 @@ /** * This file is part of Jahia: An integrated WCM, DMS and Portal Solution * Copyright (C) 2002-2010 Jahia Solutions Group SA. All rights reserved. * * 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 2 * 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * As a special exception to the terms and conditions of version 2.0 of * the GPL (or any later version), you may redistribute this Program in connection * with Free/Libre and Open Source Software ("FLOSS") applications as described * in Jahia's FLOSS exception. You should have received a copy of the text * describing the FLOSS exception, and it is also available here: * http://www.jahia.com/license * * Commercial and Supported Versions of the program * Alternatively, commercial and supported versions of the program may be used * in accordance with the terms contained in a separate written agreement * between you and Jahia Solutions Group SA. If you are unsure which license is appropriate * for your use, please contact the sales department at [email protected]. */ package org.jahia.services.shindig; import org.apache.shindig.social.opensocial.oauth.OAuthDataStore; import org.apache.shindig.social.opensocial.oauth.OAuthEntry; import org.apache.shindig.social.sample.spi.JsonDbOpensocialService; import org.apache.shindig.social.core.oauth.OAuthSecurityToken; import org.apache.shindig.auth.SecurityToken; import org.apache.shindig.auth.AuthenticationMode; import org.apache.shindig.common.crypto.Crypto; import org.json.JSONObject; import org.json.JSONException; import net.oauth.OAuthProblemException; import net.oauth.OAuthConsumer; import net.oauth.OAuthServiceProvider; import com.google.inject.Inject; import com.google.inject.name.Named; import com.google.common.collect.MapMaker; import com.google.common.collect.ImmutableList; import com.google.common.base.Preconditions; import java.util.concurrent.ConcurrentMap; import java.util.UUID; import java.util.Date; /** * TODO Comment me * * @author loom * Date: Aug 19, 2009 * Time: 2:48:41 PM */ public class JahiaOAuthDataStore implements OAuthDataStore { // This needs to be long enough that an attacker can't guess it. If the attacker can guess this // value before they exceed the maximum number of attempts, they can complete a session fixation // attack against a user. private final int CALLBACK_TOKEN_LENGTH = 6; // We limit the number of trials before disabling the request token. private final int CALLBACK_TOKEN_ATTEMPTS = 5; private final OAuthServiceProvider SERVICE_PROVIDER; @Inject public JahiaOAuthDataStore(@Named("shindig.oauth.base-url") String baseUrl) { this.SERVICE_PROVIDER = new OAuthServiceProvider(baseUrl + "requestToken", baseUrl + "authorize", baseUrl + "accessToken"); } // All valid OAuth tokens private static ConcurrentMap<String,OAuthEntry> oauthEntries = new MapMaker().makeMap(); // Get the OAuthEntry that corresponds to the oauthToken public OAuthEntry getEntry(String oauthToken) { Preconditions.checkNotNull(oauthToken); return oauthEntries.get(oauthToken); } public OAuthConsumer getConsumer(String consumerKey) { //try { - // TODO we should lookup deployed mashups here for consumerSecret info. + // TODO we should lookup deployed portlets here for consumerSecret info. /* JSONObject app = service.getDb().getJSONObject("apps").getJSONObject(Preconditions.checkNotNull(consumerKey)); String consumerSecret = app.getString("consumerSecret"); */ String consumerSecret = "secret"; if (consumerSecret == null) return null; // null below is for the callbackUrl, which we don't have in the db OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, SERVICE_PROVIDER); // Set some properties loosely based on the ModulePrefs of a gadget /* for (String key : ImmutableList.of("title", "summary", "description", "thumbnail", "icon")) { if (app.has(key)) consumer.setProperty(key, app.getString(key)); } */ return consumer; /* } catch (JSONException e) { return null; } */ } // Generate a valid requestToken for the given consumerKey public OAuthEntry generateRequestToken(String consumerKey, String oauthVersion, String signedCallbackUrl) { OAuthEntry entry = new OAuthEntry(); entry.appId = consumerKey; entry.consumerKey = consumerKey; entry.domain = "samplecontainer.com"; entry.container = "default"; entry.token = UUID.randomUUID().toString(); entry.tokenSecret = UUID.randomUUID().toString(); entry.type = OAuthEntry.Type.REQUEST; entry.issueTime = new Date(); entry.oauthVersion = oauthVersion; if (signedCallbackUrl != null) { entry.callbackUrlSigned = true; entry.callbackUrl = signedCallbackUrl; } oauthEntries.put(entry.token, entry); return entry; } // Turns the request token into an access token public OAuthEntry convertToAccessToken(OAuthEntry entry) { Preconditions.checkNotNull(entry); Preconditions.checkState(entry.type == OAuthEntry.Type.REQUEST, "Token must be a request token"); OAuthEntry accessEntry = new OAuthEntry(entry); accessEntry.token = UUID.randomUUID().toString(); accessEntry.tokenSecret = UUID.randomUUID().toString(); accessEntry.type = OAuthEntry.Type.ACCESS; accessEntry.issueTime = new Date(); oauthEntries.remove(entry.token); oauthEntries.put(accessEntry.token, accessEntry); return accessEntry; } // Authorize the request token for the given user id public void authorizeToken(OAuthEntry entry, String userId) { Preconditions.checkNotNull(entry); entry.authorized = true; entry.userId = Preconditions.checkNotNull(userId); if (entry.callbackUrlSigned) { entry.callbackToken = Crypto.getRandomDigits(CALLBACK_TOKEN_LENGTH); } } public void disableToken(OAuthEntry entry) { Preconditions.checkNotNull(entry); ++entry.callbackTokenAttempts; if (!entry.callbackUrlSigned || entry.callbackTokenAttempts >= CALLBACK_TOKEN_ATTEMPTS) { entry.type = OAuthEntry.Type.DISABLED; } oauthEntries.put(entry.token, entry); } public void removeToken(OAuthEntry entry) { Preconditions.checkNotNull(entry); oauthEntries.remove(entry.token); } // Return the proper security token for a 2 legged oauth request that has been validated // for the given consumerKey. App specific checks like making sure the requested user has the // app installed should take place in this method public SecurityToken getSecurityTokenForConsumerRequest(String consumerKey, String userId) { String domain = "samplecontainer.com"; String container = "default"; return new OAuthSecurityToken(userId, null, consumerKey, domain, container, AuthenticationMode.OAUTH_CONSUMER_REQUEST.name()); } }
true
true
public OAuthConsumer getConsumer(String consumerKey) { //try { // TODO we should lookup deployed mashups here for consumerSecret info. /* JSONObject app = service.getDb().getJSONObject("apps").getJSONObject(Preconditions.checkNotNull(consumerKey)); String consumerSecret = app.getString("consumerSecret"); */ String consumerSecret = "secret"; if (consumerSecret == null) return null; // null below is for the callbackUrl, which we don't have in the db OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, SERVICE_PROVIDER); // Set some properties loosely based on the ModulePrefs of a gadget /* for (String key : ImmutableList.of("title", "summary", "description", "thumbnail", "icon")) { if (app.has(key)) consumer.setProperty(key, app.getString(key)); } */ return consumer; /* } catch (JSONException e) {
public OAuthConsumer getConsumer(String consumerKey) { //try { // TODO we should lookup deployed portlets here for consumerSecret info. /* JSONObject app = service.getDb().getJSONObject("apps").getJSONObject(Preconditions.checkNotNull(consumerKey)); String consumerSecret = app.getString("consumerSecret"); */ String consumerSecret = "secret"; if (consumerSecret == null) return null; // null below is for the callbackUrl, which we don't have in the db OAuthConsumer consumer = new OAuthConsumer(null, consumerKey, consumerSecret, SERVICE_PROVIDER); // Set some properties loosely based on the ModulePrefs of a gadget /* for (String key : ImmutableList.of("title", "summary", "description", "thumbnail", "icon")) { if (app.has(key)) consumer.setProperty(key, app.getString(key)); } */ return consumer; /* } catch (JSONException e) {
diff --git a/platform/src/pl/net/bluesoft/rnd/processtool/editor/AperteWorkflowDefinitionGenerator.java b/platform/src/pl/net/bluesoft/rnd/processtool/editor/AperteWorkflowDefinitionGenerator.java index 7a831c6..a9e175b 100644 --- a/platform/src/pl/net/bluesoft/rnd/processtool/editor/AperteWorkflowDefinitionGenerator.java +++ b/platform/src/pl/net/bluesoft/rnd/processtool/editor/AperteWorkflowDefinitionGenerator.java @@ -1,544 +1,545 @@ package pl.net.bluesoft.rnd.processtool.editor; import com.signavio.platform.core.Platform; import com.signavio.platform.core.PlatformProperties; import com.signavio.platform.exceptions.RequestException; import de.hpi.bpmn2_0.exceptions.BpmnConverterException; import de.hpi.bpmn2_0.factory.AbstractBpmnFactory; import de.hpi.bpmn2_0.model.Definitions; import de.hpi.bpmn2_0.transformation.Bpmn2XmlConverter; import de.hpi.bpmn2_0.transformation.Diagram2BpmnConverter; import de.hpi.bpmn2_0.transformation.Diagram2XmlConverter; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.aperteworkflow.editor.domain.Permission; import org.aperteworkflow.editor.domain.ProcessConfig; import org.aperteworkflow.editor.domain.Queue; import org.aperteworkflow.editor.domain.QueueRolePermission; import org.aperteworkflow.editor.json.ProcessConfigJSONHandler; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.oryxeditor.server.diagram.basic.BasicDiagram; import org.oryxeditor.server.diagram.basic.BasicDiagramBuilder; import org.xml.sax.SAXException; import pl.net.bluesoft.rnd.processtool.editor.jpdl.exception.UnsupportedJPDLObjectException; import pl.net.bluesoft.rnd.processtool.editor.jpdl.object.*; import javax.xml.bind.JAXBException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.StringWriter; import java.net.URL; import java.net.URLConnection; import java.util.*; public class AperteWorkflowDefinitionGenerator { //key = resourceId private Map<String, JPDLComponent> componentMap = new HashMap<String, JPDLComponent>(); private Map<String, JPDLTransition> transitionMap = new HashMap<String, JPDLTransition>(); private String json; private ProcessConfig processConfig; private final Logger logger = Logger.getLogger(AperteWorkflowDefinitionGenerator.class); private String processName; private String processFileName; private String bundleDesc; private String bundleName; private String processToolDeployment; private int offsetY; private int offsetX; private String processDefinitionLanguage; public AperteWorkflowDefinitionGenerator(int offsetX, int offsetY) { this.offsetX = offsetX; this.offsetY = offsetY; } public void init(String json) { try { this.json = json; JSONObject jsonObj = enrichModelerDataForBpmn20(); // JSONObject jsonObj = new JSONObject(json); processName = jsonObj.getJSONObject("properties").getString("name"); processFileName = jsonObj.getJSONObject("properties").optString("aperte-process-filename"); bundleDesc = jsonObj.getJSONObject("properties").optString("mf-bundle-description"); bundleName = jsonObj.getJSONObject("properties").optString("mf-bundle-name"); processToolDeployment = jsonObj.getJSONObject("properties").optString("mf-processtool-deployment"); PlatformProperties props = Platform.getInstance().getPlatformProperties(); String aperteData = getAperteData(props.getServerName() + props.getJbpmGuiUrl() + props.getAperteConfigurationUrl()); processDefinitionLanguage = new JSONObject(aperteData).optString("definitionLanguage"); //processDefinitionLanguage = jsonObj.getJSONObject("properties").optString("aperte-language"); if (processDefinitionLanguage == null || "".equals(processDefinitionLanguage)) { processDefinitionLanguage = "jpdl";//for old process definitions } if (StringUtils.isEmpty(processName)) { throw new RequestException("Process name is empty."); } if (StringUtils.isEmpty(processFileName)) { throw new RequestException("Aperte process filename is empty."); } if (StringUtils.isEmpty(bundleName)) { throw new RequestException("Manifest Bundle-Name is empty."); } if (StringUtils.isEmpty(bundleDesc)) { throw new RequestException("Manifest Bundle-Description is empty."); } if (StringUtils.isEmpty(processToolDeployment)) { throw new RequestException("Manifest: ProcessTool-Process-Deployment is empty."); } String processConfJson = jsonObj.getJSONObject("properties").optString("process-conf"); if (processConfJson != null && !processConfJson.trim().isEmpty()) { processConfig = ProcessConfigJSONHandler.getInstance().toObject(processConfJson); } JSONArray childShapes = jsonObj.getJSONArray("childShapes"); for (int i = 0; i < childShapes.length(); i++) { JSONObject obj = childShapes.getJSONObject(i); JPDLObject jpdlObject = JPDLObject.getJPDLObject(obj, this); jpdlObject.fillBasicProperties(obj); if (jpdlObject instanceof JPDLComponent) { - ((JPDLComponent) jpdlObject).applyOffset(offsetX, offsetY); + //not needed anymore +// ((JPDLComponent) jpdlObject).applyOffset(offsetX, offsetY); componentMap.put(jpdlObject.getResourceId(), (JPDLComponent) jpdlObject); } else if (jpdlObject instanceof JPDLTransition) { transitionMap.put(jpdlObject.getResourceId(), (JPDLTransition) jpdlObject); } } } catch (JSONException e) { logger.error("Error while generating JPDL file.", e); throw new RequestException("Error while generating JPDL file.", e); } catch (UnsupportedJPDLObjectException e) { logger.error("Error while generating JPDL file.", e); throw new RequestException(e.getMessage()); } //second pass, complete the transition map for (String key : componentMap.keySet()) { JPDLComponent cmp = componentMap.get(key); for (String resourceId : cmp.getOutgoing().keySet()) { JPDLTransition transition = transitionMap.get(resourceId); transition.setTargetName(componentMap.get(transition.getTarget()).getName()); cmp.putTransition(resourceId, transition); } } } public String generateDefinition() { if ("jpdl".equals(processDefinitionLanguage)) { return generateJpdl(); } else { return generateBpmn20(); } } public String generateJpdl() { StringBuffer jpdl = new StringBuffer(); jpdl.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); jpdl.append(String.format("<process name=\"%s\" xmlns=\"http://jbpm.org/4.4/jpdl\">\n", processName)); Set<String> swimlanes = new HashSet<String>(); for (String key : componentMap.keySet()) { JPDLComponent comp = componentMap.get(key); if (comp instanceof JPDLUserTask) { JPDLUserTask userTask = (JPDLUserTask) comp; if (userTask.getSwimlane() != null && userTask.getSwimlane().trim().length() > 0) { swimlanes.add(userTask.getSwimlane()); } } } for (String sl : swimlanes) { jpdl.append(String.format("<swimlane candidate-groups=\"%s\" name=\"%s\"/>\n", sl, sl)); } for (String key : componentMap.keySet()) { jpdl.append(componentMap.get(key).toXML()); } jpdl.append("</process>"); return jpdl.toString(); } public String generateBpmn20() { try { JSONObject jsonObj = enrichModelerDataForBpmn20(); String jsonForBpmn20 = jsonObj.toString(); BasicDiagram diagram = BasicDiagramBuilder.parseJson(jsonForBpmn20); Diagram2BpmnConverter converter; converter = new Diagram2BpmnConverter(diagram, AbstractBpmnFactory.getFactoryClasses()); Definitions bpmnDefinitions = converter.getDefinitionsFromDiagram(); ((de.hpi.bpmn2_0.model.Process)bpmnDefinitions.getRootElement().get(0)).setExecutable(true); bpmnDefinitions.getRootElement().get(0).setId(processName); Bpmn2XmlConverter xmlConverter = new Bpmn2XmlConverter(bpmnDefinitions, Platform.getInstance().getFile("/WEB-INF/xsd/BPMN20.xsd").getAbsolutePath()); return xmlConverter.getXml().toString(); } catch (Exception e) { throw new RuntimeException(e); } } private JSONObject enrichModelerDataForBpmn20() throws JSONException { JSONObject jsonObj = new JSONObject(json); JSONArray childShapes = jsonObj.getJSONArray("childShapes"); Map<String,JSONObject> outgoingMap = new HashMap<String, JSONObject>(); Map<String,JSONObject> resourceIdMap = new HashMap<String, JSONObject>(); for (int i = 0; i < childShapes.length(); i++) { JSONObject obj = childShapes.getJSONObject(i); fixBounds(obj); fixDockers(obj); resourceIdMap.put(obj.getString("resourceId"), obj); if (obj.has("outgoing")) { JSONArray outgoing = obj.getJSONArray("outgoing"); for (int j=0; j < outgoing.length(); j++) { JSONObject outobj = outgoing.getJSONObject(j); outgoingMap.put(outobj.getString("resourceId"), obj); } } } //update user step with assignment data for (int i = 0; i < childShapes.length(); i++) { JSONObject obj = childShapes.getJSONObject(i); String stencilId = obj.getJSONObject("stencil").getString("id"); if ("Task".equals(stencilId)) { String taskType = obj.getJSONObject("properties").getString("tasktype"); if ("User".equals(taskType)) { enrichBpmn20AssignmentConfig(obj, resourceIdMap); } else { enrichBpmn20JavaTask(obj, resourceIdMap); } } else if ("SequenceFlow".equals(stencilId)) { enrichBpmn20SequenceFlow(obj, outgoingMap, resourceIdMap); } else if ("Exclusive_Databased_Gateway".equals(stencilId)) { } } return jsonObj; } private void fixDockers(JSONObject obj) throws JSONException { JSONArray dockers = obj.optJSONArray("dockers"); if (dockers == null) return; for (int i=0; i < dockers.length(); i++) { fixOffset(dockers.getJSONObject(i)); } } private void fixBounds(JSONObject obj) throws JSONException { JSONObject bounds = obj.optJSONObject("bounds"); if (bounds == null) return; JSONObject lowerRight = bounds.getJSONObject("lowerRight"); JSONObject upperLeft = bounds.getJSONObject("upperLeft"); fixOffset(lowerRight); fixOffset(upperLeft); } private void fixOffset(JSONObject point) throws JSONException { int x = point.getInt("x"); int y = point.getInt("y"); point.put("x", x + offsetX); point.put("y", y + offsetY); } private void enrichBpmn20SequenceFlow(JSONObject obj, Map<String,JSONObject> outgoingMap, Map<String,JSONObject> resourceIdMap) throws JSONException { // String targetId = obj.getJSONObject("target").getString("resourceId"); // JSONObject source = outgoingMap.get(obj.getString("resourceId")); // JSONArray incoming = obj.getJSONArray("incoming"); // JSONArray outgoing = obj.getJSONArray("outgoing"); // JSONObject incomingNode = incoming.getJSONObject(0); // JSONObject outgoingNode = outgoing.getJSONObject(0); } private void enrichBpmn20JavaTask(JSONObject obj, Map<String,JSONObject> resourceIdMap) throws JSONException { JSONObject propertiesObj = obj.getJSONObject("properties"); JSONObject aperteCfg = new JSONObject(propertiesObj.getString("aperte-conf")); String stepName = propertiesObj.getString("tasktype"); if ("bpmn20".equals(processDefinitionLanguage)) propertiesObj.put("tasktype", "Service"); propertiesObj.put("activiti_class", "org.aperteworkflow.ext.activiti.ActivitiStepAction"); JSONArray fields = new JSONArray(); JSONObject nameField = new JSONObject(); nameField.put("name", "stepName"); nameField.put("string_value", stepName); fields.put(nameField); JSONObject paramsField = new JSONObject(); paramsField.put("name", "params"); StringBuilder sb = new StringBuilder(); sb.append("<map>\n"); Iterator iterator = aperteCfg.keys(); while (iterator.hasNext()) { String key = (String) iterator.next(); String value = aperteCfg.getString(key); if (value != null && !value.trim().isEmpty()) { try { byte[] bytes = Base64.decodeBase64(value.getBytes()); value = new String(bytes); } catch (Exception e) { //TODO nothing, as some properties are base64, and some are not } sb.append(String.format("<%s>%s</%s>", key, XmlUtil.encodeXmlEcscapeCharacters(value), //todo use XStream key)); } } sb.append("</map>\n"); paramsField.put("expression", sb.toString()); fields.put(paramsField); propertiesObj.put("activiti_fields", fields); processOutgoingConditions(obj, resourceIdMap, propertiesObj, "RESULT"); } private void processOutgoingConditions(JSONObject obj, Map<String, JSONObject> resourceIdMap, JSONObject propertiesObj, String varName) throws JSONException { //find outgoing transition to XOR gateway. There should be only one outgoing transition and without a condition // If it indeed is a XOR gateway and transition conditions are not specified - fill them with defaults JSONArray outgoing = obj.getJSONArray("outgoing"); if (outgoing.length() > 1) { throw new RuntimeException("Java task: " + propertiesObj.optString("name") + " has more than one outgoing transition."); } for (int i=0; i < outgoing.length(); i++) { JSONObject transition = resourceIdMap.get(outgoing.getJSONObject(i).getString("resourceId")); JSONObject properties = transition.getJSONObject("properties"); if (properties.has("conditionexpression")) { properties.remove("conditionexpression"); } properties.put("conditiontype", "Default"); String targetId = transition.getJSONObject("target").getString("resourceId"); JSONObject nextNode = resourceIdMap.get(targetId); String stencilId = nextNode.getJSONObject("stencil").getString("id"); if ("Exclusive_Databased_Gateway".equals(stencilId)) { JSONArray xorOutgoing = nextNode.getJSONArray("outgoing"); for (int j=0; j < xorOutgoing.length(); j++) { JSONObject xorTransition = resourceIdMap.get(xorOutgoing.getJSONObject(j).getString("resourceId")); JSONObject subProperties = xorTransition.getJSONObject("properties"); if (xorOutgoing.length() == 1) { //only one outgoing, remove condition and set condition type to default if (subProperties.has("conditionexpression")) { subProperties.remove("conditionexpression"); } subProperties.put("conditiontype", "Default"); } else { String condition = subProperties.optString("conditionexpression"); String conditionType = subProperties.optString("conditiontype"); if (!"Default".equals(conditionType) && (condition == null || condition.trim().isEmpty())) { subProperties.put("conditionexpression", String.format("${%s=='%s'}", varName, subProperties.optString("name"))); subProperties.put("conditiontype", "Expression"); } } } } } } private void enrichBpmn20AssignmentConfig(JSONObject obj, Map<String,JSONObject> resourceIdMap) throws JSONException { JSONObject propertiesObj = obj.getJSONObject("properties"); JSONObject aperteCfg = new JSONObject(propertiesObj.getString("aperte-conf")); String assignee = aperteCfg.optString("assignee"); //It looks like swimlanes are unsupported in Activiti :( // String swimlane = obj.optString("swimlane"); String candidateGroups = aperteCfg.optString("candidate_groups"); //resources/items[0]/resource_type JSONObject resources = new JSONObject(); JSONArray items = new JSONArray(); if (assignee != null && !assignee.trim().isEmpty()) { JSONObject o = new JSONObject(); o.put("resource_type", "humanperformer"); o.put("resourceassignmentexpr", assignee); items.put(o); } if (candidateGroups != null && !candidateGroups.trim().isEmpty()) { JSONObject o = new JSONObject(); o.put("resource_type", "potentialowner"); o.put("resourceassignmentexpr", candidateGroups); items.put(o); } resources.put("items", items); resources.put("totalCount", items.length()); if (items.length() != 0) { if (propertiesObj.opt("resources") != null) propertiesObj.remove("resources"); propertiesObj.put("resources", resources);//overwrite } propertiesObj.put("implementation", "unspecified"); processOutgoingConditions(obj, resourceIdMap, propertiesObj, "ACTION"); } public String generateProcessToolConfig() { StringBuffer ptc = new StringBuffer(); ptc.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); ptc.append(String.format("<config.ProcessDefinitionConfig bpmDefinitionKey=\"%s\" description=\"%s\" processName=\"%s\">\n", processName, processName, processName)); if (processConfig != null) { if (processConfig.getComment() != null && !processConfig.getComment().isEmpty()) { ptc.append(String.format("<comment>%s</comment>", XmlUtil.wrapCDATA(processConfig.getComment()))); } if (processConfig.getProcessPermissions() != null && !processConfig.getProcessPermissions().isEmpty()) { ptc.append("<permissions>\n"); for (Permission permission : processConfig.getProcessPermissions()) { ptc.append(String.format("<config.ProcessDefinitionPermission privilegeName=\"%s\" roleName=\"%s\"/>", permission.getPrivilegeName(), permission.getRoleName())); } ptc.append("</permissions>\n"); } } ptc.append("<states>\n"); //processtool-config.xml generation for (String key : componentMap.keySet()) { JPDLComponent cmp = componentMap.get(key); if (cmp instanceof JPDLUserTask) { JPDLUserTask task = (JPDLUserTask) cmp; if (task.getWidget() != null) { ptc.append(task.generateWidgetXML()); } } } ptc.append("</states>\n"); ptc.append("</config.ProcessDefinitionConfig>\n"); return ptc.toString(); } public JPDLComponent findComponent(String key) { return componentMap.get(key); } public String generateQueuesConfig() { StringBuffer q = new StringBuffer(); q.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); q.append("<list>\n"); if (processConfig != null) { if (processConfig.getQueues() != null && !processConfig.getQueues().isEmpty()) { for (Queue queue : processConfig.getQueues()) { String description = queue.getDescription(); if (description == null) { description = queue.getName(); } q.append(String.format( "<config.ProcessQueueConfig name=\"%s\" description=\"%s\">\n", queue.getName(), description )); q.append("<rights>\n"); if (queue.getRolePermissions() != null && !queue.getRolePermissions().isEmpty()) { for (QueueRolePermission rolePermission : queue.getRolePermissions()) { q.append(String.format( "<config.ProcessQueueRight roleName=\"%s\" browseAllowed=\"%b\"/>\n", rolePermission.getRoleName(), rolePermission.isBrowsingAllowed() )); } } q.append("</rights>\n"); q.append("</config.ProcessQueueConfig>\n"); } } } q.append("</list>\n"); return q.toString(); } public String getProcessDefinitionLanguage() { return processDefinitionLanguage; } public String getProcessName() { return processName; } public String getProcessFileName() { return processFileName; } public String getBundleDesc() { return bundleDesc; } public String getBundleName() { return bundleName; } public String getProcessToolDeployment() { return processToolDeployment; } public Map<String, String> getMessages() { if (processConfig == null) { return null; } return processConfig.getMessages(); } public byte[] getProcessIcon() { if (processConfig == null) { return null; } return processConfig.getProcessIcon(); } private String getAperteData(String aperteUrl) { try { URL url = new URL(aperteUrl); URLConnection conn = url.openConnection(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = rd.readLine()) != null) { sb.append(line); } rd.close(); return sb.toString(); } catch (IOException e) { logger.error("Error reading data from " + aperteUrl, e); throw new RuntimeException(e); } } }
true
true
public void init(String json) { try { this.json = json; JSONObject jsonObj = enrichModelerDataForBpmn20(); // JSONObject jsonObj = new JSONObject(json); processName = jsonObj.getJSONObject("properties").getString("name"); processFileName = jsonObj.getJSONObject("properties").optString("aperte-process-filename"); bundleDesc = jsonObj.getJSONObject("properties").optString("mf-bundle-description"); bundleName = jsonObj.getJSONObject("properties").optString("mf-bundle-name"); processToolDeployment = jsonObj.getJSONObject("properties").optString("mf-processtool-deployment"); PlatformProperties props = Platform.getInstance().getPlatformProperties(); String aperteData = getAperteData(props.getServerName() + props.getJbpmGuiUrl() + props.getAperteConfigurationUrl()); processDefinitionLanguage = new JSONObject(aperteData).optString("definitionLanguage"); //processDefinitionLanguage = jsonObj.getJSONObject("properties").optString("aperte-language"); if (processDefinitionLanguage == null || "".equals(processDefinitionLanguage)) { processDefinitionLanguage = "jpdl";//for old process definitions } if (StringUtils.isEmpty(processName)) { throw new RequestException("Process name is empty."); } if (StringUtils.isEmpty(processFileName)) { throw new RequestException("Aperte process filename is empty."); } if (StringUtils.isEmpty(bundleName)) { throw new RequestException("Manifest Bundle-Name is empty."); } if (StringUtils.isEmpty(bundleDesc)) { throw new RequestException("Manifest Bundle-Description is empty."); } if (StringUtils.isEmpty(processToolDeployment)) { throw new RequestException("Manifest: ProcessTool-Process-Deployment is empty."); } String processConfJson = jsonObj.getJSONObject("properties").optString("process-conf"); if (processConfJson != null && !processConfJson.trim().isEmpty()) { processConfig = ProcessConfigJSONHandler.getInstance().toObject(processConfJson); } JSONArray childShapes = jsonObj.getJSONArray("childShapes"); for (int i = 0; i < childShapes.length(); i++) { JSONObject obj = childShapes.getJSONObject(i); JPDLObject jpdlObject = JPDLObject.getJPDLObject(obj, this); jpdlObject.fillBasicProperties(obj); if (jpdlObject instanceof JPDLComponent) { ((JPDLComponent) jpdlObject).applyOffset(offsetX, offsetY); componentMap.put(jpdlObject.getResourceId(), (JPDLComponent) jpdlObject); } else if (jpdlObject instanceof JPDLTransition) { transitionMap.put(jpdlObject.getResourceId(), (JPDLTransition) jpdlObject); } } } catch (JSONException e) { logger.error("Error while generating JPDL file.", e); throw new RequestException("Error while generating JPDL file.", e); } catch (UnsupportedJPDLObjectException e) { logger.error("Error while generating JPDL file.", e); throw new RequestException(e.getMessage()); } //second pass, complete the transition map for (String key : componentMap.keySet()) { JPDLComponent cmp = componentMap.get(key); for (String resourceId : cmp.getOutgoing().keySet()) { JPDLTransition transition = transitionMap.get(resourceId); transition.setTargetName(componentMap.get(transition.getTarget()).getName()); cmp.putTransition(resourceId, transition); } } }
public void init(String json) { try { this.json = json; JSONObject jsonObj = enrichModelerDataForBpmn20(); // JSONObject jsonObj = new JSONObject(json); processName = jsonObj.getJSONObject("properties").getString("name"); processFileName = jsonObj.getJSONObject("properties").optString("aperte-process-filename"); bundleDesc = jsonObj.getJSONObject("properties").optString("mf-bundle-description"); bundleName = jsonObj.getJSONObject("properties").optString("mf-bundle-name"); processToolDeployment = jsonObj.getJSONObject("properties").optString("mf-processtool-deployment"); PlatformProperties props = Platform.getInstance().getPlatformProperties(); String aperteData = getAperteData(props.getServerName() + props.getJbpmGuiUrl() + props.getAperteConfigurationUrl()); processDefinitionLanguage = new JSONObject(aperteData).optString("definitionLanguage"); //processDefinitionLanguage = jsonObj.getJSONObject("properties").optString("aperte-language"); if (processDefinitionLanguage == null || "".equals(processDefinitionLanguage)) { processDefinitionLanguage = "jpdl";//for old process definitions } if (StringUtils.isEmpty(processName)) { throw new RequestException("Process name is empty."); } if (StringUtils.isEmpty(processFileName)) { throw new RequestException("Aperte process filename is empty."); } if (StringUtils.isEmpty(bundleName)) { throw new RequestException("Manifest Bundle-Name is empty."); } if (StringUtils.isEmpty(bundleDesc)) { throw new RequestException("Manifest Bundle-Description is empty."); } if (StringUtils.isEmpty(processToolDeployment)) { throw new RequestException("Manifest: ProcessTool-Process-Deployment is empty."); } String processConfJson = jsonObj.getJSONObject("properties").optString("process-conf"); if (processConfJson != null && !processConfJson.trim().isEmpty()) { processConfig = ProcessConfigJSONHandler.getInstance().toObject(processConfJson); } JSONArray childShapes = jsonObj.getJSONArray("childShapes"); for (int i = 0; i < childShapes.length(); i++) { JSONObject obj = childShapes.getJSONObject(i); JPDLObject jpdlObject = JPDLObject.getJPDLObject(obj, this); jpdlObject.fillBasicProperties(obj); if (jpdlObject instanceof JPDLComponent) { //not needed anymore // ((JPDLComponent) jpdlObject).applyOffset(offsetX, offsetY); componentMap.put(jpdlObject.getResourceId(), (JPDLComponent) jpdlObject); } else if (jpdlObject instanceof JPDLTransition) { transitionMap.put(jpdlObject.getResourceId(), (JPDLTransition) jpdlObject); } } } catch (JSONException e) { logger.error("Error while generating JPDL file.", e); throw new RequestException("Error while generating JPDL file.", e); } catch (UnsupportedJPDLObjectException e) { logger.error("Error while generating JPDL file.", e); throw new RequestException(e.getMessage()); } //second pass, complete the transition map for (String key : componentMap.keySet()) { JPDLComponent cmp = componentMap.get(key); for (String resourceId : cmp.getOutgoing().keySet()) { JPDLTransition transition = transitionMap.get(resourceId); transition.setTargetName(componentMap.get(transition.getTarget()).getName()); cmp.putTransition(resourceId, transition); } } }
diff --git a/src/main/java/eionet/webq/dao/ProjectFileStorageImpl.java b/src/main/java/eionet/webq/dao/ProjectFileStorageImpl.java index 78e6ae6..8897762 100644 --- a/src/main/java/eionet/webq/dao/ProjectFileStorageImpl.java +++ b/src/main/java/eionet/webq/dao/ProjectFileStorageImpl.java @@ -1,149 +1,149 @@ /* * 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. * * The Original Code is Web Questionnaires 2 * * The Initial Owner of the Original Code is European Environment * Agency. Portions created by TripleDev are Copyright * (C) European Environment Agency. All Rights Reserved. * * Contributor(s): * Anton Dmitrijev */ package eionet.webq.dao; import eionet.webq.dao.orm.ProjectEntry; import eionet.webq.dao.orm.ProjectFile; import eionet.webq.dao.orm.ProjectFileType; import eionet.webq.dao.orm.util.WebQFileInfo; import eionet.webq.dto.WebFormType; import org.apache.commons.lang3.ArrayUtils; import org.hibernate.Session; import org.hibernate.criterion.Conjunction; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import java.sql.Timestamp; import java.util.Collection; import static org.hibernate.criterion.Restrictions.and; import static org.hibernate.criterion.Restrictions.eq; import static org.hibernate.criterion.Restrictions.in; import static org.hibernate.criterion.Restrictions.isNotNull; /** * ProjectFileStorage implementation. */ @Repository @Transactional public class ProjectFileStorageImpl extends AbstractDao<ProjectFile> implements WebFormStorage, ProjectFileStorage { @Override public int save(final ProjectFile projectFile, final ProjectEntry project) { projectFile.setProjectId(project.getId()); getCurrentSession().save(projectFile); return projectFile.getId(); } @Override public void update(final ProjectFile projectFile, ProjectEntry projectEntry) { if (projectFile.getProjectId() == projectEntry.getId()) { if (WebQFileInfo.fileIsEmpty(projectFile.getFile())) { updateWithoutChangingContent(projectFile); } else { fullUpdate(projectFile); } } } @SuppressWarnings("unchecked") @Override public Collection<ProjectFile> findAllFilesFor(ProjectEntry project) { return getCriteria().add(eq("projectId", project.getId())).addOrder(Order.asc("id")).list(); } @Override public void remove(final ProjectEntry projectEntry, final int... fileIds) { removeByCriterion(and(eq("projectId", projectEntry.getId()), in("id", ArrayUtils.toObject(fileIds)))); } @Override public ProjectFile findByNameAndProject(String name, ProjectEntry projectEntry) { return (ProjectFile) getCriteria() .add(Restrictions.and(eq("projectId", projectEntry.getId()), eq("file.name", name))).uniqueResult(); } @SuppressWarnings("unchecked") @Override public Collection<ProjectFile> getAllActiveWebForms(WebFormType type) { return getCriteria().add(activeWebFormCriterionForType(type)).list(); } @Override public ProjectFile getActiveWebFormById(WebFormType type, int id) { return (ProjectFile) getCriteria().add(and(activeWebFormCriterionForType(type), Restrictions.idEq(id))).uniqueResult(); } @SuppressWarnings("unchecked") @Override public Collection<ProjectFile> findWebFormsForSchemas(WebFormType type, Collection<String> xmlSchemas) { return getCriteria().add(and(activeWebFormCriterionForType(type), in("xmlSchema", xmlSchemas))).list(); } @Override Class<ProjectFile> getEntityClass() { return ProjectFile.class; } /** * Updates all fields. * * @param projectFile project file */ private void fullUpdate(ProjectFile projectFile) { Session currentSession = getCurrentSession(); projectFile.setUpdated(new Timestamp(System.currentTimeMillis())); currentSession.merge(projectFile); currentSession.flush(); } /** * Performs update without changing file content data. * * @param projectFile project file */ private void updateWithoutChangingContent(ProjectFile projectFile) { getCurrentSession().createQuery("UPDATE ProjectFile SET title=:title, xmlSchema=:xmlSchema, " + " description=:description, userName=:userName, " + " active=:active, localForm=:localForm, remoteFileUrl=:remoteFileUrl, " + " newXmlFileName=:newXmlFileName, emptyInstanceUrl=:emptyInstanceUrl, updated=CURRENT_TIMESTAMP() " + " WHERE id=:id").setProperties(projectFile).executeUpdate(); } /** * Criterion defining active web form. * * @param type web form type * @return criterion */ private Conjunction activeWebFormCriterionForType(WebFormType type) { - Conjunction criterion = Restrictions.and(eq("fileType", ProjectFileType.WEBFORM), eq("active", true), isNotNull("xmlSchema")); + Conjunction criterion = and(eq("fileType", ProjectFileType.WEBFORM), eq("active", true), isNotNull("xmlSchema")); if (type == WebFormType.LOCAL) { criterion.add(eq("localForm", true)); } if (type == WebFormType.REMOTE) { criterion.add(eq("remoteForm", true)); } return criterion; } }
true
true
private Conjunction activeWebFormCriterionForType(WebFormType type) { Conjunction criterion = Restrictions.and(eq("fileType", ProjectFileType.WEBFORM), eq("active", true), isNotNull("xmlSchema")); if (type == WebFormType.LOCAL) { criterion.add(eq("localForm", true)); } if (type == WebFormType.REMOTE) { criterion.add(eq("remoteForm", true)); } return criterion; }
private Conjunction activeWebFormCriterionForType(WebFormType type) { Conjunction criterion = and(eq("fileType", ProjectFileType.WEBFORM), eq("active", true), isNotNull("xmlSchema")); if (type == WebFormType.LOCAL) { criterion.add(eq("localForm", true)); } if (type == WebFormType.REMOTE) { criterion.add(eq("remoteForm", true)); } return criterion; }
diff --git a/cleia/cleia-rest/src/main/java/com/abada/cleia/rest/form/FormProcessController.java b/cleia/cleia-rest/src/main/java/com/abada/cleia/rest/form/FormProcessController.java index bbd246d..ab884a0 100644 --- a/cleia/cleia-rest/src/main/java/com/abada/cleia/rest/form/FormProcessController.java +++ b/cleia/cleia-rest/src/main/java/com/abada/cleia/rest/form/FormProcessController.java @@ -1,157 +1,157 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.abada.cleia.rest.form; import com.abada.bpm.console.server.plugin.FormAuthorityRef; import com.abada.cleia.dao.PatientDao; import com.abada.cleia.dao.ProcessInstanceDao; import com.abada.cleia.entity.user.Patient; import com.abada.springframework.web.servlet.view.InputStreamView; import com.abada.web.util.URL; import java.io.IOException; import java.util.Map; import javax.annotation.security.RolesAllowed; import javax.servlet.http.HttpServletRequest; import org.jboss.bpm.console.client.model.ProcessInstanceRef; import org.jboss.bpm.console.server.integration.ProcessManagement; import org.jboss.bpm.console.server.plugin.FormDispatcherPlugin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mobile.device.Device; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.View; /** * * @author katsu */ @Controller @RequestMapping("/rs/form/process") public class FormProcessController { @Autowired private FormDispatcherPlugin formDispatcherPlugin; @Autowired private ProcessManagement processManagement; @Autowired private PatientDao patientDao; @Autowired private ProcessInstanceDao pInstancePatientDao; /** * * Displays a form of a process and assign for a patient. Used to display an html form to start a process instance. * @param definitionid Process id. * @param patientId Patient id to assign the started process instance. * @param request Do nothing. * @return Return the html to show in a iframe in the client interface. * @throws IOException */ @RolesAllowed(value={"ROLE_ADMIN","ROLE_USER"}) @RequestMapping(value = {"/{definitionid}/patient/{patientId}/render"}, method = RequestMethod.GET) public View renderProcess(@PathVariable String definitionid, @PathVariable Long patientId, HttpServletRequest request,Device device) throws IOException { com.abada.springframework.web.servlet.menu.Device deviceAux; if (device.isMobile()) { deviceAux = com.abada.springframework.web.servlet.menu.Device.MOBILE; } else if (device.isNormal()) { deviceAux = com.abada.springframework.web.servlet.menu.Device.DESKTOP; } else { deviceAux = com.abada.springframework.web.servlet.menu.Device.TABLET; } return new InputStreamView(formDispatcherPlugin.provideForm(new FormAuthorityRef(definitionid,deviceAux.name(), FormAuthorityRef.Type.PROCESS)).getInputStream(), "text/html", null); } /** * Submit and start the process instance of the form showed in the renderProcess method. * @param definitionid Process id * @param patientId Patient id * @param request Do nothing. * @return Return success structure. */ @RolesAllowed(value={"ROLE_ADMIN","ROLE_USER"}) @RequestMapping(value = "/{definitionid}/patient/{patientId}/complete", method = RequestMethod.POST) public String completeProcess(@PathVariable String definitionid, @PathVariable Long patientId, HttpServletRequest request, Model model) { return completeProcessPriv(definitionid, patientId, request, model); } private String completeProcessPriv(String definitionid, Long patientId,HttpServletRequest request, Model model) { try { Map<String, Object> params = URL.parseRequest(request); Patient patient = this.patientDao.getPatientById(patientId); //params.put("patient_patientids", patient.getPatientidList()); params.put("patient_birthday", patient.getBirthDay()); params.put("patient_genre", patient.getGenre().toString()); params.put("patient_id", patient.getId()); - params.put("putoactor",patient.getUser().getUsername()); + params.put("patient_username",patient.getUser().getUsername()); ProcessInstanceRef pir = processManagement.newInstance(definitionid, params); if (pir != null) { this.pInstancePatientDao.addPInstancePatient(patientId, Long.parseLong(pir.getId())); model.addAttribute("error", pir.getId()); model.addAttribute("success", Boolean.TRUE.toString()); } else { model.addAttribute("success", Boolean.FALSE.toString()); model.addAttribute("error", "ProcessInstance null"); } } catch (Exception e) { model.addAttribute("success", Boolean.FALSE.toString()); model.addAttribute("error", e.getMessage()); } return "success"; } //<editor-fold defaultstate="collapsed" desc="GWT Console"> /** * * Displays a form of a process. Used to display an html form to start a process instance. * @param definitionid Process id. * @param request Do nothing. * @return Return the html to show in a iframe in the client interface. * @throws IOException */ @RolesAllowed(value={"ROLE_ADMIN","ROLE_USER"}) @RequestMapping(value = "/{definitionid}/render", method = RequestMethod.GET) public View renderProcess(@PathVariable String definitionid, HttpServletRequest request,Device device) throws IOException { com.abada.springframework.web.servlet.menu.Device deviceAux; if (device.isMobile()) { deviceAux = com.abada.springframework.web.servlet.menu.Device.MOBILE; } else if (device.isNormal()) { deviceAux = com.abada.springframework.web.servlet.menu.Device.DESKTOP; } else { deviceAux = com.abada.springframework.web.servlet.menu.Device.TABLET; } return new InputStreamView(formDispatcherPlugin.provideForm(new FormAuthorityRef(definitionid,deviceAux.name(), FormAuthorityRef.Type.PROCESS)).getInputStream(), "text/html", null); } /** * Submit and start the process instance of the form showed in the renderProcess method. * @param definitionid Process id * @param request Do nothing. * @param model Do nothing. * @return Return success structure. */ @RolesAllowed(value={"ROLE_ADMIN","ROLE_USER"}) @RequestMapping(value = "/{definitionid}/complete", method = RequestMethod.POST) /*public ProcessInstanceRef completeProcess(@PathVariable String definitionid, HttpServletRequest request) throws IOException { * return processManagement.newInstance(definitionid, URL.parseRequest(request)); * }*/ public String completeProcess(@PathVariable String definitionid, HttpServletRequest request, Model model) { try { ProcessInstanceRef pir = processManagement.newInstance(definitionid, URL.parseRequest(request)); model.addAttribute("error", pir.getId()); model.addAttribute("success", Boolean.TRUE.toString()); } catch (Exception e) { model.addAttribute("success", Boolean.FALSE.toString()); model.addAttribute("error", e.getMessage()); } return "success"; } //</editor-fold> }
true
true
private String completeProcessPriv(String definitionid, Long patientId,HttpServletRequest request, Model model) { try { Map<String, Object> params = URL.parseRequest(request); Patient patient = this.patientDao.getPatientById(patientId); //params.put("patient_patientids", patient.getPatientidList()); params.put("patient_birthday", patient.getBirthDay()); params.put("patient_genre", patient.getGenre().toString()); params.put("patient_id", patient.getId()); params.put("putoactor",patient.getUser().getUsername()); ProcessInstanceRef pir = processManagement.newInstance(definitionid, params); if (pir != null) { this.pInstancePatientDao.addPInstancePatient(patientId, Long.parseLong(pir.getId())); model.addAttribute("error", pir.getId()); model.addAttribute("success", Boolean.TRUE.toString()); } else { model.addAttribute("success", Boolean.FALSE.toString()); model.addAttribute("error", "ProcessInstance null"); } } catch (Exception e) { model.addAttribute("success", Boolean.FALSE.toString()); model.addAttribute("error", e.getMessage()); } return "success"; }
private String completeProcessPriv(String definitionid, Long patientId,HttpServletRequest request, Model model) { try { Map<String, Object> params = URL.parseRequest(request); Patient patient = this.patientDao.getPatientById(patientId); //params.put("patient_patientids", patient.getPatientidList()); params.put("patient_birthday", patient.getBirthDay()); params.put("patient_genre", patient.getGenre().toString()); params.put("patient_id", patient.getId()); params.put("patient_username",patient.getUser().getUsername()); ProcessInstanceRef pir = processManagement.newInstance(definitionid, params); if (pir != null) { this.pInstancePatientDao.addPInstancePatient(patientId, Long.parseLong(pir.getId())); model.addAttribute("error", pir.getId()); model.addAttribute("success", Boolean.TRUE.toString()); } else { model.addAttribute("success", Boolean.FALSE.toString()); model.addAttribute("error", "ProcessInstance null"); } } catch (Exception e) { model.addAttribute("success", Boolean.FALSE.toString()); model.addAttribute("error", e.getMessage()); } return "success"; }
diff --git a/src/main/java/tconstruct/client/tabs/AbstractTab.java b/src/main/java/tconstruct/client/tabs/AbstractTab.java index 4e14da422..97da51632 100644 --- a/src/main/java/tconstruct/client/tabs/AbstractTab.java +++ b/src/main/java/tconstruct/client/tabs/AbstractTab.java @@ -1,67 +1,67 @@ package tconstruct.client.tabs; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.*; public abstract class AbstractTab extends GuiButton { ResourceLocation texture = new ResourceLocation("textures/gui/container/creative_inventory/tabs.png"); ItemStack renderStack; RenderItem itemRenderer = new RenderItem(); public AbstractTab(int id, int posX, int posY, ItemStack renderStack) { super(id, posX, posY, 28, 32, ""); this.renderStack = renderStack; } @Override public void drawButton (Minecraft mc, int mouseX, int mouseY) { if (this.visible) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); - int yTexPos = this.enabled ? 0 : 32; + int yTexPos = this.enabled ? 3 : 32; int ySize = this.enabled ? 28 : 32; int xOffset = this.id == 2 ? 0 : 1; mc.renderEngine.bindTexture(this.texture); this.drawTexturedModalRect(this.xPosition, this.yPosition, xOffset * 28, yTexPos, 28, ySize); RenderHelper.enableGUIStandardItemLighting(); this.zLevel = 100.0F; this.itemRenderer.zLevel = 100.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); this.itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); this.itemRenderer.renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); GL11.glDisable(GL11.GL_LIGHTING); this.itemRenderer.zLevel = 0.0F; this.zLevel = 0.0F; RenderHelper.disableStandardItemLighting(); } } @Override public boolean mousePressed (Minecraft mc, int mouseX, int mouseY) { boolean inWindow = this.enabled && this.visible && mouseX >= this.xPosition && mouseY >= this.yPosition && mouseX < this.xPosition + this.width && mouseY < this.yPosition + this.height; if (inWindow) { this.onTabClicked(); } return inWindow; } public abstract void onTabClicked (); public abstract boolean shouldAddToList (); }
true
true
public void drawButton (Minecraft mc, int mouseX, int mouseY) { if (this.visible) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); int yTexPos = this.enabled ? 0 : 32; int ySize = this.enabled ? 28 : 32; int xOffset = this.id == 2 ? 0 : 1; mc.renderEngine.bindTexture(this.texture); this.drawTexturedModalRect(this.xPosition, this.yPosition, xOffset * 28, yTexPos, 28, ySize); RenderHelper.enableGUIStandardItemLighting(); this.zLevel = 100.0F; this.itemRenderer.zLevel = 100.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); this.itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); this.itemRenderer.renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); GL11.glDisable(GL11.GL_LIGHTING); this.itemRenderer.zLevel = 0.0F; this.zLevel = 0.0F; RenderHelper.disableStandardItemLighting(); } }
public void drawButton (Minecraft mc, int mouseX, int mouseY) { if (this.visible) { GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); int yTexPos = this.enabled ? 3 : 32; int ySize = this.enabled ? 28 : 32; int xOffset = this.id == 2 ? 0 : 1; mc.renderEngine.bindTexture(this.texture); this.drawTexturedModalRect(this.xPosition, this.yPosition, xOffset * 28, yTexPos, 28, ySize); RenderHelper.enableGUIStandardItemLighting(); this.zLevel = 100.0F; this.itemRenderer.zLevel = 100.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL12.GL_RESCALE_NORMAL); this.itemRenderer.renderItemAndEffectIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); this.itemRenderer.renderItemOverlayIntoGUI(mc.fontRenderer, mc.renderEngine, renderStack, xPosition + 6, yPosition + 8); GL11.glDisable(GL11.GL_LIGHTING); this.itemRenderer.zLevel = 0.0F; this.zLevel = 0.0F; RenderHelper.disableStandardItemLighting(); } }
diff --git a/src/plugin/bleachisback/LogiBlocks/LogiBlocksMain.java b/src/plugin/bleachisback/LogiBlocks/LogiBlocksMain.java index 3605284..de383d6 100644 --- a/src/plugin/bleachisback/LogiBlocks/LogiBlocksMain.java +++ b/src/plugin/bleachisback/LogiBlocks/LogiBlocksMain.java @@ -1,900 +1,900 @@ package plugin.bleachisback.LogiBlocks; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Random; import java.util.logging.Logger; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Server; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.command.BlockCommandSender; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.configuration.Configuration; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryHolder; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.ShapedRecipe; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.SkullMeta; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.PluginDescriptionFile; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; public class LogiBlocksMain extends JavaPlugin implements FlagListener { protected Logger log; private Server server; private PluginDescriptionFile desc; private PluginManager pm; protected FileConfiguration flagConfig; protected Configuration config; protected static File flagFile; protected HashMap<String, FlagListener> flags= new HashMap<String, FlagListener>(); private HashMap<String,Integer> inventorySubs=new HashMap<String,Integer>(); public void onEnable() { server=getServer(); log=getLogger(); desc=getDescription(); pm=server.getPluginManager(); flagFile=new File(getDataFolder(), "flags"); flagConfig=YamlConfiguration.loadConfiguration(flagFile); convertOldFlags(); saveDefaultConfig(); config=getConfig(); getCommand("command").setExecutor(new BaseCommandListener(this)); getCommand("logicif").setExecutor(new LogiCommandListener(this)); if(config.getBoolean("allow-crafting", true)) { pm.registerEvents(new LogiBlocksCraftListener(this), this); setupRecipe(); } if(config.getBoolean("allow-command-insertion",true)) { pm.registerEvents(new LogiBlocksInteractListener(this), this); setupPermissions(); } registerFlag("getFlag",this); registerFlag("isFlag",this); registerFlag("getGlobalFlag",this); registerFlag("isGlobalFlag",this); registerFlag("hasequip",this); registerFlag("inventory",this); registerFlag("exists",this); registerFlag("hasPassenger",this); registerFlag("isPassenger",this); inventorySubs.put("contains",1); inventorySubs.put("containsexact",1); inventorySubs.put("isfull",0); inventorySubs.put("isempty",0); inventorySubs.put("slot",2); log.info(desc.getFullName()+" is enabled"); } public void onDisable() { trace(desc.getName()+" is disabled"); } private void trace(String string) { log.info(string); } @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { switch(cmd.getName()) { case "phantom": if(sender.hasPermission("c.hidden.phantom")&&args.length>1) { server.getPlayer(args[0]).remove(); return true; } break; } return false; } private char[][] getchar={{'a','b','c'},{'d','e','f'},{'g','h','i'}}; private void setupRecipe() { Material[][] mats=new Material[3][3]; HashMap<Material,Character> chars=new HashMap<Material,Character>(); for(int i=0;i<3;i++) { String[] units=config.getStringList("crafting-recipe").get(i).replace(" ","").split(","); for(int j=0;j<3;j++) { Material material=Material.matchMaterial(units[j]); if(material==null) { material=Material.getMaterial(Integer.parseInt(units[j])); } mats[i][j]=material; if(!chars.containsKey(material)) { chars.put(material,getchar[i][j]); } } } ItemStack result=new ItemStack(Material.COMMAND,1); ShapedRecipe recipe=new ShapedRecipe(result); String[] shape=new String[3]; for(int i=0;i<3;i++) { shape[i]=""; for(int j=0;j<3;j++) { Material material=mats[i][j]; shape[i]=shape[i]+chars.get(material).toString(); } } recipe.shape(shape); for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { Material material=mats[i][j]; if(material!=Material.AIR) { recipe.setIngredient(chars.get(material), material); } } } server.addRecipe(recipe); } private void setupPermissions() { for(String perm:config.getConfigurationSection("permissions").getKeys(false)) { pm.addPermission(new Permission("c.permission."+perm,PermissionDefault.OP)); } } private void convertOldFlags() { //Converts old flag files to new ones //All old flags are now global flags for(String name:flagConfig.getKeys(false)) { if(!name.equals("global")&&!name.equals("local")) { flagConfig.set("global."+name, flagConfig.getBoolean(name)); flagConfig.set(name, null); try { flagConfig.save(flagFile); } catch (IOException e) { e.printStackTrace(); } } } } public boolean onFlag(String flag, String[] args, BlockCommandSender sender) throws FlagFailureException { switch(flag) { case "getflag": - if(!(args.length<1)) + if(args.length<1) { throw new FlagFailureException(); } if(flagConfig.contains("local."+sender.getName()+"."+args[0])) { return flagConfig.getBoolean("local."+sender.getName()+"."+args[0]); } else { throw new FlagFailureException(); } //end getflag case "isflag": - if(!(args.length<1)) + if(args.length<1) { throw new FlagFailureException(); } if(flagConfig.contains("local."+sender.getName()+"."+args[0])) { return true; } else { return false; } //end isflag case "getglobalflag": - if(!(args.length<1)) + if(args.length<1) { throw new FlagFailureException(); } if(flagConfig.contains("global."+args[0])) { return flagConfig.getBoolean("global."+args[0]); } else { throw new FlagFailureException(); } //end getglobalflag case "isglobalflag": - if(!(args.length<1)) + if(args.length<1) { throw new FlagFailureException(); } if(flagConfig.contains("global."+args[0])) { return true; } else { return false; } //end isglobalflag case "hasequip": switch(args.length) { case 1: Entity equipEntity=LogiBlocksMain.parseEntity(args[0],sender.getBlock().getWorld()); if(equipEntity==null||!(equipEntity instanceof LivingEntity)) { equipEntity=server.getPlayer(args[0]); if(equipEntity==null) { throw new FlagFailureException(); } } ItemStack[] equip=((LivingEntity) equipEntity).getEquipment().getArmorContents(); return equip[0].getType()==Material.AIR?equip[1].getType()==Material.AIR?equip[2].getType()==Material.AIR?equip[3].getType()==Material.AIR?false:true:true:true:true; case 2: Entity equipEntity1=LogiBlocksMain.parseEntity(args[0],sender.getBlock().getWorld()); if(equipEntity1==null||!(equipEntity1 instanceof LivingEntity)) { equipEntity1=server.getPlayer(args[0]); if(equipEntity1==null) { throw new FlagFailureException(); } } ItemStack[] equip1=((LivingEntity) equipEntity1).getEquipment().getArmorContents(); switch(args[1]) { case "head": case "helmet": return equip1[3].getType()!=Material.AIR; case "chest": case "chestplate": case "shirt": return equip1[2].getType()!=Material.AIR; case "legs": case "leggings": case "pants": return equip1[1].getType()!=Material.AIR; case "feet": case "boots": case "shoes": return equip1[0].getType()!=Material.AIR; } break; case 3: ItemStack item=LogiBlocksMain.parseItemStack(args[2]); if(item==null) { throw new FlagFailureException(); } Entity equipEntity2=LogiBlocksMain.parseEntity(args[0],sender.getBlock().getWorld()); if(equipEntity2==null||!(equipEntity2 instanceof LivingEntity)) { equipEntity2=server.getPlayer(args[0]); if(equipEntity2==null) { throw new FlagFailureException(); } } ItemStack[] equip2=((LivingEntity) equipEntity2).getEquipment().getArmorContents(); switch(args[1]) { case "head": case "helmet": return equip2[3].equals(item); case "chest": case "chestplate": case "shirt": return equip2[2].equals(item); case "legs": case "leggings": case "pants": return equip2[1].equals(item); case "feet": case "boots": case "shoes": return equip2[0].equals(item); } break; } break; //end hasequip case "inventory": Inventory inventory= null; if(args.length<1) { throw new FlagFailureException(); } if((args[0].startsWith("@l[")&&args[1].endsWith("]"))||inventorySubs.containsKey(args[0])) { Location invLocation=LogiBlocksMain.parseLocation(args[0], sender.getBlock().getLocation()); loop: for(int x=-1;x<=1;x++) { for(int y=-1;y<=1;y++) { for(int z=-1;z<=1;z++) { Block testBlock=invLocation.clone().add(x, y, z).getBlock(); if(testBlock.getState() instanceof InventoryHolder) { inventory=((InventoryHolder) testBlock.getState()).getInventory(); break loop; } } } } } else { Player player=Bukkit.getPlayer(args[0]); if(player==null) { throw new FlagFailureException(); } inventory=player.getInventory(); } if(inventory==null) { throw new FlagFailureException(); } int subIndex=inventorySubs.containsKey(args[0])?0:1; if(!inventorySubs.containsKey(args[subIndex])) { throw new FlagFailureException(); } if(inventorySubs.get(args[subIndex])+subIndex+1>args.length) { throw new FlagFailureException(); } switch(args[subIndex].toLowerCase()) { case "contains": ItemStack item=LogiBlocksMain.parseItemStack(args[subIndex+1]); if(item==null) { throw new FlagFailureException(); } for(ItemStack testItem:inventory.getContents()) { if(testItem==null) { continue; } else if(item.isSimilar(testItem)) { return true; } } return false; case "containsexact": ItemStack item1=LogiBlocksMain.parseItemStack(args[subIndex+1]); if(item1==null) { throw new FlagFailureException(); } return inventory.contains(item1); case "isfull": return inventory.firstEmpty()==-1; case "isempty": for(ItemStack testItem:inventory.getContents()) { if(testItem!=null) { throw new FlagFailureException(); } } return true; case "slot": int slot=Integer.parseInt(args[subIndex+1]); if(slot>=inventory.getSize()) { slot=inventory.getSize()-1; } if(slot<0) { slot=0; } switch(args[subIndex+2].toLowerCase()) { case "is": if(args.length<=subIndex+3) { throw new FlagFailureException(); } ItemStack item2=LogiBlocksMain.parseItemStack(args[subIndex+3]); if(item2==null) { throw new FlagFailureException(); } return item2.isSimilar(inventory.getItem(slot)); case "isexact": if(args.length<=subIndex+3) { throw new FlagFailureException(); } ItemStack item3=LogiBlocksMain.parseItemStack(args[subIndex+3]); if(item3==null) { throw new FlagFailureException(); } return item3.equals(inventory.getItem(slot)); case "isenchanted": ItemStack item4=inventory.getItem(slot); if(item4==null) { throw new FlagFailureException(); } return !item4.getEnchantments().isEmpty(); } break; } break; //end inventory case "exists": if(args.length<1) { throw new FlagFailureException(); } return parseEntity(args[0],sender.getBlock().getWorld())!=null; //end exists case "haspassenger": if(args.length<1) { throw new FlagFailureException(); } Entity entity = parseEntity(args[0],sender.getBlock().getWorld()); if(entity==null) { throw new FlagFailureException(); } return entity.getPassenger()!=null; //end hasPassanger case "ispassenger": if(args.length<1) { throw new FlagFailureException(); } Entity entity1 = parseEntity(args[0],sender.getBlock().getWorld()); if(entity1==null) { throw new FlagFailureException(); } return entity1.getVehicle()!=null; //end isPassenger } throw new FlagFailureException(); } public static boolean filter(String[] args, BlockCommandSender block, Command command) { for(int currentArg=0;currentArg<args.length;currentArg++) { String string=args[currentArg]; if(string.startsWith("@")) { switch(string.charAt(1)) { case 'e': World world=block.getBlock().getWorld(); //search properties EntityType type=null; double x=block.getBlock().getX(); double y=block.getBlock().getY(); double z=block.getBlock().getZ(); int r=0; int rm=0; int c=1; boolean rand=false; if(string.contains("[")&&string.contains("]")) { if(!string.contains("=")) { return true; } for(String args1:string.substring(string.indexOf("[")+1, string.indexOf("]")).split(",")) { if(args1.length()<3||!args1.contains("=")) { continue; } if(args1.length()<=args1.indexOf("=")) { continue; } switch(args1.substring(0,args1.indexOf("="))) { case "t": type=EntityType.fromName(args1.substring(2,args1.length())); break; case "x": x=Double.parseDouble(args1.substring(2,args1.length())); break; case "y": y=Double.parseDouble(args1.substring(2,args1.length())); break; case "z": z=Double.parseDouble(args1.substring(2,args1.length())); break; case "loc": String[] locArray=args1.substring(2,args1.length()).split("\\|"); switch(locArray.length) { default: case 3: z=Double.parseDouble(locArray[2]); case 2: y=Double.parseDouble(locArray[1]); case 1: x=Double.parseDouble(locArray[0]); break; case 0: break; } break; case "r": r=Integer.parseInt(args1.substring(2,args1.length())); break; case "rm": rm=Integer.parseInt(args1.substring(3,args1.length())); break; case "c": c=Integer.parseInt(args1.substring(2,args1.length())); break; case "rand": rand=Boolean.parseBoolean(args1.substring(5,args1.length())); break; } } } List<Entity> nearbyEntities=block.getBlock().getWorld().getEntities(); for(int i=0;i<nearbyEntities.size();i++) { if(i<0) { continue; } Entity entity=nearbyEntities.get(i); if((entity.getLocation().distance(new Location(world,x,y,z))>r&&r>0) ||(entity.getLocation().distance(new Location(world,x,y,z))<rm)) { nearbyEntities.remove(entity); i--; } if(type!=null) { if(entity.getType()!=type) { nearbyEntities.remove(entity); i--; } } } if(nearbyEntities.size()==0) { return false; } if(c<1) { c=nearbyEntities.size(); } Entity[] entities=new Entity[c]; if(rand) { for(int i=0;i<c;i++) { Entity entity=nearbyEntities.get(new Random().nextInt(nearbyEntities.size())); entities[i]=entity; nearbyEntities.remove(entity); } } else { Location loc=block.getBlock().getLocation(); for(int i=0;i<c;i++) { double distance=nearbyEntities.get(0).getLocation().distance(loc); Entity entity=nearbyEntities.get(0); for(Entity e:nearbyEntities) { if(loc.distance(e.getLocation())<distance) { distance=loc.distance(e.getLocation()); entity=e; } } entities[i]=entity; nearbyEntities.remove(entity); } } String entid=""; if(c==1) { entid=""+entities[0].getEntityId(); args[currentArg]="@e["+entid+"]"; } else { String[] newArgs=args; for(int i=0;i<c;i++) { String newArg="@e["+entities[i].getEntityId()+"]"; for(int j=currentArg+1;j<args.length;j++) { Bukkit.getLogger().info("Arg comparison: "+args[currentArg]+" == "+args[j]); if(args[currentArg].equals(args[j])) { Bukkit.getLogger().info("True"); newArgs[j]=newArg; } } newArgs[currentArg]=newArg; command.execute(block, command.getLabel(), newArgs); } return false; } return true; //End @e } } } return true; } public static ItemStack parseItemStack(String itemString) { if(itemString.startsWith("@i[")&&itemString.endsWith("]")) { Material mat=Material.AIR; int amount=1; short damage=0; String name=null; String lore=null; HashMap<Enchantment, Integer> enchantments= new HashMap<Enchantment, Integer>(); String owner=null; for(String arg:itemString.substring(itemString.indexOf("[")+1,itemString.indexOf("]")).split(",")) { if(arg.length()<3||!arg.contains("=")) { continue; } if(arg.length()<=arg.indexOf("=")) { continue; } switch(arg.substring(0,arg.indexOf("="))) { case "m": case "mat": case "material": case "id": mat=Material.matchMaterial(arg.substring(arg.indexOf("=")+1,arg.length()).toUpperCase()); break; case "c": case "count": case "amount": amount=Integer.parseInt(arg.substring(arg.indexOf("=")+1,arg.length())); break; case "d": case "data": case "damage": case "durability": damage=Short.parseShort(arg.substring(arg.indexOf("=")+1,arg.length())); break; case "n": case "name": name=arg.substring(arg.indexOf("=")+1,arg.length()).replace("_", " "); break; case "l": case "lore": case "description": lore=arg.substring(arg.indexOf("=")+1,arg.length()); break; case "e": case "enchant": case "enchantment": String enchString=arg.substring(arg.indexOf("=")+1,arg.length()); if(enchString.contains("|")) { String[] enchStringArray=enchString.split("\\|"); enchantments.put(Enchantment.getByName(enchStringArray[0].toUpperCase()), Integer.valueOf(enchStringArray[1])); } break; case "o": case "owner": owner=arg.substring(arg.indexOf("=")+1,arg.length()); break; } } if(mat==null) { mat=Material.AIR; } ItemStack item=new ItemStack(mat,amount,damage); ItemMeta meta=item.getItemMeta(); if(name!=null) { meta.setDisplayName(name); } if(lore!=null) { meta.setLore(Arrays.asList(lore.replace("_"," ").split("\\|"))); } if(item.getType()==Material.SKULL_ITEM&&owner!=null) { ((SkullMeta) meta).setOwner(owner); } item.setItemMeta(meta); for(Enchantment ench:enchantments.keySet()) { if(ench==null||enchantments.get(ench)==null) { continue; } item.addUnsafeEnchantment(ench, enchantments.get(ench)); } return item; } return null; } public static Entity parseEntity(String entity, World world) { if(entity.startsWith("@e[")&&entity.endsWith("]")) { int id=0; try { id=Integer.parseInt(entity.substring(3, entity.length()-1)); } catch(Exception e) { return null; } for(Entity ent:world.getEntities()) { if(ent.getEntityId()==id) { return ent; } } } return Bukkit.getPlayer(entity); } public static Location parseLocation(String locString, Location def) { if(locString.startsWith("@l[")&&locString.endsWith("]")) { World world=def.getWorld(); double x=def.getX(); double y=def.getY(); double z=def.getZ(); float yaw=def.getYaw(); float pitch=def.getPitch(); for(String arg:locString.substring(locString.indexOf("[")+1,locString.indexOf("]")).split(",")) { if(arg.length()<3||!arg.contains("=")) { continue; } if(arg.length()<=arg.indexOf("=")) { continue; } switch(arg.substring(0,arg.indexOf("="))) { case "w": case "world": world=Bukkit.getWorld(arg.substring(arg.indexOf("=")+1,arg.length())); break; case "c": case "coords": case "coordinates": String[] coords=arg.substring(arg.indexOf("=")+1,arg.length()).split("\\|"); switch(coords.length) { default: case 3: z=Double.parseDouble(coords[2]); case 2: y=Double.parseDouble(coords[1]); case 1: x=Double.parseDouble(coords[0]); break; case 0: break; } break; case "x": x=Double.parseDouble(arg.substring(arg.indexOf("=")+1,arg.length())); break; case "y": y=Double.parseDouble(arg.substring(arg.indexOf("=")+1,arg.length())); break; case "z": z=Double.parseDouble(arg.substring(arg.indexOf("=")+1,arg.length())); break; case "p": case "pitch": pitch=Float.parseFloat(arg.substring(arg.indexOf("=")+1,arg.length())); break; case "ya": case "yaw": yaw=Float.parseFloat(arg.substring(arg.indexOf("=")+1,arg.length())); break; } } return new Location(world,x,y,z,yaw,pitch); } else if(parseEntity(locString,def.getWorld())!=null) { return parseEntity(locString,def.getWorld()).getLocation(); } return def; } public void registerFlag(String flag, FlagListener listener) { if(listener==null) { return; } flags.put(flag.toLowerCase().replace(" ", "_"), listener); } }
false
true
public boolean onFlag(String flag, String[] args, BlockCommandSender sender) throws FlagFailureException { switch(flag) { case "getflag": if(!(args.length<1)) { throw new FlagFailureException(); } if(flagConfig.contains("local."+sender.getName()+"."+args[0])) { return flagConfig.getBoolean("local."+sender.getName()+"."+args[0]); } else { throw new FlagFailureException(); } //end getflag case "isflag": if(!(args.length<1)) { throw new FlagFailureException(); } if(flagConfig.contains("local."+sender.getName()+"."+args[0])) { return true; } else { return false; } //end isflag case "getglobalflag": if(!(args.length<1)) { throw new FlagFailureException(); } if(flagConfig.contains("global."+args[0])) { return flagConfig.getBoolean("global."+args[0]); } else { throw new FlagFailureException(); } //end getglobalflag case "isglobalflag": if(!(args.length<1)) { throw new FlagFailureException(); } if(flagConfig.contains("global."+args[0])) { return true; } else { return false; } //end isglobalflag case "hasequip": switch(args.length) { case 1: Entity equipEntity=LogiBlocksMain.parseEntity(args[0],sender.getBlock().getWorld()); if(equipEntity==null||!(equipEntity instanceof LivingEntity)) { equipEntity=server.getPlayer(args[0]); if(equipEntity==null) { throw new FlagFailureException(); } } ItemStack[] equip=((LivingEntity) equipEntity).getEquipment().getArmorContents(); return equip[0].getType()==Material.AIR?equip[1].getType()==Material.AIR?equip[2].getType()==Material.AIR?equip[3].getType()==Material.AIR?false:true:true:true:true; case 2: Entity equipEntity1=LogiBlocksMain.parseEntity(args[0],sender.getBlock().getWorld()); if(equipEntity1==null||!(equipEntity1 instanceof LivingEntity)) { equipEntity1=server.getPlayer(args[0]); if(equipEntity1==null) { throw new FlagFailureException(); } } ItemStack[] equip1=((LivingEntity) equipEntity1).getEquipment().getArmorContents(); switch(args[1]) { case "head": case "helmet": return equip1[3].getType()!=Material.AIR; case "chest": case "chestplate": case "shirt": return equip1[2].getType()!=Material.AIR; case "legs": case "leggings": case "pants": return equip1[1].getType()!=Material.AIR; case "feet": case "boots": case "shoes": return equip1[0].getType()!=Material.AIR; } break; case 3: ItemStack item=LogiBlocksMain.parseItemStack(args[2]); if(item==null) { throw new FlagFailureException(); } Entity equipEntity2=LogiBlocksMain.parseEntity(args[0],sender.getBlock().getWorld()); if(equipEntity2==null||!(equipEntity2 instanceof LivingEntity)) { equipEntity2=server.getPlayer(args[0]); if(equipEntity2==null) { throw new FlagFailureException(); } } ItemStack[] equip2=((LivingEntity) equipEntity2).getEquipment().getArmorContents(); switch(args[1]) { case "head": case "helmet": return equip2[3].equals(item); case "chest": case "chestplate": case "shirt": return equip2[2].equals(item); case "legs": case "leggings": case "pants": return equip2[1].equals(item); case "feet": case "boots": case "shoes": return equip2[0].equals(item); } break; } break; //end hasequip case "inventory": Inventory inventory= null; if(args.length<1) { throw new FlagFailureException(); } if((args[0].startsWith("@l[")&&args[1].endsWith("]"))||inventorySubs.containsKey(args[0])) { Location invLocation=LogiBlocksMain.parseLocation(args[0], sender.getBlock().getLocation()); loop: for(int x=-1;x<=1;x++) { for(int y=-1;y<=1;y++) { for(int z=-1;z<=1;z++) { Block testBlock=invLocation.clone().add(x, y, z).getBlock(); if(testBlock.getState() instanceof InventoryHolder) { inventory=((InventoryHolder) testBlock.getState()).getInventory(); break loop; } } } } } else { Player player=Bukkit.getPlayer(args[0]); if(player==null) { throw new FlagFailureException(); } inventory=player.getInventory(); } if(inventory==null) { throw new FlagFailureException(); } int subIndex=inventorySubs.containsKey(args[0])?0:1; if(!inventorySubs.containsKey(args[subIndex])) { throw new FlagFailureException(); } if(inventorySubs.get(args[subIndex])+subIndex+1>args.length) { throw new FlagFailureException(); } switch(args[subIndex].toLowerCase()) { case "contains": ItemStack item=LogiBlocksMain.parseItemStack(args[subIndex+1]); if(item==null) { throw new FlagFailureException(); } for(ItemStack testItem:inventory.getContents()) { if(testItem==null) { continue; } else if(item.isSimilar(testItem)) { return true; } } return false; case "containsexact": ItemStack item1=LogiBlocksMain.parseItemStack(args[subIndex+1]); if(item1==null) { throw new FlagFailureException(); } return inventory.contains(item1); case "isfull": return inventory.firstEmpty()==-1; case "isempty": for(ItemStack testItem:inventory.getContents()) { if(testItem!=null) { throw new FlagFailureException(); } } return true; case "slot": int slot=Integer.parseInt(args[subIndex+1]); if(slot>=inventory.getSize()) { slot=inventory.getSize()-1; } if(slot<0) { slot=0; } switch(args[subIndex+2].toLowerCase()) { case "is": if(args.length<=subIndex+3) { throw new FlagFailureException(); } ItemStack item2=LogiBlocksMain.parseItemStack(args[subIndex+3]); if(item2==null) { throw new FlagFailureException(); } return item2.isSimilar(inventory.getItem(slot)); case "isexact": if(args.length<=subIndex+3) { throw new FlagFailureException(); } ItemStack item3=LogiBlocksMain.parseItemStack(args[subIndex+3]); if(item3==null) { throw new FlagFailureException(); } return item3.equals(inventory.getItem(slot)); case "isenchanted": ItemStack item4=inventory.getItem(slot); if(item4==null) { throw new FlagFailureException(); } return !item4.getEnchantments().isEmpty(); } break; } break; //end inventory case "exists": if(args.length<1) { throw new FlagFailureException(); } return parseEntity(args[0],sender.getBlock().getWorld())!=null; //end exists case "haspassenger": if(args.length<1) { throw new FlagFailureException(); } Entity entity = parseEntity(args[0],sender.getBlock().getWorld()); if(entity==null) { throw new FlagFailureException(); } return entity.getPassenger()!=null; //end hasPassanger case "ispassenger": if(args.length<1) { throw new FlagFailureException(); } Entity entity1 = parseEntity(args[0],sender.getBlock().getWorld()); if(entity1==null) { throw new FlagFailureException(); } return entity1.getVehicle()!=null; //end isPassenger } throw new FlagFailureException(); }
public boolean onFlag(String flag, String[] args, BlockCommandSender sender) throws FlagFailureException { switch(flag) { case "getflag": if(args.length<1) { throw new FlagFailureException(); } if(flagConfig.contains("local."+sender.getName()+"."+args[0])) { return flagConfig.getBoolean("local."+sender.getName()+"."+args[0]); } else { throw new FlagFailureException(); } //end getflag case "isflag": if(args.length<1) { throw new FlagFailureException(); } if(flagConfig.contains("local."+sender.getName()+"."+args[0])) { return true; } else { return false; } //end isflag case "getglobalflag": if(args.length<1) { throw new FlagFailureException(); } if(flagConfig.contains("global."+args[0])) { return flagConfig.getBoolean("global."+args[0]); } else { throw new FlagFailureException(); } //end getglobalflag case "isglobalflag": if(args.length<1) { throw new FlagFailureException(); } if(flagConfig.contains("global."+args[0])) { return true; } else { return false; } //end isglobalflag case "hasequip": switch(args.length) { case 1: Entity equipEntity=LogiBlocksMain.parseEntity(args[0],sender.getBlock().getWorld()); if(equipEntity==null||!(equipEntity instanceof LivingEntity)) { equipEntity=server.getPlayer(args[0]); if(equipEntity==null) { throw new FlagFailureException(); } } ItemStack[] equip=((LivingEntity) equipEntity).getEquipment().getArmorContents(); return equip[0].getType()==Material.AIR?equip[1].getType()==Material.AIR?equip[2].getType()==Material.AIR?equip[3].getType()==Material.AIR?false:true:true:true:true; case 2: Entity equipEntity1=LogiBlocksMain.parseEntity(args[0],sender.getBlock().getWorld()); if(equipEntity1==null||!(equipEntity1 instanceof LivingEntity)) { equipEntity1=server.getPlayer(args[0]); if(equipEntity1==null) { throw new FlagFailureException(); } } ItemStack[] equip1=((LivingEntity) equipEntity1).getEquipment().getArmorContents(); switch(args[1]) { case "head": case "helmet": return equip1[3].getType()!=Material.AIR; case "chest": case "chestplate": case "shirt": return equip1[2].getType()!=Material.AIR; case "legs": case "leggings": case "pants": return equip1[1].getType()!=Material.AIR; case "feet": case "boots": case "shoes": return equip1[0].getType()!=Material.AIR; } break; case 3: ItemStack item=LogiBlocksMain.parseItemStack(args[2]); if(item==null) { throw new FlagFailureException(); } Entity equipEntity2=LogiBlocksMain.parseEntity(args[0],sender.getBlock().getWorld()); if(equipEntity2==null||!(equipEntity2 instanceof LivingEntity)) { equipEntity2=server.getPlayer(args[0]); if(equipEntity2==null) { throw new FlagFailureException(); } } ItemStack[] equip2=((LivingEntity) equipEntity2).getEquipment().getArmorContents(); switch(args[1]) { case "head": case "helmet": return equip2[3].equals(item); case "chest": case "chestplate": case "shirt": return equip2[2].equals(item); case "legs": case "leggings": case "pants": return equip2[1].equals(item); case "feet": case "boots": case "shoes": return equip2[0].equals(item); } break; } break; //end hasequip case "inventory": Inventory inventory= null; if(args.length<1) { throw new FlagFailureException(); } if((args[0].startsWith("@l[")&&args[1].endsWith("]"))||inventorySubs.containsKey(args[0])) { Location invLocation=LogiBlocksMain.parseLocation(args[0], sender.getBlock().getLocation()); loop: for(int x=-1;x<=1;x++) { for(int y=-1;y<=1;y++) { for(int z=-1;z<=1;z++) { Block testBlock=invLocation.clone().add(x, y, z).getBlock(); if(testBlock.getState() instanceof InventoryHolder) { inventory=((InventoryHolder) testBlock.getState()).getInventory(); break loop; } } } } } else { Player player=Bukkit.getPlayer(args[0]); if(player==null) { throw new FlagFailureException(); } inventory=player.getInventory(); } if(inventory==null) { throw new FlagFailureException(); } int subIndex=inventorySubs.containsKey(args[0])?0:1; if(!inventorySubs.containsKey(args[subIndex])) { throw new FlagFailureException(); } if(inventorySubs.get(args[subIndex])+subIndex+1>args.length) { throw new FlagFailureException(); } switch(args[subIndex].toLowerCase()) { case "contains": ItemStack item=LogiBlocksMain.parseItemStack(args[subIndex+1]); if(item==null) { throw new FlagFailureException(); } for(ItemStack testItem:inventory.getContents()) { if(testItem==null) { continue; } else if(item.isSimilar(testItem)) { return true; } } return false; case "containsexact": ItemStack item1=LogiBlocksMain.parseItemStack(args[subIndex+1]); if(item1==null) { throw new FlagFailureException(); } return inventory.contains(item1); case "isfull": return inventory.firstEmpty()==-1; case "isempty": for(ItemStack testItem:inventory.getContents()) { if(testItem!=null) { throw new FlagFailureException(); } } return true; case "slot": int slot=Integer.parseInt(args[subIndex+1]); if(slot>=inventory.getSize()) { slot=inventory.getSize()-1; } if(slot<0) { slot=0; } switch(args[subIndex+2].toLowerCase()) { case "is": if(args.length<=subIndex+3) { throw new FlagFailureException(); } ItemStack item2=LogiBlocksMain.parseItemStack(args[subIndex+3]); if(item2==null) { throw new FlagFailureException(); } return item2.isSimilar(inventory.getItem(slot)); case "isexact": if(args.length<=subIndex+3) { throw new FlagFailureException(); } ItemStack item3=LogiBlocksMain.parseItemStack(args[subIndex+3]); if(item3==null) { throw new FlagFailureException(); } return item3.equals(inventory.getItem(slot)); case "isenchanted": ItemStack item4=inventory.getItem(slot); if(item4==null) { throw new FlagFailureException(); } return !item4.getEnchantments().isEmpty(); } break; } break; //end inventory case "exists": if(args.length<1) { throw new FlagFailureException(); } return parseEntity(args[0],sender.getBlock().getWorld())!=null; //end exists case "haspassenger": if(args.length<1) { throw new FlagFailureException(); } Entity entity = parseEntity(args[0],sender.getBlock().getWorld()); if(entity==null) { throw new FlagFailureException(); } return entity.getPassenger()!=null; //end hasPassanger case "ispassenger": if(args.length<1) { throw new FlagFailureException(); } Entity entity1 = parseEntity(args[0],sender.getBlock().getWorld()); if(entity1==null) { throw new FlagFailureException(); } return entity1.getVehicle()!=null; //end isPassenger } throw new FlagFailureException(); }
diff --git a/src/main/java/net/h31ix/anticheat/util/Utilities.java b/src/main/java/net/h31ix/anticheat/util/Utilities.java index 0d63eea..a0510c7 100644 --- a/src/main/java/net/h31ix/anticheat/util/Utilities.java +++ b/src/main/java/net/h31ix/anticheat/util/Utilities.java @@ -1,231 +1,231 @@ /* * AntiCheat for Bukkit. * Copyright (C) 2012 AntiCheat Team | http://h31ix.net * * 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 net.h31ix.anticheat.util; import com.gmail.nossr50.datatypes.AbilityType; import com.gmail.nossr50.mcMMO; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import net.h31ix.anticheat.Anticheat; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; public final class Utilities { private static final List<Material> INSTANT_BREAK = new ArrayList<Material>(); private static final List<Material> FOOD = new ArrayList<Material>(); private static final List<Material> INTERACTABLE = new ArrayList<Material>(); private static final HashSet<Byte> NOTSOLID = new HashSet<Byte>(); public static void alert(String[] message) { for(Player player : Bukkit.getOnlinePlayers()) { - if(player.hasPermission("anticheat.alert")); for (String msg : message) { - player.sendMessage(msg); + if(player.hasPermission("anticheat.alert")) + player.sendMessage(msg); } } if (Anticheat.getManager().getConfiguration().logConsole()) { for (String msg : message) { Anticheat.getManager().log(msg); } } } public static boolean cantStandAt(Block block) { return !canStand(block) && cantStandClose(block) && cantStandFar(block); } public static boolean cantStandClose(Block block) { return !canStand(block.getRelative(BlockFace.NORTH)) && !canStand(block.getRelative(BlockFace.EAST)) && !canStand(block.getRelative(BlockFace.SOUTH)) && !canStand(block.getRelative(BlockFace.WEST)); } public static boolean cantStandFar(Block block) { return !canStand(block.getRelative(BlockFace.NORTH_WEST)) && !canStand(block.getRelative(BlockFace.NORTH_EAST)) && !canStand(block.getRelative(BlockFace.SOUTH_WEST)) && !canStand(block.getRelative(BlockFace.SOUTH_EAST)); } public static boolean canStand(Block block) { return !(block.isLiquid() || block.getType() == Material.AIR); } public static boolean isInstantBreak(Material m) { return INSTANT_BREAK.contains(m); } public static boolean isFood(Material m) { return FOOD.contains(m); } public static boolean isInteractable(Material m) { return INTERACTABLE.contains(m); } public static HashSet<Byte> getNonSolid() { return NOTSOLID; } public static boolean sprintFly(Player player) { return player.isSprinting() || player.isFlying(); } public static boolean isOnLilyPad(Player player) { Block block = player.getLocation().getBlock(); Material lily = Material.WATER_LILY; return block.getType() == lily || block.getRelative(BlockFace.NORTH).getType() == lily || block.getRelative(BlockFace.SOUTH).getType() == lily || block.getRelative(BlockFace.EAST).getType() == lily || block.getRelative(BlockFace.WEST).getType() == lily; } public static boolean isUsingMcMMOAbility(Player player) { boolean b = false; if (player.getServer().getPluginManager().getPlugin("mcMMO") != null) { if (mcMMO.p.getPlayerProfile(player).getAbilityMode(AbilityType.TREE_FELLER) || mcMMO.p.getPlayerProfile(player).getAbilityMode(AbilityType.SUPER_BREAKER) || mcMMO.p.getPlayerProfile(player).getAbilityMode(AbilityType.BERSERK) || mcMMO.p.getPlayerProfile(player).getAbilityMode(AbilityType.GIGA_DRILL_BREAKER) || mcMMO.p.getPlayerProfile(player).getAbilityMode(AbilityType.BLAST_MINING)) { b = true; } } return b; } public static boolean isSubmersed(Player player) { return player.getLocation().getBlock().isLiquid() && player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); } public static boolean isInWater(Player player) { return player.getLocation().getBlock().isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.DOWN).isLiquid() || player.getLocation().getBlock().getRelative(BlockFace.UP).isLiquid(); } public static boolean isOnClimbableBlock(Player player) { return player.getLocation().getBlock().getType() == Material.VINE || player.getLocation().getBlock().getType() == Material.LADDER; } public static boolean isOnVine(Player player) { return player.getLocation().getBlock().getType() == Material.VINE; } public static boolean isInt(String string) { boolean x = false; try { Integer.parseInt(string); x = true; } catch (Exception ex) { } return x; } static { INSTANT_BREAK.add(Material.RED_MUSHROOM); INSTANT_BREAK.add(Material.RED_ROSE); INSTANT_BREAK.add(Material.BROWN_MUSHROOM); INSTANT_BREAK.add(Material.YELLOW_FLOWER); INSTANT_BREAK.add(Material.REDSTONE); INSTANT_BREAK.add(Material.REDSTONE_TORCH_OFF); INSTANT_BREAK.add(Material.REDSTONE_TORCH_ON); INSTANT_BREAK.add(Material.REDSTONE_WIRE); INSTANT_BREAK.add(Material.LONG_GRASS); INSTANT_BREAK.add(Material.PAINTING); INSTANT_BREAK.add(Material.WHEAT); INSTANT_BREAK.add(Material.SUGAR_CANE); INSTANT_BREAK.add(Material.SUGAR_CANE_BLOCK); INSTANT_BREAK.add(Material.DIODE); INSTANT_BREAK.add(Material.DIODE_BLOCK_OFF); INSTANT_BREAK.add(Material.DIODE_BLOCK_ON); INSTANT_BREAK.add(Material.SAPLING); INSTANT_BREAK.add(Material.TORCH); INSTANT_BREAK.add(Material.CROPS); INSTANT_BREAK.add(Material.SNOW); INSTANT_BREAK.add(Material.TNT); INTERACTABLE.add(Material.STONE_BUTTON); INTERACTABLE.add(Material.LEVER); INTERACTABLE.add(Material.CHEST); NOTSOLID.add((byte)Material.TORCH.getId()); NOTSOLID.add((byte)Material.REDSTONE_TORCH_OFF.getId()); NOTSOLID.add((byte)Material.REDSTONE_TORCH_OFF.getId()); NOTSOLID.add((byte)Material.FENCE.getId()); NOTSOLID.add((byte)Material.FENCE_GATE.getId()); NOTSOLID.add((byte)Material.IRON_FENCE.getId()); NOTSOLID.add((byte)Material.NETHER_FENCE.getId()); NOTSOLID.add((byte)Material.TRAP_DOOR.getId()); NOTSOLID.add((byte)Material.SIGN.getId()); NOTSOLID.add((byte)Material.STONE_BUTTON.getId()); NOTSOLID.add((byte)Material.LEVER.getId()); NOTSOLID.add((byte)Material.AIR.getId()); NOTSOLID.add((byte)Material.WATER.getId()); NOTSOLID.add((byte)Material.LAVA.getId()); NOTSOLID.add((byte)Material.REDSTONE_WIRE.getId()); NOTSOLID.add((byte)Material.WOOD_PLATE.getId()); NOTSOLID.add((byte)Material.STONE_PLATE.getId()); NOTSOLID.add((byte)Material.SAPLING.getId()); NOTSOLID.add((byte)Material.RED_ROSE.getId()); NOTSOLID.add((byte)Material.YELLOW_FLOWER.getId()); NOTSOLID.add((byte)Material.BROWN_MUSHROOM.getId()); NOTSOLID.add((byte)Material.RED_MUSHROOM.getId()); NOTSOLID.add((byte)Material.THIN_GLASS.getId()); NOTSOLID.add((byte)Material.LADDER.getId()); NOTSOLID.add((byte)Material.RAILS.getId()); NOTSOLID.add((byte)Material.DETECTOR_RAIL.getId()); NOTSOLID.add((byte)Material.POWERED_RAIL.getId()); NOTSOLID.add((byte)Material.STEP.getId()); NOTSOLID.add((byte)Material.VINE.getId()); NOTSOLID.add((byte)Material.ENCHANTMENT_TABLE.getId()); FOOD.add(Material.COOKED_BEEF); FOOD.add(Material.COOKED_CHICKEN); FOOD.add(Material.COOKED_FISH); FOOD.add(Material.GRILLED_PORK); FOOD.add(Material.PORK); FOOD.add(Material.MUSHROOM_SOUP); FOOD.add(Material.RAW_BEEF); FOOD.add(Material.RAW_CHICKEN); FOOD.add(Material.RAW_FISH); FOOD.add(Material.APPLE); FOOD.add(Material.GOLDEN_APPLE); FOOD.add(Material.MELON); FOOD.add(Material.COOKIE); FOOD.add(Material.BREAD); FOOD.add(Material.SPIDER_EYE); FOOD.add(Material.ROTTEN_FLESH); } }
false
true
public static void alert(String[] message) { for(Player player : Bukkit.getOnlinePlayers()) { if(player.hasPermission("anticheat.alert")); for (String msg : message) { player.sendMessage(msg); } } if (Anticheat.getManager().getConfiguration().logConsole()) { for (String msg : message) { Anticheat.getManager().log(msg); } } }
public static void alert(String[] message) { for(Player player : Bukkit.getOnlinePlayers()) { for (String msg : message) { if(player.hasPermission("anticheat.alert")) player.sendMessage(msg); } } if (Anticheat.getManager().getConfiguration().logConsole()) { for (String msg : message) { Anticheat.getManager().log(msg); } } }
diff --git a/src/com/sonyericsson/chkbugreport/plugins/stacktrace/Generator.java b/src/com/sonyericsson/chkbugreport/plugins/stacktrace/Generator.java index 713c28c..db7796d 100644 --- a/src/com/sonyericsson/chkbugreport/plugins/stacktrace/Generator.java +++ b/src/com/sonyericsson/chkbugreport/plugins/stacktrace/Generator.java @@ -1,236 +1,238 @@ /* * Copyright (C) 2011 Sony Ericsson Mobile Communications AB * Copyright (C) 2012 Sony Mobile Communications AB * * This file is part of ChkBugReport. * * ChkBugReport 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) any later version. * * ChkBugReport 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 ChkBugReport. If not, see <http://www.gnu.org/licenses/>. */ package com.sonyericsson.chkbugreport.plugins.stacktrace; import com.sonyericsson.chkbugreport.BugReportModule; import com.sonyericsson.chkbugreport.Module; import com.sonyericsson.chkbugreport.ProcessRecord; import com.sonyericsson.chkbugreport.doc.Anchor; import com.sonyericsson.chkbugreport.doc.Block; import com.sonyericsson.chkbugreport.doc.Chapter; import com.sonyericsson.chkbugreport.doc.DocNode; import com.sonyericsson.chkbugreport.doc.Hint; import com.sonyericsson.chkbugreport.doc.Img; import com.sonyericsson.chkbugreport.doc.Link; import com.sonyericsson.chkbugreport.doc.List; import com.sonyericsson.chkbugreport.doc.Para; import com.sonyericsson.chkbugreport.doc.ProcessLink; import com.sonyericsson.chkbugreport.doc.Span; import com.sonyericsson.chkbugreport.ps.PSRecord; import com.sonyericsson.chkbugreport.util.Util; import java.util.Calendar; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; /* package */ class Generator { public Generator(StackTracePlugin plugin) { } public void generate(Module rep, Processes processes) { BugReportModule br = (BugReportModule)rep; int id = processes.getId(); String chapterName = processes.getName(); // Generate chapter genChapter(br, id, processes, chapterName); } private void genChapter(BugReportModule br, int id, Processes processes, String chapterName) { Chapter main = processes.getChapter(); Calendar tsBr = br.getTimestamp(); Calendar tsSec = Util.parseTimestamp(br, processes.getSectionName()); String diff = Util.formatTimeDiff(tsBr, tsSec, true); diff = (diff == null) ? "" : "; " + diff + ""; new Hint(main).add("Generated from : \"" + processes.getSectionName() + "\" " + diff); // Dump the actuall stack traces for (Process p : processes) { Chapter ch = p.getChapter(); main.addChapter(ch); // Add timestamp String dateTime = p.getDate() + " " + p.getTime(); Calendar tsProc = Util.parseTimestamp(br, dateTime); diff = Util.formatTimeDiff(tsBr, tsProc, true); diff = (diff == null) ? "" : "; " + diff + ""; new Hint(ch).add(dateTime + diff); // Add link from global process record ProcessRecord pr = br.getProcessRecord(p.getPid(), true, true); pr.suggestName(p.getName(), 50); String linkText = "Related stack traces &gt;&gt;&gt;"; if (id == StackTracePlugin.ID_NOW) { linkText = "Current stack trace &gt;&gt;&gt;"; } else if (id == StackTracePlugin.ID_ANR) { linkText = "Stack trace at last ANR &gt;&gt;&gt;"; } else if (id == StackTracePlugin.ID_OLD) { linkText = "Old stack traces &gt;&gt;&gt;"; } new Para(pr).add(new Link(ch.getAnchor(), linkText)); int cnt = p.getCount(); for (int i = 0; i < cnt; i++) { StackTrace stack = p.get(i); Anchor anchorTrace = stack.getAnchor(); DocNode waiting = new DocNode(); int waitOn = stack.getWaitOn(); StackTrace aidlDep = stack.getAidlDependency(); if (waitOn >= 0) { StackTrace stackWaitOn = p.findTid(waitOn); waiting.add(" waiting on "); waiting.add(new Link(stackWaitOn.getAnchor(), "thread-" + waitOn)); } else if (aidlDep != null) { Process aidlDepProc = aidlDep.getProcess(); waiting.add(" waiting on "); waiting.add(new Link(aidlDep.getAnchor(), aidlDepProc.getName() + "/" + aidlDep.getName())); } String sched = parseSched(stack.getProperty("sched")); String nice = parseNice(stack.getProperty("nice")); ch.add(anchorTrace); DocNode st = new Block(ch).addStyle("stacktrace"); DocNode stName = new Block(st).addStyle("stacktrace-name"); new Span(stName).add("-"); new Span(stName).addStyle("stacktrace-name-name").add(stack.getName()); new Span(stName).addStyle("stacktrace-name-info") .add( " (tid=" + stack.getTid() + " pid=" + stack.getProperty("sysTid") + " prio=" + stack.getPrio() + " ") .add(new Img(nice)) .add(new Img(sched)) .add(" state=" + stack.getState()) .add(waiting) .add(")"); DocNode stItems = new Block(st).addStyle("stacktrace-items"); int itemCnt = stack.getCount(); for (int j = 0; j < itemCnt; j++) { StackTraceItem item = stack.get(j); DocNode stItem = new Block(stItems).addStyle("stacktrace-item"); new Span(stItem).addStyle("stacktrace-item-method").addStyle(item.getStyle()).add(item.getMethod()); if (item.getFileName() != null) { new Span(stItem).addStyle("stacktrace-item-file").add(" (" + item.getFileName() + ")"); } } } cnt = p.getUnknownThreadCount(); if (cnt > 0) { DocNode stu = new Block(ch).addStyle("stacktrace-unknown"); new Para(stu).add("Other/unknown threads:"); new Hint(stu).add("These are child processes/threads of this application, but there is no information about the stacktrace of them. They are either native threads, or dalvik threads which haven't existed yet when the stack traces were saved"); List list = new List(List.TYPE_UNORDERED, stu); for (int i = 0; i < cnt; i++) { PSRecord psr = p.getUnknownThread(i); new DocNode(list).add(psr.getName() + "(" + psr.getPid() + ")"); } } } // Detect threads which could be busy Vector<StackTrace> busy = processes.getBusyStackTraces(); if (busy.size() > 0) { // Build list List list = new List(List.TYPE_UNORDERED); for (StackTrace stack : busy) { Process proc = stack.getProcess(); new DocNode(list) .add(new ProcessLink(br, proc.getPid())) .add("/") .add(new Link(stack.getAnchor(), stack.getName())); } // Build comment new Para(main) .add("The following threads seems to be busy:") .add(new Hint().add("NOTE: there might be some more busy threads than these, " + "since this tool has only a few patterns to recognise busy threads. " + "Currently only binder threads and looper based threads are recognised.")) .add(list); } // List all ongoig AIDL calls Vector<StackTrace> aidl = processes.getAIDLCalls(); if (aidl.size() > 0) { // Build list List list = new List(List.TYPE_UNORDERED); for (StackTrace stack : aidl) { StackTrace dep = stack.getAidlDependency(); - new DocNode() - .add(new ProcessLink(br, stack.getPid())) - .add("/" + stack.getName()) + new DocNode(list) + .add(new ProcessLink(br, stack.getProcess().getPid())) + .add("/") + .add(new Link(stack.getAnchor(), stack.getName())) .add(" -&gt; ") - .add(new ProcessLink(br, dep.getPid())) - .add("/" + dep.getName()) + .add(new ProcessLink(br, dep.getProcess().getPid())) + .add("/") + .add(new Link(dep.getAnchor(), dep.getName())) .add(" (" + detectAidlCall(stack) + ")"); } // Build comment new Para(main) .add("The following threads are executing AIDL calls:") .add(list); } } private String detectAidlCall(StackTrace stack) { Pattern p = Pattern.compile("([^.]+)\\$Stub\\$Proxy\\.(.+)"); for (StackTraceItem item : stack) { String method = item.getMethod(); Matcher m = p.matcher(method); if (m.find()) { String interf = m.group(1); String msg = m.group(2); return interf + "." + msg; } } return "could find interface call"; } private String parseSched(String sched) { int ret = PSRecord.PCY_UNKNOWN; if (sched != null) { String fields[] = sched.split("/"); try { int v = Integer.parseInt(fields[0]); switch (v) { case 0: ret = PSRecord.PCY_NORMAL; break; case 1: ret = PSRecord.PCY_FIFO; break; case 3: ret = PSRecord.PCY_BATCH; break; } } catch (Exception e) { /* NOP */ } } return Util.getSchedImg(ret); } private String parseNice(String sNice) { int nice = PSRecord.NICE_UNKNOWN; try { nice = Integer.parseInt(sNice); } catch (Exception e) { /* NOP */ } return Util.getNiceImg(nice); } }
false
true
private void genChapter(BugReportModule br, int id, Processes processes, String chapterName) { Chapter main = processes.getChapter(); Calendar tsBr = br.getTimestamp(); Calendar tsSec = Util.parseTimestamp(br, processes.getSectionName()); String diff = Util.formatTimeDiff(tsBr, tsSec, true); diff = (diff == null) ? "" : "; " + diff + ""; new Hint(main).add("Generated from : \"" + processes.getSectionName() + "\" " + diff); // Dump the actuall stack traces for (Process p : processes) { Chapter ch = p.getChapter(); main.addChapter(ch); // Add timestamp String dateTime = p.getDate() + " " + p.getTime(); Calendar tsProc = Util.parseTimestamp(br, dateTime); diff = Util.formatTimeDiff(tsBr, tsProc, true); diff = (diff == null) ? "" : "; " + diff + ""; new Hint(ch).add(dateTime + diff); // Add link from global process record ProcessRecord pr = br.getProcessRecord(p.getPid(), true, true); pr.suggestName(p.getName(), 50); String linkText = "Related stack traces &gt;&gt;&gt;"; if (id == StackTracePlugin.ID_NOW) { linkText = "Current stack trace &gt;&gt;&gt;"; } else if (id == StackTracePlugin.ID_ANR) { linkText = "Stack trace at last ANR &gt;&gt;&gt;"; } else if (id == StackTracePlugin.ID_OLD) { linkText = "Old stack traces &gt;&gt;&gt;"; } new Para(pr).add(new Link(ch.getAnchor(), linkText)); int cnt = p.getCount(); for (int i = 0; i < cnt; i++) { StackTrace stack = p.get(i); Anchor anchorTrace = stack.getAnchor(); DocNode waiting = new DocNode(); int waitOn = stack.getWaitOn(); StackTrace aidlDep = stack.getAidlDependency(); if (waitOn >= 0) { StackTrace stackWaitOn = p.findTid(waitOn); waiting.add(" waiting on "); waiting.add(new Link(stackWaitOn.getAnchor(), "thread-" + waitOn)); } else if (aidlDep != null) { Process aidlDepProc = aidlDep.getProcess(); waiting.add(" waiting on "); waiting.add(new Link(aidlDep.getAnchor(), aidlDepProc.getName() + "/" + aidlDep.getName())); } String sched = parseSched(stack.getProperty("sched")); String nice = parseNice(stack.getProperty("nice")); ch.add(anchorTrace); DocNode st = new Block(ch).addStyle("stacktrace"); DocNode stName = new Block(st).addStyle("stacktrace-name"); new Span(stName).add("-"); new Span(stName).addStyle("stacktrace-name-name").add(stack.getName()); new Span(stName).addStyle("stacktrace-name-info") .add( " (tid=" + stack.getTid() + " pid=" + stack.getProperty("sysTid") + " prio=" + stack.getPrio() + " ") .add(new Img(nice)) .add(new Img(sched)) .add(" state=" + stack.getState()) .add(waiting) .add(")"); DocNode stItems = new Block(st).addStyle("stacktrace-items"); int itemCnt = stack.getCount(); for (int j = 0; j < itemCnt; j++) { StackTraceItem item = stack.get(j); DocNode stItem = new Block(stItems).addStyle("stacktrace-item"); new Span(stItem).addStyle("stacktrace-item-method").addStyle(item.getStyle()).add(item.getMethod()); if (item.getFileName() != null) { new Span(stItem).addStyle("stacktrace-item-file").add(" (" + item.getFileName() + ")"); } } } cnt = p.getUnknownThreadCount(); if (cnt > 0) { DocNode stu = new Block(ch).addStyle("stacktrace-unknown"); new Para(stu).add("Other/unknown threads:"); new Hint(stu).add("These are child processes/threads of this application, but there is no information about the stacktrace of them. They are either native threads, or dalvik threads which haven't existed yet when the stack traces were saved"); List list = new List(List.TYPE_UNORDERED, stu); for (int i = 0; i < cnt; i++) { PSRecord psr = p.getUnknownThread(i); new DocNode(list).add(psr.getName() + "(" + psr.getPid() + ")"); } } } // Detect threads which could be busy Vector<StackTrace> busy = processes.getBusyStackTraces(); if (busy.size() > 0) { // Build list List list = new List(List.TYPE_UNORDERED); for (StackTrace stack : busy) { Process proc = stack.getProcess(); new DocNode(list) .add(new ProcessLink(br, proc.getPid())) .add("/") .add(new Link(stack.getAnchor(), stack.getName())); } // Build comment new Para(main) .add("The following threads seems to be busy:") .add(new Hint().add("NOTE: there might be some more busy threads than these, " + "since this tool has only a few patterns to recognise busy threads. " + "Currently only binder threads and looper based threads are recognised.")) .add(list); } // List all ongoig AIDL calls Vector<StackTrace> aidl = processes.getAIDLCalls(); if (aidl.size() > 0) { // Build list List list = new List(List.TYPE_UNORDERED); for (StackTrace stack : aidl) { StackTrace dep = stack.getAidlDependency(); new DocNode() .add(new ProcessLink(br, stack.getPid())) .add("/" + stack.getName()) .add(" -&gt; ") .add(new ProcessLink(br, dep.getPid())) .add("/" + dep.getName()) .add(" (" + detectAidlCall(stack) + ")"); } // Build comment new Para(main) .add("The following threads are executing AIDL calls:") .add(list); } }
private void genChapter(BugReportModule br, int id, Processes processes, String chapterName) { Chapter main = processes.getChapter(); Calendar tsBr = br.getTimestamp(); Calendar tsSec = Util.parseTimestamp(br, processes.getSectionName()); String diff = Util.formatTimeDiff(tsBr, tsSec, true); diff = (diff == null) ? "" : "; " + diff + ""; new Hint(main).add("Generated from : \"" + processes.getSectionName() + "\" " + diff); // Dump the actuall stack traces for (Process p : processes) { Chapter ch = p.getChapter(); main.addChapter(ch); // Add timestamp String dateTime = p.getDate() + " " + p.getTime(); Calendar tsProc = Util.parseTimestamp(br, dateTime); diff = Util.formatTimeDiff(tsBr, tsProc, true); diff = (diff == null) ? "" : "; " + diff + ""; new Hint(ch).add(dateTime + diff); // Add link from global process record ProcessRecord pr = br.getProcessRecord(p.getPid(), true, true); pr.suggestName(p.getName(), 50); String linkText = "Related stack traces &gt;&gt;&gt;"; if (id == StackTracePlugin.ID_NOW) { linkText = "Current stack trace &gt;&gt;&gt;"; } else if (id == StackTracePlugin.ID_ANR) { linkText = "Stack trace at last ANR &gt;&gt;&gt;"; } else if (id == StackTracePlugin.ID_OLD) { linkText = "Old stack traces &gt;&gt;&gt;"; } new Para(pr).add(new Link(ch.getAnchor(), linkText)); int cnt = p.getCount(); for (int i = 0; i < cnt; i++) { StackTrace stack = p.get(i); Anchor anchorTrace = stack.getAnchor(); DocNode waiting = new DocNode(); int waitOn = stack.getWaitOn(); StackTrace aidlDep = stack.getAidlDependency(); if (waitOn >= 0) { StackTrace stackWaitOn = p.findTid(waitOn); waiting.add(" waiting on "); waiting.add(new Link(stackWaitOn.getAnchor(), "thread-" + waitOn)); } else if (aidlDep != null) { Process aidlDepProc = aidlDep.getProcess(); waiting.add(" waiting on "); waiting.add(new Link(aidlDep.getAnchor(), aidlDepProc.getName() + "/" + aidlDep.getName())); } String sched = parseSched(stack.getProperty("sched")); String nice = parseNice(stack.getProperty("nice")); ch.add(anchorTrace); DocNode st = new Block(ch).addStyle("stacktrace"); DocNode stName = new Block(st).addStyle("stacktrace-name"); new Span(stName).add("-"); new Span(stName).addStyle("stacktrace-name-name").add(stack.getName()); new Span(stName).addStyle("stacktrace-name-info") .add( " (tid=" + stack.getTid() + " pid=" + stack.getProperty("sysTid") + " prio=" + stack.getPrio() + " ") .add(new Img(nice)) .add(new Img(sched)) .add(" state=" + stack.getState()) .add(waiting) .add(")"); DocNode stItems = new Block(st).addStyle("stacktrace-items"); int itemCnt = stack.getCount(); for (int j = 0; j < itemCnt; j++) { StackTraceItem item = stack.get(j); DocNode stItem = new Block(stItems).addStyle("stacktrace-item"); new Span(stItem).addStyle("stacktrace-item-method").addStyle(item.getStyle()).add(item.getMethod()); if (item.getFileName() != null) { new Span(stItem).addStyle("stacktrace-item-file").add(" (" + item.getFileName() + ")"); } } } cnt = p.getUnknownThreadCount(); if (cnt > 0) { DocNode stu = new Block(ch).addStyle("stacktrace-unknown"); new Para(stu).add("Other/unknown threads:"); new Hint(stu).add("These are child processes/threads of this application, but there is no information about the stacktrace of them. They are either native threads, or dalvik threads which haven't existed yet when the stack traces were saved"); List list = new List(List.TYPE_UNORDERED, stu); for (int i = 0; i < cnt; i++) { PSRecord psr = p.getUnknownThread(i); new DocNode(list).add(psr.getName() + "(" + psr.getPid() + ")"); } } } // Detect threads which could be busy Vector<StackTrace> busy = processes.getBusyStackTraces(); if (busy.size() > 0) { // Build list List list = new List(List.TYPE_UNORDERED); for (StackTrace stack : busy) { Process proc = stack.getProcess(); new DocNode(list) .add(new ProcessLink(br, proc.getPid())) .add("/") .add(new Link(stack.getAnchor(), stack.getName())); } // Build comment new Para(main) .add("The following threads seems to be busy:") .add(new Hint().add("NOTE: there might be some more busy threads than these, " + "since this tool has only a few patterns to recognise busy threads. " + "Currently only binder threads and looper based threads are recognised.")) .add(list); } // List all ongoig AIDL calls Vector<StackTrace> aidl = processes.getAIDLCalls(); if (aidl.size() > 0) { // Build list List list = new List(List.TYPE_UNORDERED); for (StackTrace stack : aidl) { StackTrace dep = stack.getAidlDependency(); new DocNode(list) .add(new ProcessLink(br, stack.getProcess().getPid())) .add("/") .add(new Link(stack.getAnchor(), stack.getName())) .add(" -&gt; ") .add(new ProcessLink(br, dep.getProcess().getPid())) .add("/") .add(new Link(dep.getAnchor(), dep.getName())) .add(" (" + detectAidlCall(stack) + ")"); } // Build comment new Para(main) .add("The following threads are executing AIDL calls:") .add(list); } }
diff --git a/deeva/processor/PrimitiveValue.java b/deeva/processor/PrimitiveValue.java index 85ad9af..5c99c9e 100644 --- a/deeva/processor/PrimitiveValue.java +++ b/deeva/processor/PrimitiveValue.java @@ -1,41 +1,41 @@ package deeva.processor; //import com.google.gson.Gson; //import com.google.gson.GsonBuilder; import com.sun.jdi.*; /** * Plain old Java Object containing data we want to eventually serialize. */ public class PrimitiveValue extends JVMValue { private final Object value; public PrimitiveValue(String type, String value) { super(type); this.value = value; } public PrimitiveValue(String type, Value variableValue) { super(type); - if (variableValue instanceof IntegerType) { + if (variableValue instanceof IntegerValue) { this.value = ((IntegerValue) variableValue).value(); - } else if (variableValue instanceof BooleanType) { + } else if (variableValue instanceof BooleanValue) { this.value = ((BooleanValue) variableValue).value(); - } else if (variableValue instanceof ByteType) { + } else if (variableValue instanceof ByteValue) { this.value = ((ByteValue) variableValue).value(); - } else if (variableValue instanceof CharType) { + } else if (variableValue instanceof CharValue) { this.value = ((CharValue) variableValue).value(); - } else if (variableValue instanceof DoubleType) { + } else if (variableValue instanceof DoubleValue) { this.value = ((DoubleValue) variableValue).value(); - } else if (variableValue instanceof FloatType) { + } else if (variableValue instanceof FloatValue) { this.value = ((FloatValue) variableValue).value(); - } else if (variableValue instanceof LongType) { + } else if (variableValue instanceof LongValue) { this.value = ((LongValue) variableValue).value(); - } else if (variableValue instanceof ShortType) { + } else if (variableValue instanceof ShortValue) { this.value = ((ShortValue) variableValue).value(); } else { this.value = "void"; } } }
false
true
public PrimitiveValue(String type, Value variableValue) { super(type); if (variableValue instanceof IntegerType) { this.value = ((IntegerValue) variableValue).value(); } else if (variableValue instanceof BooleanType) { this.value = ((BooleanValue) variableValue).value(); } else if (variableValue instanceof ByteType) { this.value = ((ByteValue) variableValue).value(); } else if (variableValue instanceof CharType) { this.value = ((CharValue) variableValue).value(); } else if (variableValue instanceof DoubleType) { this.value = ((DoubleValue) variableValue).value(); } else if (variableValue instanceof FloatType) { this.value = ((FloatValue) variableValue).value(); } else if (variableValue instanceof LongType) { this.value = ((LongValue) variableValue).value(); } else if (variableValue instanceof ShortType) { this.value = ((ShortValue) variableValue).value(); } else { this.value = "void"; } }
public PrimitiveValue(String type, Value variableValue) { super(type); if (variableValue instanceof IntegerValue) { this.value = ((IntegerValue) variableValue).value(); } else if (variableValue instanceof BooleanValue) { this.value = ((BooleanValue) variableValue).value(); } else if (variableValue instanceof ByteValue) { this.value = ((ByteValue) variableValue).value(); } else if (variableValue instanceof CharValue) { this.value = ((CharValue) variableValue).value(); } else if (variableValue instanceof DoubleValue) { this.value = ((DoubleValue) variableValue).value(); } else if (variableValue instanceof FloatValue) { this.value = ((FloatValue) variableValue).value(); } else if (variableValue instanceof LongValue) { this.value = ((LongValue) variableValue).value(); } else if (variableValue instanceof ShortValue) { this.value = ((ShortValue) variableValue).value(); } else { this.value = "void"; } }
diff --git a/src/Extra/org/objectweb/proactive/extra/gcmdeployment/GCMDeployment/GroupParsers/GroupRSHParser.java b/src/Extra/org/objectweb/proactive/extra/gcmdeployment/GCMDeployment/GroupParsers/GroupRSHParser.java index b93f97242..1b0a109c9 100644 --- a/src/Extra/org/objectweb/proactive/extra/gcmdeployment/GCMDeployment/GroupParsers/GroupRSHParser.java +++ b/src/Extra/org/objectweb/proactive/extra/gcmdeployment/GCMDeployment/GroupParsers/GroupRSHParser.java @@ -1,66 +1,66 @@ /* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library 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 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 * General Public License for more details. * * You should have received a copy of the GNU 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 * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.extra.gcmdeployment.GCMDeployment.GroupParsers; import javax.xml.xpath.XPath; import org.objectweb.proactive.extra.gcmdeployment.GCMParserHelper; import org.objectweb.proactive.extra.gcmdeployment.process.group.AbstractGroup; import org.objectweb.proactive.extra.gcmdeployment.process.group.GroupRSH; import org.objectweb.proactive.extra.gcmdeployment.process.group.GroupSSH; import org.w3c.dom.Node; public class GroupRSHParser extends AbstractGroupParser { private static final String ATTR_HOST_LIST = "hostList"; static final String NODE_NAME = "rshGroup"; @Override public AbstractGroup parseGroupNode(Node groupNode, XPath xpath) { - GroupSSH groupSSH = (GroupSSH) super.parseGroupNode(groupNode, xpath); + GroupRSH groupRSH = (GroupRSH) super.parseGroupNode(groupNode, xpath); // Mandatory attributes String hostList = GCMParserHelper.getAttributeValue(groupNode, ATTR_HOST_LIST); - groupSSH.setHostList(hostList); + groupRSH.setHostList(hostList); - return groupSSH; + return groupRSH; } @Override public AbstractGroup createGroup() { return new GroupRSH(); } @Override public String getNodeName() { return NODE_NAME; } }
false
true
public AbstractGroup parseGroupNode(Node groupNode, XPath xpath) { GroupSSH groupSSH = (GroupSSH) super.parseGroupNode(groupNode, xpath); // Mandatory attributes String hostList = GCMParserHelper.getAttributeValue(groupNode, ATTR_HOST_LIST); groupSSH.setHostList(hostList); return groupSSH; }
public AbstractGroup parseGroupNode(Node groupNode, XPath xpath) { GroupRSH groupRSH = (GroupRSH) super.parseGroupNode(groupNode, xpath); // Mandatory attributes String hostList = GCMParserHelper.getAttributeValue(groupNode, ATTR_HOST_LIST); groupRSH.setHostList(hostList); return groupRSH; }
diff --git a/src/net/wcjj/scharing/DailyScheduleListActivity.java b/src/net/wcjj/scharing/DailyScheduleListActivity.java index de06f08..c241cbd 100755 --- a/src/net/wcjj/scharing/DailyScheduleListActivity.java +++ b/src/net/wcjj/scharing/DailyScheduleListActivity.java @@ -1,133 +1,134 @@ /** * Scharing - Allows you to set a ring, vibrate and silence shedule for your android device. * Copyright (C) 2009 Wilby C. Jackson Jr. * * 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 2 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, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * Contact: jacksw02-at-gmail-dot-com */ package net.wcjj.scharing; import java.io.IOException; import android.app.ListActivity; import android.os.Bundle; import android.text.format.Time; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; public class DailyScheduleListActivity extends ListActivity { public static int WEEK_DAY; private DailyScheduleAdapter mAdapter; private final String TAG = "Scharing_DailyScheduleListActivity"; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.lv_container); this.setTitle(Utilities.DAYS_OF_WEEK_TEXT[WEEK_DAY]); // mSa = new SimpleAdapter(this, Service.getRingSchedule() // .toSimpleAdapterMap(DailyScheduleListActivity.WEEK_DAY), // R.layout.daily_schedule_list_row, new String[] { // Schedule.SCHEDULE_DOW, Schedule.SCHEDULED_TIME, // Schedule.RINGER_MODE }, new int[] { R.id.txtId, // R.id.txtTime, R.id.txtRingMode }); Schedule schedule = Service.getRingSchedule(); mAdapter = new DailyScheduleAdapter(this, schedule.getDay(WEEK_DAY)); setListAdapter(mAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.daily_schedule_lv_menu, menu); return true; } public void mBtnDelete_Click() { Schedule ringSchedule = Service.getRingSchedule(); final int CHECKBOX_INDEX = 3; final int TIME_TEXTBOX_INDEX = 1; final int NBR_VIEWS_IN_ROW = 4; LinearLayout row = null; Time time = null; CheckBox cb = null; ListView lv = getListView(); int rowCount = lv.getCount(); int childCount = -1; String strTime; String[] hourMins; // iterate over the views in the ListView // and remove items from the schedule that // have been checked by the user // this also removes the selected times from Services // schedule object for (int i = 0; i < rowCount; i++) { row = (LinearLayout) lv.getChildAt(i); if (row != null) { childCount = row.getChildCount(); if (childCount == NBR_VIEWS_IN_ROW) { cb = (CheckBox) row.getChildAt(CHECKBOX_INDEX); if (cb.isChecked()) { strTime = ((TextView) row.getChildAt(TIME_TEXTBOX_INDEX)) .getText().toString(); hourMins = strTime.split(":"); time = Utilities.normalizeToScharingTime( Integer.parseInt(hourMins[0]), Integer.parseInt(hourMins[1]) ); ringSchedule.delRingSchedule(WEEK_DAY, - time.toMillis(true)); - row.setVisibility(View.GONE); + time.toMillis(true)); + mAdapter.notifyDataSetChanged(); + //row.setVisibility(View.GONE); } } } } // Save the changes to disk try { ringSchedule.saveSchedule(this); } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.mBtnDelete: mBtnDelete_Click(); return true; } return false; } }
true
true
public void mBtnDelete_Click() { Schedule ringSchedule = Service.getRingSchedule(); final int CHECKBOX_INDEX = 3; final int TIME_TEXTBOX_INDEX = 1; final int NBR_VIEWS_IN_ROW = 4; LinearLayout row = null; Time time = null; CheckBox cb = null; ListView lv = getListView(); int rowCount = lv.getCount(); int childCount = -1; String strTime; String[] hourMins; // iterate over the views in the ListView // and remove items from the schedule that // have been checked by the user // this also removes the selected times from Services // schedule object for (int i = 0; i < rowCount; i++) { row = (LinearLayout) lv.getChildAt(i); if (row != null) { childCount = row.getChildCount(); if (childCount == NBR_VIEWS_IN_ROW) { cb = (CheckBox) row.getChildAt(CHECKBOX_INDEX); if (cb.isChecked()) { strTime = ((TextView) row.getChildAt(TIME_TEXTBOX_INDEX)) .getText().toString(); hourMins = strTime.split(":"); time = Utilities.normalizeToScharingTime( Integer.parseInt(hourMins[0]), Integer.parseInt(hourMins[1]) ); ringSchedule.delRingSchedule(WEEK_DAY, time.toMillis(true)); row.setVisibility(View.GONE); } } } } // Save the changes to disk try { ringSchedule.saveSchedule(this); } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); } }
public void mBtnDelete_Click() { Schedule ringSchedule = Service.getRingSchedule(); final int CHECKBOX_INDEX = 3; final int TIME_TEXTBOX_INDEX = 1; final int NBR_VIEWS_IN_ROW = 4; LinearLayout row = null; Time time = null; CheckBox cb = null; ListView lv = getListView(); int rowCount = lv.getCount(); int childCount = -1; String strTime; String[] hourMins; // iterate over the views in the ListView // and remove items from the schedule that // have been checked by the user // this also removes the selected times from Services // schedule object for (int i = 0; i < rowCount; i++) { row = (LinearLayout) lv.getChildAt(i); if (row != null) { childCount = row.getChildCount(); if (childCount == NBR_VIEWS_IN_ROW) { cb = (CheckBox) row.getChildAt(CHECKBOX_INDEX); if (cb.isChecked()) { strTime = ((TextView) row.getChildAt(TIME_TEXTBOX_INDEX)) .getText().toString(); hourMins = strTime.split(":"); time = Utilities.normalizeToScharingTime( Integer.parseInt(hourMins[0]), Integer.parseInt(hourMins[1]) ); ringSchedule.delRingSchedule(WEEK_DAY, time.toMillis(true)); mAdapter.notifyDataSetChanged(); //row.setVisibility(View.GONE); } } } } // Save the changes to disk try { ringSchedule.saveSchedule(this); } catch (IOException e) { Log.e(TAG, Log.getStackTraceString(e)); } }
diff --git a/src/com/group7/project/Building.java b/src/com/group7/project/Building.java index 17cb05d..5acf31b 100644 --- a/src/com/group7/project/Building.java +++ b/src/com/group7/project/Building.java @@ -1,43 +1,43 @@ package com.group7.project; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; //TODO: Finish off this object. We need a way to keep track of what the building contains. // Boolean values are not at all the best way to do this public class Building { String name; LatLngBounds bounds; //GeoPoint centrePoint; public Building(String name, LatLngBounds bounds) { this.name = name; this.bounds = bounds; } public LatLngBounds getBounds() { return bounds; } public String getName() { return name; } public LatLng getCenter() { double n = bounds.northeast.latitude; - double e = bounds.northeast.longitude; - double s = bounds.southwest.latitude; - double w = bounds.southwest.longitude; + double e = bounds.northeast.longitude; + double s = bounds.southwest.latitude; + double w = bounds.southwest.longitude; - double lat = ((n + s) / 2.0); - double lon = ((e + w) / 2.0); + double lat = ((n + s) / 2.0); + double lon = ((e + w) / 2.0); - return new LatLng(lat, lon); + return new LatLng(lat, lon); } }
false
true
public LatLng getCenter() { double n = bounds.northeast.latitude; double e = bounds.northeast.longitude; double s = bounds.southwest.latitude; double w = bounds.southwest.longitude; double lat = ((n + s) / 2.0); double lon = ((e + w) / 2.0); return new LatLng(lat, lon); }
public LatLng getCenter() { double n = bounds.northeast.latitude; double e = bounds.northeast.longitude; double s = bounds.southwest.latitude; double w = bounds.southwest.longitude; double lat = ((n + s) / 2.0); double lon = ((e + w) / 2.0); return new LatLng(lat, lon); }
diff --git a/geoserver/community/web2/core/src/main/java/org/geoserver/web/GeoServerBasePage.java b/geoserver/community/web2/core/src/main/java/org/geoserver/web/GeoServerBasePage.java index 31eb33c62f..6496a07ca7 100644 --- a/geoserver/community/web2/core/src/main/java/org/geoserver/web/GeoServerBasePage.java +++ b/geoserver/community/web2/core/src/main/java/org/geoserver/web/GeoServerBasePage.java @@ -1,186 +1,186 @@ /* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the GPL 2.0 license, available at the root * application directory. */ package org.geoserver.web; import java.util.List; import org.apache.wicket.Application; import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.ResourceReference; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.markup.html.AjaxFallbackLink; import org.apache.wicket.ajax.markup.html.form.AjaxFallbackButton; import org.apache.wicket.extensions.breadcrumb.BreadCrumbBar; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.StatelessForm; import org.apache.wicket.markup.html.form.TextField; import org.apache.wicket.markup.html.form.PasswordTextField; import org.apache.wicket.markup.html.image.Image; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; import org.apache.wicket.markup.html.list.ListView; import org.apache.wicket.model.StringResourceModel; import org.apache.wicket.model.CompoundPropertyModel; import org.geoserver.web.acegi.GeoServerSession; import org.geoserver.catalog.Catalog; import org.geoserver.config.GeoServer; import org.geoserver.web.admin.ServerAdminPage; import org.geoserver.web.services.ServicePageInfo; /** * Base class for web pages in GeoServer web application. * <ul> * <li>The basic layout</li> * <li>An OO infrastructure for common elements location</li> * <li>An infrastructure for locating subpages in the Spring context and * creating links</li> * </ul> * * TODO: breadcrumb automated cration. This can be done by using a list of * {@link BookmarkablePageInfo} instances that needs to be passed to each page, * a custom PageLink subclass that provides that information, and some code * coming from {@link BreadCrumbBar}. <br> * See also this discussion on the wicket users mailing list: * http://www.nabble.com/Bread-crumbs-based-on-pages%2C-not-panels--tf2244730.html#a6225855 * * @author Andrea Aaime, The Open Planning Project * @author Justin Deoliveira, The Open Planning Project */ public class GeoServerBasePage extends WebPage { @SuppressWarnings("serial") public GeoServerBasePage() { // login form Form loginForm = new SignInForm("loginform"); add(loginForm); loginForm.setVisible(GeoServerSession.get().getAuthentication() == null); Form logoutForm = new StatelessForm("logoutform"){ @Override public void onSubmit(){ GeoServerSession.get().signout(); setResponsePage(GeoServerHomePage.class); } }; logoutForm.setVisible(GeoServerSession.get().getAuthentication() != null); add(logoutForm); logoutForm.add(new Label("username", GeoServerSession.get().getAuthentication() == null ? "Nobody" : "Some guy")); - // welcome page link - add( new BookmarkablePageLink( "welcome", GeoServerHomePage.class ) - .add( new Label( "label", new StringResourceModel( "welcome", (Component)null, null ) ) ) ); + // home page link + add( new BookmarkablePageLink( "home", GeoServerHomePage.class ) + .add( new Label( "label", new StringResourceModel( "home", (Component)null, null ) ) ) ); // server admin link add( new BookmarkablePageLink( "admin.server", ServerAdminPage.class ) .add( new Label( "label", new StringResourceModel( "server", (Component)null, null ) ) ) ); // list of services to administer List<ServicePageInfo> pages = getGeoServerApplication().getBeansOfType( ServicePageInfo.class); ListView services = new ListView("admin.services", pages) { protected void populateItem(ListItem item) { ServicePageInfo page = (ServicePageInfo) item.getModelObject(); //add a link BookmarkablePageLink link = new BookmarkablePageLink("admin.service", page.getComponentClass()); link.add(new Image( "serviceIcon", new ResourceReference( page.getComponentClass(), page.getIcon() ) ) ); link.add(new Label("serviceLabel", new StringResourceModel( page.getTitleKey(), (Component) null, null ) )); link.add(new AttributeModifier( "title", new StringResourceModel( page.getDescriptionKey(), (Component) null, null ) ) ); item.add(link); } }; add( services ); List<ShortcutPageInfo> links = getGeoServerApplication().getBeansOfType(ShortcutPageInfo.class); ListView shortcuts = new ListView("shortcuts", links){ protected void populateItem(ListItem item) { ShortcutPageInfo info = (ShortcutPageInfo) item.getModelObject(); BookmarkablePageLink link = new BookmarkablePageLink("link", info.getComponentClass()); item.add(link); link.add(new Label("label", new StringResourceModel(info.getTitleKey(), (Component) null, null))); } }; add(shortcuts); // dev buttons WebMarkupContainer devButtons = new WebMarkupContainer("devButtons"); add(devButtons); devButtons.add(new AjaxFallbackLink("clearCache"){ @Override public void onClick(AjaxRequestTarget target) { getGeoServerApplication().clearWicketCaches(); } }); devButtons.setVisible(Application.DEVELOPMENT.equalsIgnoreCase( getApplication().getConfigurationType())); } /** * Returns the application instance. */ protected GeoServerApplication getGeoServerApplication() { return (GeoServerApplication) getApplication(); } /** * Convenience method for pages to get access to the geoserver * configuration. */ protected GeoServer getGeoServer() { return getGeoServerApplication().getGeoServer(); } /** * Convenience method for pages to get access to the catalog. */ protected Catalog getCatalog() { return getGeoServerApplication().getCatalog(); } private static class SignInForm extends StatelessForm { private String password; private String username; public SignInForm(final String id){ super(id); setModel(new CompoundPropertyModel(this)); add(new TextField("username")); add(new PasswordTextField("password")); } @Override public final void onSubmit(){ if (signIn(username, password)){ if (!continueToOriginalDestination()) { setResponsePage(getApplication().getHomePage()); } } else { error("Unknown username/password"); } } private final boolean signIn(String username, String password) { return GeoServerSession.get().authenticate(username, password); } } }
true
true
public GeoServerBasePage() { // login form Form loginForm = new SignInForm("loginform"); add(loginForm); loginForm.setVisible(GeoServerSession.get().getAuthentication() == null); Form logoutForm = new StatelessForm("logoutform"){ @Override public void onSubmit(){ GeoServerSession.get().signout(); setResponsePage(GeoServerHomePage.class); } }; logoutForm.setVisible(GeoServerSession.get().getAuthentication() != null); add(logoutForm); logoutForm.add(new Label("username", GeoServerSession.get().getAuthentication() == null ? "Nobody" : "Some guy")); // welcome page link add( new BookmarkablePageLink( "welcome", GeoServerHomePage.class ) .add( new Label( "label", new StringResourceModel( "welcome", (Component)null, null ) ) ) ); // server admin link add( new BookmarkablePageLink( "admin.server", ServerAdminPage.class ) .add( new Label( "label", new StringResourceModel( "server", (Component)null, null ) ) ) ); // list of services to administer List<ServicePageInfo> pages = getGeoServerApplication().getBeansOfType( ServicePageInfo.class); ListView services = new ListView("admin.services", pages) { protected void populateItem(ListItem item) { ServicePageInfo page = (ServicePageInfo) item.getModelObject(); //add a link BookmarkablePageLink link = new BookmarkablePageLink("admin.service", page.getComponentClass()); link.add(new Image( "serviceIcon", new ResourceReference( page.getComponentClass(), page.getIcon() ) ) ); link.add(new Label("serviceLabel", new StringResourceModel( page.getTitleKey(), (Component) null, null ) )); link.add(new AttributeModifier( "title", new StringResourceModel( page.getDescriptionKey(), (Component) null, null ) ) ); item.add(link); } }; add( services ); List<ShortcutPageInfo> links = getGeoServerApplication().getBeansOfType(ShortcutPageInfo.class); ListView shortcuts = new ListView("shortcuts", links){ protected void populateItem(ListItem item) { ShortcutPageInfo info = (ShortcutPageInfo) item.getModelObject(); BookmarkablePageLink link = new BookmarkablePageLink("link", info.getComponentClass()); item.add(link); link.add(new Label("label", new StringResourceModel(info.getTitleKey(), (Component) null, null))); } }; add(shortcuts); // dev buttons WebMarkupContainer devButtons = new WebMarkupContainer("devButtons"); add(devButtons); devButtons.add(new AjaxFallbackLink("clearCache"){ @Override public void onClick(AjaxRequestTarget target) { getGeoServerApplication().clearWicketCaches(); } }); devButtons.setVisible(Application.DEVELOPMENT.equalsIgnoreCase( getApplication().getConfigurationType())); }
public GeoServerBasePage() { // login form Form loginForm = new SignInForm("loginform"); add(loginForm); loginForm.setVisible(GeoServerSession.get().getAuthentication() == null); Form logoutForm = new StatelessForm("logoutform"){ @Override public void onSubmit(){ GeoServerSession.get().signout(); setResponsePage(GeoServerHomePage.class); } }; logoutForm.setVisible(GeoServerSession.get().getAuthentication() != null); add(logoutForm); logoutForm.add(new Label("username", GeoServerSession.get().getAuthentication() == null ? "Nobody" : "Some guy")); // home page link add( new BookmarkablePageLink( "home", GeoServerHomePage.class ) .add( new Label( "label", new StringResourceModel( "home", (Component)null, null ) ) ) ); // server admin link add( new BookmarkablePageLink( "admin.server", ServerAdminPage.class ) .add( new Label( "label", new StringResourceModel( "server", (Component)null, null ) ) ) ); // list of services to administer List<ServicePageInfo> pages = getGeoServerApplication().getBeansOfType( ServicePageInfo.class); ListView services = new ListView("admin.services", pages) { protected void populateItem(ListItem item) { ServicePageInfo page = (ServicePageInfo) item.getModelObject(); //add a link BookmarkablePageLink link = new BookmarkablePageLink("admin.service", page.getComponentClass()); link.add(new Image( "serviceIcon", new ResourceReference( page.getComponentClass(), page.getIcon() ) ) ); link.add(new Label("serviceLabel", new StringResourceModel( page.getTitleKey(), (Component) null, null ) )); link.add(new AttributeModifier( "title", new StringResourceModel( page.getDescriptionKey(), (Component) null, null ) ) ); item.add(link); } }; add( services ); List<ShortcutPageInfo> links = getGeoServerApplication().getBeansOfType(ShortcutPageInfo.class); ListView shortcuts = new ListView("shortcuts", links){ protected void populateItem(ListItem item) { ShortcutPageInfo info = (ShortcutPageInfo) item.getModelObject(); BookmarkablePageLink link = new BookmarkablePageLink("link", info.getComponentClass()); item.add(link); link.add(new Label("label", new StringResourceModel(info.getTitleKey(), (Component) null, null))); } }; add(shortcuts); // dev buttons WebMarkupContainer devButtons = new WebMarkupContainer("devButtons"); add(devButtons); devButtons.add(new AjaxFallbackLink("clearCache"){ @Override public void onClick(AjaxRequestTarget target) { getGeoServerApplication().clearWicketCaches(); } }); devButtons.setVisible(Application.DEVELOPMENT.equalsIgnoreCase( getApplication().getConfigurationType())); }
diff --git a/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationItem.java b/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationItem.java index 7c005694..e0431f05 100644 --- a/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationItem.java +++ b/SWADroid/src/es/ugr/swad/swadroid/modules/notifications/NotificationItem.java @@ -1,169 +1,169 @@ /* * This file is part of SWADroid. * * Copyright (C) 2010 Juan Miguel Boyero Corral <[email protected]> * * SWADroid 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. * * SWADroid 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 SWADroid. If not, see <http://www.gnu.org/licenses/>. */ package es.ugr.swad.swadroid.modules.notifications; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.ImageView; import android.widget.TextView; import es.ugr.swad.swadroid.Constants; import es.ugr.swad.swadroid.R; import es.ugr.swad.swadroid.gui.MenuActivity; import es.ugr.swad.swadroid.modules.Messages; import es.ugr.swad.swadroid.utils.DownloadImageTask; import es.ugr.swad.swadroid.utils.Utils; /** * Webview activity for showing marks * * @author Juan Miguel Boyero Corral <[email protected]> */ public class NotificationItem extends MenuActivity { /** * NotificationsItem tag name for Logcat */ private static final String TAG = Constants.APP_TAG + " Notificationsitem"; private Long notifCode; private Long eventCode; private String sender; private String userPhoto; private String course; private String summary; private String content; private String date; private String time; private boolean seenLocal; @Override protected void onCreate(Bundle savedInstanceState) { TextView senderTextView, courseTextView, summaryTextView, dateTextView, timeTextView; ImageView userPhotoView; WebView webview; Intent activity; String type = this.getIntent().getStringExtra("notificationType"); super.onCreate(savedInstanceState); setContentView(R.layout.single_notification_view); - getSupportActionBar().setIcon(R.drawable.notif_black); + getSupportActionBar().setIcon(R.drawable.notif); senderTextView = (TextView) this.findViewById(R.id.senderNameText); courseTextView = (TextView) this.findViewById(R.id.courseNameText); summaryTextView = (TextView) this.findViewById(R.id.summaryText); userPhotoView = (ImageView) this.findViewById(R.id.notifUserPhoto); webview = (WebView) this.findViewById(R.id.contentWebView); dateTextView = (TextView) this.findViewById(R.id.notifDate); timeTextView = (TextView) this.findViewById(R.id.notifTime); notifCode = Long.valueOf(this.getIntent().getStringExtra("notifCode")); eventCode = Long.valueOf(this.getIntent().getStringExtra("eventCode")); sender = this.getIntent().getStringExtra("sender"); userPhoto = this.getIntent().getStringExtra("userPhoto"); course = this.getIntent().getStringExtra("course"); summary = this.getIntent().getStringExtra("summary"); content = this.getIntent().getStringExtra("content"); date = this.getIntent().getStringExtra("date"); time = this.getIntent().getStringExtra("time"); seenLocal = Utils.parseStringBool(this.getIntent().getStringExtra("seenLocal")); senderTextView.setText(sender); courseTextView.setText(course); summaryTextView.setText(summary); dateTextView.setText(date); timeTextView.setText(time); //If the user photo exists and is public, download and show it if (Utils.connectionAvailable(this) && (userPhoto != null) && !userPhoto.equals("") && !userPhoto.equals(Constants.NULL_VALUE)) { //userPhotoView.setImageURI(Uri.parse(userPhoto)); new DownloadImageTask(userPhotoView).execute(userPhoto); } else { Log.d("NotificationItem", "No connection or no photo " + userPhoto); } content = Utils.fixLinks(content); if (content.startsWith("<![CDATA[")) { content = content.substring(9, content.length() - 3); } webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); webview.loadDataWithBaseURL("", content, "text/html", "utf-8", ""); //Set notification as seen locally dbHelper.updateNotification(notifCode, "seenLocal", Utils.parseBoolString(true)); //Sends "seen notifications" info to the server if there is a connection available if(!seenLocal) { if(Utils.connectionAvailable(this)) { activity = new Intent(this, NotificationsMarkAllAsRead.class); activity.putExtra("seenNotifCodes", String.valueOf(notifCode)); activity.putExtra("numMarkedNotificationsList", 1); startActivityForResult(activity, Constants.NOTIFMARKALLASREAD_REQUEST_CODE); } else { Log.w(TAG, "Not connected: Marking the notification " + notifCode + " as read in SWAD was deferred"); } } } /* (non-Javadoc) * @see android.app.Activity#onActivityResult(int, int, android.content.Intent) */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == Constants.NOTIFMARKALLASREAD_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { Log.i(TAG, "Notification " + notifCode + " marked as read in SWAD"); } else { Log.e(TAG, "Error marking notification " + notifCode + " as read in SWAD"); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.notification_single_activity_actions, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_reply: Intent activity = new Intent(this, Messages.class); activity.putExtra("eventCode", eventCode); activity.putExtra("summary", summary); startActivity(activity); return true; default: return super.onOptionsItemSelected(item); } } }
true
true
protected void onCreate(Bundle savedInstanceState) { TextView senderTextView, courseTextView, summaryTextView, dateTextView, timeTextView; ImageView userPhotoView; WebView webview; Intent activity; String type = this.getIntent().getStringExtra("notificationType"); super.onCreate(savedInstanceState); setContentView(R.layout.single_notification_view); getSupportActionBar().setIcon(R.drawable.notif_black); senderTextView = (TextView) this.findViewById(R.id.senderNameText); courseTextView = (TextView) this.findViewById(R.id.courseNameText); summaryTextView = (TextView) this.findViewById(R.id.summaryText); userPhotoView = (ImageView) this.findViewById(R.id.notifUserPhoto); webview = (WebView) this.findViewById(R.id.contentWebView); dateTextView = (TextView) this.findViewById(R.id.notifDate); timeTextView = (TextView) this.findViewById(R.id.notifTime); notifCode = Long.valueOf(this.getIntent().getStringExtra("notifCode")); eventCode = Long.valueOf(this.getIntent().getStringExtra("eventCode")); sender = this.getIntent().getStringExtra("sender"); userPhoto = this.getIntent().getStringExtra("userPhoto"); course = this.getIntent().getStringExtra("course"); summary = this.getIntent().getStringExtra("summary"); content = this.getIntent().getStringExtra("content"); date = this.getIntent().getStringExtra("date"); time = this.getIntent().getStringExtra("time"); seenLocal = Utils.parseStringBool(this.getIntent().getStringExtra("seenLocal")); senderTextView.setText(sender); courseTextView.setText(course); summaryTextView.setText(summary); dateTextView.setText(date); timeTextView.setText(time); //If the user photo exists and is public, download and show it if (Utils.connectionAvailable(this) && (userPhoto != null) && !userPhoto.equals("") && !userPhoto.equals(Constants.NULL_VALUE)) { //userPhotoView.setImageURI(Uri.parse(userPhoto)); new DownloadImageTask(userPhotoView).execute(userPhoto); } else { Log.d("NotificationItem", "No connection or no photo " + userPhoto); } content = Utils.fixLinks(content); if (content.startsWith("<![CDATA[")) { content = content.substring(9, content.length() - 3); } webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); webview.loadDataWithBaseURL("", content, "text/html", "utf-8", ""); //Set notification as seen locally dbHelper.updateNotification(notifCode, "seenLocal", Utils.parseBoolString(true)); //Sends "seen notifications" info to the server if there is a connection available if(!seenLocal) { if(Utils.connectionAvailable(this)) { activity = new Intent(this, NotificationsMarkAllAsRead.class); activity.putExtra("seenNotifCodes", String.valueOf(notifCode)); activity.putExtra("numMarkedNotificationsList", 1); startActivityForResult(activity, Constants.NOTIFMARKALLASREAD_REQUEST_CODE); } else { Log.w(TAG, "Not connected: Marking the notification " + notifCode + " as read in SWAD was deferred"); } } }
protected void onCreate(Bundle savedInstanceState) { TextView senderTextView, courseTextView, summaryTextView, dateTextView, timeTextView; ImageView userPhotoView; WebView webview; Intent activity; String type = this.getIntent().getStringExtra("notificationType"); super.onCreate(savedInstanceState); setContentView(R.layout.single_notification_view); getSupportActionBar().setIcon(R.drawable.notif); senderTextView = (TextView) this.findViewById(R.id.senderNameText); courseTextView = (TextView) this.findViewById(R.id.courseNameText); summaryTextView = (TextView) this.findViewById(R.id.summaryText); userPhotoView = (ImageView) this.findViewById(R.id.notifUserPhoto); webview = (WebView) this.findViewById(R.id.contentWebView); dateTextView = (TextView) this.findViewById(R.id.notifDate); timeTextView = (TextView) this.findViewById(R.id.notifTime); notifCode = Long.valueOf(this.getIntent().getStringExtra("notifCode")); eventCode = Long.valueOf(this.getIntent().getStringExtra("eventCode")); sender = this.getIntent().getStringExtra("sender"); userPhoto = this.getIntent().getStringExtra("userPhoto"); course = this.getIntent().getStringExtra("course"); summary = this.getIntent().getStringExtra("summary"); content = this.getIntent().getStringExtra("content"); date = this.getIntent().getStringExtra("date"); time = this.getIntent().getStringExtra("time"); seenLocal = Utils.parseStringBool(this.getIntent().getStringExtra("seenLocal")); senderTextView.setText(sender); courseTextView.setText(course); summaryTextView.setText(summary); dateTextView.setText(date); timeTextView.setText(time); //If the user photo exists and is public, download and show it if (Utils.connectionAvailable(this) && (userPhoto != null) && !userPhoto.equals("") && !userPhoto.equals(Constants.NULL_VALUE)) { //userPhotoView.setImageURI(Uri.parse(userPhoto)); new DownloadImageTask(userPhotoView).execute(userPhoto); } else { Log.d("NotificationItem", "No connection or no photo " + userPhoto); } content = Utils.fixLinks(content); if (content.startsWith("<![CDATA[")) { content = content.substring(9, content.length() - 3); } webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); webview.loadDataWithBaseURL("", content, "text/html", "utf-8", ""); //Set notification as seen locally dbHelper.updateNotification(notifCode, "seenLocal", Utils.parseBoolString(true)); //Sends "seen notifications" info to the server if there is a connection available if(!seenLocal) { if(Utils.connectionAvailable(this)) { activity = new Intent(this, NotificationsMarkAllAsRead.class); activity.putExtra("seenNotifCodes", String.valueOf(notifCode)); activity.putExtra("numMarkedNotificationsList", 1); startActivityForResult(activity, Constants.NOTIFMARKALLASREAD_REQUEST_CODE); } else { Log.w(TAG, "Not connected: Marking the notification " + notifCode + " as read in SWAD was deferred"); } } }
diff --git a/hedwig-server/src/main/java/org/apache/hedwig/server/handlers/SubscribeHandler.java b/hedwig-server/src/main/java/org/apache/hedwig/server/handlers/SubscribeHandler.java index 0622f2b8..64478a9b 100644 --- a/hedwig-server/src/main/java/org/apache/hedwig/server/handlers/SubscribeHandler.java +++ b/hedwig-server/src/main/java/org/apache/hedwig/server/handlers/SubscribeHandler.java @@ -1,240 +1,236 @@ /** * 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.hedwig.server.handlers; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import com.google.protobuf.ByteString; import org.apache.bookkeeper.stats.OpStatsLogger; import org.apache.bookkeeper.util.MathUtils; import org.apache.bookkeeper.util.ReflectionUtils; import org.apache.hedwig.client.data.TopicSubscriber; import org.apache.hedwig.exceptions.PubSubException; import org.apache.hedwig.exceptions.PubSubException.ServerNotResponsibleForTopicException; import org.apache.hedwig.filter.PipelineFilter; import org.apache.hedwig.filter.ServerMessageFilter; import org.apache.hedwig.protocol.PubSubProtocol.MessageSeqId; import org.apache.hedwig.protocol.PubSubProtocol.OperationType; import org.apache.hedwig.protocol.PubSubProtocol.PubSubRequest; import org.apache.hedwig.protocol.PubSubProtocol.ResponseBody; import org.apache.hedwig.protocol.PubSubProtocol.SubscribeRequest; import org.apache.hedwig.protocol.PubSubProtocol.SubscribeResponse; import org.apache.hedwig.protocol.PubSubProtocol.SubscriptionData; import org.apache.hedwig.protoextensions.PubSubResponseUtils; import org.apache.hedwig.protoextensions.SubscriptionStateUtils; import org.apache.hedwig.server.common.ServerConfiguration; import org.apache.hedwig.server.delivery.ChannelEndPoint; import org.apache.hedwig.server.delivery.DeliveryManager; import org.apache.hedwig.server.netty.UmbrellaHandler; import org.apache.hedwig.server.persistence.PersistenceManager; import org.apache.hedwig.server.stats.HedwigServerStatsLogger.HedwigServerSimpleStatType; import org.apache.hedwig.server.stats.ServerStatsProvider; import org.apache.hedwig.server.subscriptions.SubscriptionEventListener; import org.apache.hedwig.server.subscriptions.SubscriptionManager; import org.apache.hedwig.server.subscriptions.AllToAllTopologyFilter; import org.apache.hedwig.server.topics.TopicManager; import org.apache.hedwig.util.Callback; import static org.apache.hedwig.util.VarArgs.va; public class SubscribeHandler extends BaseHandler { static Logger logger = LoggerFactory.getLogger(SubscribeHandler.class); private final DeliveryManager deliveryMgr; private final PersistenceManager persistenceMgr; private final SubscriptionManager subMgr; private final SubscriptionChannelManager subChannelMgr; // op stats private final OpStatsLogger subStatsLogger; public SubscribeHandler(ServerConfiguration cfg, TopicManager topicMgr, DeliveryManager deliveryManager, PersistenceManager persistenceMgr, SubscriptionManager subMgr, SubscriptionChannelManager subChannelMgr) { super(topicMgr, cfg); this.deliveryMgr = deliveryManager; this.persistenceMgr = persistenceMgr; this.subMgr = subMgr; this.subChannelMgr = subChannelMgr; subStatsLogger = ServerStatsProvider.getStatsLoggerInstance().getOpStatsLogger(OperationType.SUBSCRIBE); } @Override public void handleRequestAtOwner(final PubSubRequest request, final Channel channel) { final long requestTimeMillis = MathUtils.now(); if (!request.hasSubscribeRequest()) { logger.error("Received a request: {} on channel: {} without a Subscribe request.", request, channel); UmbrellaHandler.sendErrorResponseToMalformedRequest(channel, request.getTxnId(), "Missing subscribe request data"); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); return; } logger.info("Received a subscription request for topic:" + request.getTopic().toStringUtf8() + " and subId:" + request .getSubscribeRequest().getSubscriberId().toStringUtf8() + " from address:" + channel.getRemoteAddress()); final ByteString topic = request.getTopic(); MessageSeqId seqId; try { seqId = persistenceMgr.getCurrentSeqIdForTopic(topic); } catch (ServerNotResponsibleForTopicException e) { - channel.write(PubSubResponseUtils.getResponseForException(e, request.getTxnId())).addListener( - ChannelFutureListener.CLOSE); + channel.write(PubSubResponseUtils.getResponseForException(e, request.getTxnId())); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); ServerStatsProvider.getStatsLoggerInstance() .getSimpleStatLogger(HedwigServerSimpleStatType.TOTAL_REQUESTS_REDIRECT).inc(); // The exception's getMessage() gives us the actual owner for the topic logger.info("Redirecting a subscribe request for subId: " + request.getSubscribeRequest().getSubscriberId().toStringUtf8() + " and topic: " + request.getTopic().toStringUtf8() + " from client: " + channel.getRemoteAddress() + " to remote host: " + e.getMessage()); return; } final SubscribeRequest subRequest = request.getSubscribeRequest(); final ByteString subscriberId = subRequest.getSubscriberId(); MessageSeqId lastSeqIdPublished = MessageSeqId.newBuilder(seqId).setLocalComponent(seqId.getLocalComponent()).build(); subMgr.serveSubscribeRequest(topic, subRequest, lastSeqIdPublished, new Callback<SubscriptionData>() { @Override public void operationFailed(Object ctx, PubSubException exception) { - channel.write(PubSubResponseUtils.getResponseForException(exception, request.getTxnId())).addListener( - ChannelFutureListener.CLOSE); + channel.write(PubSubResponseUtils.getResponseForException(exception, request.getTxnId())); logger.error("Error serving subscribe request (" + request.getTxnId() + ") for (topic: " + topic.toStringUtf8() + " , subscriber: " + subscriberId.toStringUtf8() + ")", exception); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); } @Override public void operationFinished(Object ctx, final SubscriptionData subData) { TopicSubscriber topicSub = new TopicSubscriber(topic, subscriberId); synchronized (channel) { if (!channel.isConnected()) { logger.warn("Channel: {} disconnected while the hub was processing its subscription request: {}", channel, request); // channel got disconnected while we were processing the // subscribe request, // nothing much we can do in this case subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); return; } } // initialize the message filter PipelineFilter filter = new PipelineFilter(); try { // the filter pipeline should be // 1) AllToAllTopologyFilter to filter cross-region messages filter.addLast(new AllToAllTopologyFilter()); // 2) User-Customized MessageFilter if (subData.hasPreferences() && subData.getPreferences().hasMessageFilter()) { String messageFilterName = subData.getPreferences().getMessageFilter(); filter.addLast(ReflectionUtils.newInstance(messageFilterName, ServerMessageFilter.class)); } // initialize the filter filter.initialize(cfg.getConf()); filter.setSubscriptionPreferences(topic, subscriberId, subData.getPreferences()); } catch (RuntimeException re) { String errMsg = "RuntimeException caught when instantiating message filter for (topic:" + topic.toStringUtf8() + ", subscriber:" + subscriberId.toStringUtf8() + ")." + "It might be introduced by programming error in message filter."; logger.error(errMsg, re); PubSubException pse = new PubSubException.InvalidMessageFilterException(errMsg, re); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); // we should not close the subscription channel, just response error // client decide to close it or not. channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())); return; } catch (Throwable t) { String errMsg = "Failed to instantiate message filter for (topic:" + topic.toStringUtf8() + ", subscriber:" + subscriberId.toStringUtf8() + ")."; logger.error(errMsg, t); PubSubException pse = new PubSubException.InvalidMessageFilterException(errMsg, t); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); - channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())) - .addListener(ChannelFutureListener.CLOSE); + channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())); return; } boolean forceAttach = false; if (subRequest.hasForceAttach()) { forceAttach = subRequest.getForceAttach(); } // Try to store the subscription channel for the topic subscriber Channel oldChannel = subChannelMgr.put(topicSub, channel, forceAttach); if (null != oldChannel) { PubSubException pse = new PubSubException.TopicBusyException( "Subscriber " + subscriberId.toStringUtf8() + " for topic " + topic.toStringUtf8() + " is already being served on a different channel " + oldChannel + "."); logger.error("Topic busy exception as subscriber is being served on another channel: {} while handling " + "subscription request: {} on channel: {}", va(oldChannel, request, channel)); - channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())) - .addListener(ChannelFutureListener.CLOSE); + channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); return; } logger.info("Serve subscription request succeeded for request: {} on channel: {}. Issuing start delivery request.", request, channel); // want to start 1 ahead of the consume ptr MessageSeqId lastConsumedSeqId = subData.getState().getMsgId(); MessageSeqId seqIdToStartFrom = MessageSeqId.newBuilder(lastConsumedSeqId).setLocalComponent( lastConsumedSeqId.getLocalComponent() + 1).build(); deliveryMgr.startServingSubscription(topic, subscriberId, subData.getPreferences(), seqIdToStartFrom, new ChannelEndPoint(channel), filter, new Callback<Void>() { @Override public void operationFinished(Object ctx, Void result) { // First write success and then tell the delivery manager, // otherwise the first message might go out before the response // to the subscribe SubscribeResponse.Builder subRespBuilder = SubscribeResponse.newBuilder() .setPreferences(subData.getPreferences()); ResponseBody respBody = ResponseBody.newBuilder() .setSubscribeResponse(subRespBuilder).build(); channel.write(PubSubResponseUtils.getSuccessResponse(request.getTxnId(), respBody)); logger.info("Subscribe request (" + request.getTxnId() + ") for (topic:" + topic.toStringUtf8() + ", subscriber:" + subscriberId.toStringUtf8() + ") from channel " + channel.getRemoteAddress() + " succeed - its subscription data is " + SubscriptionStateUtils.toString(subData)); subStatsLogger.registerSuccessfulEvent(MathUtils.now() - requestTimeMillis); } @Override public void operationFailed(Object ctx, PubSubException exception) { logger.error("Delivery manager failed to start serving subscription for request: {} on channel: {}", va(request, channel), exception); } }, null); } }, null); } }
false
true
public void handleRequestAtOwner(final PubSubRequest request, final Channel channel) { final long requestTimeMillis = MathUtils.now(); if (!request.hasSubscribeRequest()) { logger.error("Received a request: {} on channel: {} without a Subscribe request.", request, channel); UmbrellaHandler.sendErrorResponseToMalformedRequest(channel, request.getTxnId(), "Missing subscribe request data"); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); return; } logger.info("Received a subscription request for topic:" + request.getTopic().toStringUtf8() + " and subId:" + request .getSubscribeRequest().getSubscriberId().toStringUtf8() + " from address:" + channel.getRemoteAddress()); final ByteString topic = request.getTopic(); MessageSeqId seqId; try { seqId = persistenceMgr.getCurrentSeqIdForTopic(topic); } catch (ServerNotResponsibleForTopicException e) { channel.write(PubSubResponseUtils.getResponseForException(e, request.getTxnId())).addListener( ChannelFutureListener.CLOSE); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); ServerStatsProvider.getStatsLoggerInstance() .getSimpleStatLogger(HedwigServerSimpleStatType.TOTAL_REQUESTS_REDIRECT).inc(); // The exception's getMessage() gives us the actual owner for the topic logger.info("Redirecting a subscribe request for subId: " + request.getSubscribeRequest().getSubscriberId().toStringUtf8() + " and topic: " + request.getTopic().toStringUtf8() + " from client: " + channel.getRemoteAddress() + " to remote host: " + e.getMessage()); return; } final SubscribeRequest subRequest = request.getSubscribeRequest(); final ByteString subscriberId = subRequest.getSubscriberId(); MessageSeqId lastSeqIdPublished = MessageSeqId.newBuilder(seqId).setLocalComponent(seqId.getLocalComponent()).build(); subMgr.serveSubscribeRequest(topic, subRequest, lastSeqIdPublished, new Callback<SubscriptionData>() { @Override public void operationFailed(Object ctx, PubSubException exception) { channel.write(PubSubResponseUtils.getResponseForException(exception, request.getTxnId())).addListener( ChannelFutureListener.CLOSE); logger.error("Error serving subscribe request (" + request.getTxnId() + ") for (topic: " + topic.toStringUtf8() + " , subscriber: " + subscriberId.toStringUtf8() + ")", exception); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); } @Override public void operationFinished(Object ctx, final SubscriptionData subData) { TopicSubscriber topicSub = new TopicSubscriber(topic, subscriberId); synchronized (channel) { if (!channel.isConnected()) { logger.warn("Channel: {} disconnected while the hub was processing its subscription request: {}", channel, request); // channel got disconnected while we were processing the // subscribe request, // nothing much we can do in this case subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); return; } } // initialize the message filter PipelineFilter filter = new PipelineFilter(); try { // the filter pipeline should be // 1) AllToAllTopologyFilter to filter cross-region messages filter.addLast(new AllToAllTopologyFilter()); // 2) User-Customized MessageFilter if (subData.hasPreferences() && subData.getPreferences().hasMessageFilter()) { String messageFilterName = subData.getPreferences().getMessageFilter(); filter.addLast(ReflectionUtils.newInstance(messageFilterName, ServerMessageFilter.class)); } // initialize the filter filter.initialize(cfg.getConf()); filter.setSubscriptionPreferences(topic, subscriberId, subData.getPreferences()); } catch (RuntimeException re) { String errMsg = "RuntimeException caught when instantiating message filter for (topic:" + topic.toStringUtf8() + ", subscriber:" + subscriberId.toStringUtf8() + ")." + "It might be introduced by programming error in message filter."; logger.error(errMsg, re); PubSubException pse = new PubSubException.InvalidMessageFilterException(errMsg, re); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); // we should not close the subscription channel, just response error // client decide to close it or not. channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())); return; } catch (Throwable t) { String errMsg = "Failed to instantiate message filter for (topic:" + topic.toStringUtf8() + ", subscriber:" + subscriberId.toStringUtf8() + ")."; logger.error(errMsg, t); PubSubException pse = new PubSubException.InvalidMessageFilterException(errMsg, t); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())) .addListener(ChannelFutureListener.CLOSE); return; } boolean forceAttach = false; if (subRequest.hasForceAttach()) { forceAttach = subRequest.getForceAttach(); } // Try to store the subscription channel for the topic subscriber Channel oldChannel = subChannelMgr.put(topicSub, channel, forceAttach); if (null != oldChannel) { PubSubException pse = new PubSubException.TopicBusyException( "Subscriber " + subscriberId.toStringUtf8() + " for topic " + topic.toStringUtf8() + " is already being served on a different channel " + oldChannel + "."); logger.error("Topic busy exception as subscriber is being served on another channel: {} while handling " + "subscription request: {} on channel: {}", va(oldChannel, request, channel)); channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())) .addListener(ChannelFutureListener.CLOSE); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); return; } logger.info("Serve subscription request succeeded for request: {} on channel: {}. Issuing start delivery request.", request, channel); // want to start 1 ahead of the consume ptr MessageSeqId lastConsumedSeqId = subData.getState().getMsgId(); MessageSeqId seqIdToStartFrom = MessageSeqId.newBuilder(lastConsumedSeqId).setLocalComponent( lastConsumedSeqId.getLocalComponent() + 1).build(); deliveryMgr.startServingSubscription(topic, subscriberId, subData.getPreferences(), seqIdToStartFrom, new ChannelEndPoint(channel), filter, new Callback<Void>() { @Override public void operationFinished(Object ctx, Void result) { // First write success and then tell the delivery manager, // otherwise the first message might go out before the response // to the subscribe SubscribeResponse.Builder subRespBuilder = SubscribeResponse.newBuilder() .setPreferences(subData.getPreferences()); ResponseBody respBody = ResponseBody.newBuilder() .setSubscribeResponse(subRespBuilder).build(); channel.write(PubSubResponseUtils.getSuccessResponse(request.getTxnId(), respBody)); logger.info("Subscribe request (" + request.getTxnId() + ") for (topic:" + topic.toStringUtf8() + ", subscriber:" + subscriberId.toStringUtf8() + ") from channel " + channel.getRemoteAddress() + " succeed - its subscription data is " + SubscriptionStateUtils.toString(subData)); subStatsLogger.registerSuccessfulEvent(MathUtils.now() - requestTimeMillis); } @Override public void operationFailed(Object ctx, PubSubException exception) { logger.error("Delivery manager failed to start serving subscription for request: {} on channel: {}", va(request, channel), exception); } }, null); } }, null); }
public void handleRequestAtOwner(final PubSubRequest request, final Channel channel) { final long requestTimeMillis = MathUtils.now(); if (!request.hasSubscribeRequest()) { logger.error("Received a request: {} on channel: {} without a Subscribe request.", request, channel); UmbrellaHandler.sendErrorResponseToMalformedRequest(channel, request.getTxnId(), "Missing subscribe request data"); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); return; } logger.info("Received a subscription request for topic:" + request.getTopic().toStringUtf8() + " and subId:" + request .getSubscribeRequest().getSubscriberId().toStringUtf8() + " from address:" + channel.getRemoteAddress()); final ByteString topic = request.getTopic(); MessageSeqId seqId; try { seqId = persistenceMgr.getCurrentSeqIdForTopic(topic); } catch (ServerNotResponsibleForTopicException e) { channel.write(PubSubResponseUtils.getResponseForException(e, request.getTxnId())); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); ServerStatsProvider.getStatsLoggerInstance() .getSimpleStatLogger(HedwigServerSimpleStatType.TOTAL_REQUESTS_REDIRECT).inc(); // The exception's getMessage() gives us the actual owner for the topic logger.info("Redirecting a subscribe request for subId: " + request.getSubscribeRequest().getSubscriberId().toStringUtf8() + " and topic: " + request.getTopic().toStringUtf8() + " from client: " + channel.getRemoteAddress() + " to remote host: " + e.getMessage()); return; } final SubscribeRequest subRequest = request.getSubscribeRequest(); final ByteString subscriberId = subRequest.getSubscriberId(); MessageSeqId lastSeqIdPublished = MessageSeqId.newBuilder(seqId).setLocalComponent(seqId.getLocalComponent()).build(); subMgr.serveSubscribeRequest(topic, subRequest, lastSeqIdPublished, new Callback<SubscriptionData>() { @Override public void operationFailed(Object ctx, PubSubException exception) { channel.write(PubSubResponseUtils.getResponseForException(exception, request.getTxnId())); logger.error("Error serving subscribe request (" + request.getTxnId() + ") for (topic: " + topic.toStringUtf8() + " , subscriber: " + subscriberId.toStringUtf8() + ")", exception); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); } @Override public void operationFinished(Object ctx, final SubscriptionData subData) { TopicSubscriber topicSub = new TopicSubscriber(topic, subscriberId); synchronized (channel) { if (!channel.isConnected()) { logger.warn("Channel: {} disconnected while the hub was processing its subscription request: {}", channel, request); // channel got disconnected while we were processing the // subscribe request, // nothing much we can do in this case subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); return; } } // initialize the message filter PipelineFilter filter = new PipelineFilter(); try { // the filter pipeline should be // 1) AllToAllTopologyFilter to filter cross-region messages filter.addLast(new AllToAllTopologyFilter()); // 2) User-Customized MessageFilter if (subData.hasPreferences() && subData.getPreferences().hasMessageFilter()) { String messageFilterName = subData.getPreferences().getMessageFilter(); filter.addLast(ReflectionUtils.newInstance(messageFilterName, ServerMessageFilter.class)); } // initialize the filter filter.initialize(cfg.getConf()); filter.setSubscriptionPreferences(topic, subscriberId, subData.getPreferences()); } catch (RuntimeException re) { String errMsg = "RuntimeException caught when instantiating message filter for (topic:" + topic.toStringUtf8() + ", subscriber:" + subscriberId.toStringUtf8() + ")." + "It might be introduced by programming error in message filter."; logger.error(errMsg, re); PubSubException pse = new PubSubException.InvalidMessageFilterException(errMsg, re); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); // we should not close the subscription channel, just response error // client decide to close it or not. channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())); return; } catch (Throwable t) { String errMsg = "Failed to instantiate message filter for (topic:" + topic.toStringUtf8() + ", subscriber:" + subscriberId.toStringUtf8() + ")."; logger.error(errMsg, t); PubSubException pse = new PubSubException.InvalidMessageFilterException(errMsg, t); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())); return; } boolean forceAttach = false; if (subRequest.hasForceAttach()) { forceAttach = subRequest.getForceAttach(); } // Try to store the subscription channel for the topic subscriber Channel oldChannel = subChannelMgr.put(topicSub, channel, forceAttach); if (null != oldChannel) { PubSubException pse = new PubSubException.TopicBusyException( "Subscriber " + subscriberId.toStringUtf8() + " for topic " + topic.toStringUtf8() + " is already being served on a different channel " + oldChannel + "."); logger.error("Topic busy exception as subscriber is being served on another channel: {} while handling " + "subscription request: {} on channel: {}", va(oldChannel, request, channel)); channel.write(PubSubResponseUtils.getResponseForException(pse, request.getTxnId())); subStatsLogger.registerFailedEvent(MathUtils.now() - requestTimeMillis); return; } logger.info("Serve subscription request succeeded for request: {} on channel: {}. Issuing start delivery request.", request, channel); // want to start 1 ahead of the consume ptr MessageSeqId lastConsumedSeqId = subData.getState().getMsgId(); MessageSeqId seqIdToStartFrom = MessageSeqId.newBuilder(lastConsumedSeqId).setLocalComponent( lastConsumedSeqId.getLocalComponent() + 1).build(); deliveryMgr.startServingSubscription(topic, subscriberId, subData.getPreferences(), seqIdToStartFrom, new ChannelEndPoint(channel), filter, new Callback<Void>() { @Override public void operationFinished(Object ctx, Void result) { // First write success and then tell the delivery manager, // otherwise the first message might go out before the response // to the subscribe SubscribeResponse.Builder subRespBuilder = SubscribeResponse.newBuilder() .setPreferences(subData.getPreferences()); ResponseBody respBody = ResponseBody.newBuilder() .setSubscribeResponse(subRespBuilder).build(); channel.write(PubSubResponseUtils.getSuccessResponse(request.getTxnId(), respBody)); logger.info("Subscribe request (" + request.getTxnId() + ") for (topic:" + topic.toStringUtf8() + ", subscriber:" + subscriberId.toStringUtf8() + ") from channel " + channel.getRemoteAddress() + " succeed - its subscription data is " + SubscriptionStateUtils.toString(subData)); subStatsLogger.registerSuccessfulEvent(MathUtils.now() - requestTimeMillis); } @Override public void operationFailed(Object ctx, PubSubException exception) { logger.error("Delivery manager failed to start serving subscription for request: {} on channel: {}", va(request, channel), exception); } }, null); } }, null); }
diff --git a/Addons/Camouflage/CF-common/wirelessredstone/addon/camouflager/inventory/ContainerCamouflagedRedstoneWireless.java b/Addons/Camouflage/CF-common/wirelessredstone/addon/camouflager/inventory/ContainerCamouflagedRedstoneWireless.java index fb006c8..68509d2 100644 --- a/Addons/Camouflage/CF-common/wirelessredstone/addon/camouflager/inventory/ContainerCamouflagedRedstoneWireless.java +++ b/Addons/Camouflage/CF-common/wirelessredstone/addon/camouflager/inventory/ContainerCamouflagedRedstoneWireless.java @@ -1,91 +1,84 @@ package wirelessredstone.addon.camouflager.inventory; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import wirelessredstone.addon.camouflager.inventory.slot.SlotBlock; import wirelessredstone.tileentity.ContainerRedstoneWireless; public class ContainerCamouflagedRedstoneWireless extends ContainerRedstoneWireless { InventoryPlayer playerInventory; public ContainerCamouflagedRedstoneWireless(InventoryPlayer playerInventory, TileEntity tileentity) { super(tileentity); this.playerInventory = playerInventory; this.bindLocalInventory(); this.bindPlayerInventory( 0, 84); } protected void bindLocalInventory() { this.addSlotToContainer(new SlotBlock(this.redstoneWireless, 0, 80, 36)); } protected void bindPlayerInventory(int playerColOffset, int playerRowOffset) { // Player inventory for (int row = 0; row < 3; ++row) { for (int column = 0; column < 9; ++column) { int slotIndex = column + row * 9 + 9; this.addSlotToContainer(new Slot(this.playerInventory, slotIndex, (8 + column * 18 + playerColOffset), (row * 18 + playerRowOffset))); } } // Hotbar inventory for (int column = 0; column < 9; ++column) { int slotIndex = column; this.addSlotToContainer(new Slot(this.playerInventory, slotIndex, (8 + column * 18 + playerColOffset), 58 + playerRowOffset)); } } private ItemStack transferBlockToSlot(EntityPlayer player, int slotShiftClicked) { ItemStack stackCopy = null; Slot slot = this.getSlot(slotShiftClicked); if (slot != null && slot.getHasStack()) { ItemStack stackInSlot = slot.getStack(); stackCopy = stackInSlot.copy(); if (slotShiftClicked < 1) { if (!this.mergeItemStack( stackInSlot, 1, this.inventorySlots.size(), true)) { - if (!this.mergeItemStack( stackInSlot, - 0, - 1, - true)) { - return null; - } + return null; } } else { - if (!this.getSlot(0).getHasStack()) { - if (!this.mergeItemStack( stackInSlot, - 0, - 1, - true)) { - return null; - } + if (!this.mergeItemStack( stackInSlot, + 0, + 1, + true)) { + return null; } } if (stackInSlot.stackSize == 0) { slot.putStack((ItemStack) null); } else { slot.onSlotChanged(); } } return stackCopy; } @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotID) { ItemStack stack = this.transferBlockToSlot( player, slotID); return stack; } }
false
true
private ItemStack transferBlockToSlot(EntityPlayer player, int slotShiftClicked) { ItemStack stackCopy = null; Slot slot = this.getSlot(slotShiftClicked); if (slot != null && slot.getHasStack()) { ItemStack stackInSlot = slot.getStack(); stackCopy = stackInSlot.copy(); if (slotShiftClicked < 1) { if (!this.mergeItemStack( stackInSlot, 1, this.inventorySlots.size(), true)) { if (!this.mergeItemStack( stackInSlot, 0, 1, true)) { return null; } } } else { if (!this.getSlot(0).getHasStack()) { if (!this.mergeItemStack( stackInSlot, 0, 1, true)) { return null; } } } if (stackInSlot.stackSize == 0) { slot.putStack((ItemStack) null); } else { slot.onSlotChanged(); } } return stackCopy; }
private ItemStack transferBlockToSlot(EntityPlayer player, int slotShiftClicked) { ItemStack stackCopy = null; Slot slot = this.getSlot(slotShiftClicked); if (slot != null && slot.getHasStack()) { ItemStack stackInSlot = slot.getStack(); stackCopy = stackInSlot.copy(); if (slotShiftClicked < 1) { if (!this.mergeItemStack( stackInSlot, 1, this.inventorySlots.size(), true)) { return null; } } else { if (!this.mergeItemStack( stackInSlot, 0, 1, true)) { return null; } } if (stackInSlot.stackSize == 0) { slot.putStack((ItemStack) null); } else { slot.onSlotChanged(); } } return stackCopy; }
diff --git a/src/com/jidesoft/swing/PartialLineBorder.java b/src/com/jidesoft/swing/PartialLineBorder.java index 44bdcef1..36738571 100644 --- a/src/com/jidesoft/swing/PartialLineBorder.java +++ b/src/com/jidesoft/swing/PartialLineBorder.java @@ -1,70 +1,70 @@ package com.jidesoft.swing; import javax.swing.border.LineBorder; import java.awt.*; /** * This is a better version of LineBorder which allows you to show line only at one side or several sides. */ public class PartialLineBorder extends LineBorder implements PartialSide { private int _sides = ALL; public PartialLineBorder(Color color) { super(color); } public PartialLineBorder(Color color, int thickness) { super(color, thickness); } public PartialLineBorder(Color color, int thickness, boolean roundedCorners) { super(color, thickness, roundedCorners); } public PartialLineBorder(Color color, int thickness, int side) { super(color, thickness); _sides = side; } public int getSides() { return _sides; } public void setSides(int sides) { _sides = sides; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color oldColor = g.getColor(); int i; g.setColor(lineColor); for (i = 0; i < thickness; i++) { if (_sides == ALL) { if (!roundedCorners) g.drawRect(x + i, y + i, width - i - i - 1, height - i - i - 1); else - g.drawRoundRect(x + i, y + i, width - i - i - 1, height - i - i - 1, 5, 5); + g.drawRoundRect(x + i, y + i, width - i - i - 1, height - i - i - 1, thickness, thickness); } else { if ((_sides & NORTH) != 0) { g.drawLine(x, y + i, x + width - 1, y + i); } if ((_sides & SOUTH) != 0) { g.drawLine(x, y + height - i - 1, x + width - 1, y + height - i - 1); } if ((_sides & WEST) != 0) { g.drawLine(x + i, y, x + i, y + height - 1); } if ((_sides & EAST) != 0) { g.drawLine(x + width - i - 1, y, x + width - i - 1, y + height - 1); } } } g.setColor(oldColor); } }
true
true
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color oldColor = g.getColor(); int i; g.setColor(lineColor); for (i = 0; i < thickness; i++) { if (_sides == ALL) { if (!roundedCorners) g.drawRect(x + i, y + i, width - i - i - 1, height - i - i - 1); else g.drawRoundRect(x + i, y + i, width - i - i - 1, height - i - i - 1, 5, 5); } else { if ((_sides & NORTH) != 0) { g.drawLine(x, y + i, x + width - 1, y + i); } if ((_sides & SOUTH) != 0) { g.drawLine(x, y + height - i - 1, x + width - 1, y + height - i - 1); } if ((_sides & WEST) != 0) { g.drawLine(x + i, y, x + i, y + height - 1); } if ((_sides & EAST) != 0) { g.drawLine(x + width - i - 1, y, x + width - i - 1, y + height - 1); } } } g.setColor(oldColor); }
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { Color oldColor = g.getColor(); int i; g.setColor(lineColor); for (i = 0; i < thickness; i++) { if (_sides == ALL) { if (!roundedCorners) g.drawRect(x + i, y + i, width - i - i - 1, height - i - i - 1); else g.drawRoundRect(x + i, y + i, width - i - i - 1, height - i - i - 1, thickness, thickness); } else { if ((_sides & NORTH) != 0) { g.drawLine(x, y + i, x + width - 1, y + i); } if ((_sides & SOUTH) != 0) { g.drawLine(x, y + height - i - 1, x + width - 1, y + height - i - 1); } if ((_sides & WEST) != 0) { g.drawLine(x + i, y, x + i, y + height - 1); } if ((_sides & EAST) != 0) { g.drawLine(x + width - i - 1, y, x + width - i - 1, y + height - 1); } } } g.setColor(oldColor); }
diff --git a/src/com/android/contacts/list/DefaultContactListAdapter.java b/src/com/android/contacts/list/DefaultContactListAdapter.java index 2a8d66581..3409f5652 100644 --- a/src/com/android/contacts/list/DefaultContactListAdapter.java +++ b/src/com/android/contacts/list/DefaultContactListAdapter.java @@ -1,254 +1,254 @@ /* * Copyright (C) 2010 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.contacts.list; import com.android.contacts.preference.ContactsPreferences; import android.content.ContentUris; import android.content.Context; import android.content.CursorLoader; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.net.Uri.Builder; import android.preference.PreferenceManager; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds.GroupMembership; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.Directory; import android.provider.ContactsContract.RawContacts; import android.provider.ContactsContract.SearchSnippetColumns; import android.text.TextUtils; import android.view.View; import java.util.ArrayList; import java.util.List; /** * A cursor adapter for the {@link ContactsContract.Contacts#CONTENT_TYPE} content type. */ public class DefaultContactListAdapter extends ContactListAdapter { public static final char SNIPPET_START_MATCH = '\u0001'; public static final char SNIPPET_END_MATCH = '\u0001'; public static final String SNIPPET_ELLIPSIS = "\u2026"; public static final int SNIPPET_MAX_TOKENS = 5; public static final String SNIPPET_ARGS = SNIPPET_START_MATCH + "," + SNIPPET_END_MATCH + "," + SNIPPET_ELLIPSIS + "," + SNIPPET_MAX_TOKENS; public DefaultContactListAdapter(Context context) { super(context); } @Override public void configureLoader(CursorLoader loader, long directoryId) { if (loader instanceof ProfileAndContactsLoader) { ((ProfileAndContactsLoader) loader).setLoadProfile(shouldIncludeProfile()); } ContactListFilter filter = getFilter(); if (isSearchMode()) { String query = getQueryString(); if (query == null) { query = ""; } query = query.trim(); if (TextUtils.isEmpty(query)) { // Regardless of the directory, we don't want anything returned, // so let's just send a "nothing" query to the local directory. loader.setUri(Contacts.CONTENT_URI); loader.setProjection(PROJECTION_CONTACT); loader.setSelection("0"); } else { Builder builder = Contacts.CONTENT_FILTER_URI.buildUpon(); builder.appendPath(query); // Builder will encode the query builder.appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(directoryId)); if (directoryId != Directory.DEFAULT && directoryId != Directory.LOCAL_INVISIBLE) { builder.appendQueryParameter(ContactsContract.LIMIT_PARAM_KEY, String.valueOf(getDirectoryResultLimit())); } builder.appendQueryParameter(SearchSnippetColumns.SNIPPET_ARGS_PARAM_KEY, SNIPPET_ARGS); builder.appendQueryParameter(SearchSnippetColumns.DEFERRED_SNIPPETING_KEY,"1"); loader.setUri(builder.build()); loader.setProjection(FILTER_PROJECTION); } } else { configureUri(loader, directoryId, filter); configureProjection(loader, directoryId, filter); configureSelection(loader, directoryId, filter); } String sortOrder; if (getSortOrder() == ContactsContract.Preferences.SORT_ORDER_PRIMARY) { sortOrder = Contacts.SORT_KEY_PRIMARY; } else { sortOrder = Contacts.SORT_KEY_ALTERNATIVE; } loader.setSortOrder(sortOrder); } protected void configureUri(CursorLoader loader, long directoryId, ContactListFilter filter) { Uri uri = Contacts.CONTENT_URI; if (filter != null) { if (filter.filterType == ContactListFilter.FILTER_TYPE_GROUP) { uri = Data.CONTENT_URI; } else if (filter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) { String lookupKey = getSelectedContactLookupKey(); if (lookupKey != null) { uri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey); } else { uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, getSelectedContactId()); } } } if (directoryId == Directory.DEFAULT && isSectionHeaderDisplayEnabled()) { uri = buildSectionIndexerUri(uri); } // The "All accounts" filter is the same as the entire contents of Directory.DEFAULT if (filter != null && filter.filterType != ContactListFilter.FILTER_TYPE_CUSTOM && filter.filterType != ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) { uri = uri.buildUpon().appendQueryParameter( ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(Directory.DEFAULT)) .build(); } loader.setUri(uri); } protected void configureProjection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter != null && filter.filterType == ContactListFilter.FILTER_TYPE_GROUP) { loader.setProjection(PROJECTION_DATA); } else { loader.setProjection(PROJECTION_CONTACT); } } private void configureSelection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter == null) { return; } if (directoryId != Directory.DEFAULT) { return; } StringBuilder selection = new StringBuilder(); List<String> selectionArgs = new ArrayList<String>(); switch (filter.filterType) { case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: { // We have already added directory=0 to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: { // We have already added the lookup key to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_STARRED: { selection.append(Contacts.STARRED + "!=0"); break; } case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: { selection.append(Contacts.HAS_PHONE_NUMBER + "=1"); break; } case ContactListFilter.FILTER_TYPE_CUSTOM: { selection.append(Contacts.IN_VISIBLE_GROUP + "=1"); if (isCustomFilterForPhoneNumbersOnly()) { selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } break; } case ContactListFilter.FILTER_TYPE_ACCOUNT: { - // TODO (stopship): avoid the use of private API + // TODO: avoid the use of private API selection.append( Contacts._ID + " IN (" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM raw_contacts" + " WHERE " + RawContacts.ACCOUNT_TYPE + "=?" + " AND " + RawContacts.ACCOUNT_NAME + "=?"); selectionArgs.add(filter.accountType); selectionArgs.add(filter.accountName); if (filter.dataSet != null) { selection.append(" AND " + RawContacts.DATA_SET + "=?"); selectionArgs.add(filter.dataSet); } else { selection.append(" AND " + RawContacts.DATA_SET + " IS NULL"); } selection.append(")"); break; } case ContactListFilter.FILTER_TYPE_GROUP: { selection.append(Data.MIMETYPE + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=?"); selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE); selectionArgs.add(String.valueOf(filter.groupId)); break; } } loader.setSelection(selection.toString()); loader.setSelectionArgs(selectionArgs.toArray(new String[0])); } @Override protected void bindView(View itemView, int partition, Cursor cursor, int position) { final ContactListItemView view = (ContactListItemView)itemView; view.setHighlightedPrefix(isSearchMode() ? getUpperCaseQueryString() : null); if (isSelectionVisible()) { view.setActivated(isSelectedContact(partition, cursor)); } bindSectionHeaderAndDivider(view, position, cursor); if (isQuickContactEnabled()) { bindQuickContact(view, partition, cursor, CONTACT_PHOTO_ID_COLUMN_INDEX, CONTACT_ID_COLUMN_INDEX, CONTACT_LOOKUP_KEY_COLUMN_INDEX); } else { bindPhoto(view, partition, cursor); } bindName(view, cursor); bindPresenceAndStatusMessage(view, cursor); if (isSearchMode()) { bindSearchSnippet(view, cursor); } else { view.setSnippet(null); } } private boolean isCustomFilterForPhoneNumbersOnly() { // TODO: this flag should not be stored in shared prefs. It needs to be in the db. SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); return prefs.getBoolean(ContactsPreferences.PREF_DISPLAY_ONLY_PHONES, ContactsPreferences.PREF_DISPLAY_ONLY_PHONES_DEFAULT); } }
true
true
private void configureSelection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter == null) { return; } if (directoryId != Directory.DEFAULT) { return; } StringBuilder selection = new StringBuilder(); List<String> selectionArgs = new ArrayList<String>(); switch (filter.filterType) { case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: { // We have already added directory=0 to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: { // We have already added the lookup key to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_STARRED: { selection.append(Contacts.STARRED + "!=0"); break; } case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: { selection.append(Contacts.HAS_PHONE_NUMBER + "=1"); break; } case ContactListFilter.FILTER_TYPE_CUSTOM: { selection.append(Contacts.IN_VISIBLE_GROUP + "=1"); if (isCustomFilterForPhoneNumbersOnly()) { selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } break; } case ContactListFilter.FILTER_TYPE_ACCOUNT: { // TODO (stopship): avoid the use of private API selection.append( Contacts._ID + " IN (" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM raw_contacts" + " WHERE " + RawContacts.ACCOUNT_TYPE + "=?" + " AND " + RawContacts.ACCOUNT_NAME + "=?"); selectionArgs.add(filter.accountType); selectionArgs.add(filter.accountName); if (filter.dataSet != null) { selection.append(" AND " + RawContacts.DATA_SET + "=?"); selectionArgs.add(filter.dataSet); } else { selection.append(" AND " + RawContacts.DATA_SET + " IS NULL"); } selection.append(")"); break; } case ContactListFilter.FILTER_TYPE_GROUP: { selection.append(Data.MIMETYPE + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=?"); selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE); selectionArgs.add(String.valueOf(filter.groupId)); break; } } loader.setSelection(selection.toString()); loader.setSelectionArgs(selectionArgs.toArray(new String[0])); }
private void configureSelection( CursorLoader loader, long directoryId, ContactListFilter filter) { if (filter == null) { return; } if (directoryId != Directory.DEFAULT) { return; } StringBuilder selection = new StringBuilder(); List<String> selectionArgs = new ArrayList<String>(); switch (filter.filterType) { case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: { // We have already added directory=0 to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: { // We have already added the lookup key to the URI, which takes care of this // filter break; } case ContactListFilter.FILTER_TYPE_STARRED: { selection.append(Contacts.STARRED + "!=0"); break; } case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: { selection.append(Contacts.HAS_PHONE_NUMBER + "=1"); break; } case ContactListFilter.FILTER_TYPE_CUSTOM: { selection.append(Contacts.IN_VISIBLE_GROUP + "=1"); if (isCustomFilterForPhoneNumbersOnly()) { selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1"); } break; } case ContactListFilter.FILTER_TYPE_ACCOUNT: { // TODO: avoid the use of private API selection.append( Contacts._ID + " IN (" + "SELECT DISTINCT " + RawContacts.CONTACT_ID + " FROM raw_contacts" + " WHERE " + RawContacts.ACCOUNT_TYPE + "=?" + " AND " + RawContacts.ACCOUNT_NAME + "=?"); selectionArgs.add(filter.accountType); selectionArgs.add(filter.accountName); if (filter.dataSet != null) { selection.append(" AND " + RawContacts.DATA_SET + "=?"); selectionArgs.add(filter.dataSet); } else { selection.append(" AND " + RawContacts.DATA_SET + " IS NULL"); } selection.append(")"); break; } case ContactListFilter.FILTER_TYPE_GROUP: { selection.append(Data.MIMETYPE + "=?" + " AND " + GroupMembership.GROUP_ROW_ID + "=?"); selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE); selectionArgs.add(String.valueOf(filter.groupId)); break; } } loader.setSelection(selection.toString()); loader.setSelectionArgs(selectionArgs.toArray(new String[0])); }
diff --git a/loci/visbio/util/MatlabUtil.java b/loci/visbio/util/MatlabUtil.java index 44c2a2027..0dd5d04da 100644 --- a/loci/visbio/util/MatlabUtil.java +++ b/loci/visbio/util/MatlabUtil.java @@ -1,244 +1,244 @@ // // MatlabUtil.java // /* VisBio application for visualization of multidimensional biological image data. Copyright (C) 2002-2005 Curtis Rueden. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package loci.visbio.util; import java.rmi.RemoteException; import java.util.StringTokenizer; import loci.visbio.math.*; import visad.*; /** MatlabUtil contains useful MATLAB and Octave functions. */ public abstract class MatlabUtil { // -- Constants -- /** Variable naming scheme for MATLAB return values. */ protected static final String VAR = "visbioValue"; // -- MATLAB methods -- /** The singleton MATLAB control. */ private static MatlabControl matlab; /** Gets the singleton MATLAB interface object. */ public static MatlabControl getMatlab() { if (matlab == null) { try { matlab = new MatlabControl(); } catch (Throwable t) { } } return matlab; } /** Gets the version of MATLAB available, or null if none. */ public static String getMatlabVersion() { MatlabControl mc = getMatlab(); if (mc == null) return null; Object rval = null; try { rval = mc.blockingFeval("version", null); } catch (InterruptedException exc) { } return rval == null ? "Installed" : rval.toString(); } // -- Octave methods -- /** Gets the singleton Octave interface object. */ public static OctaveContext getOctave() { try { return OctaveContext.getInstance(); } catch (Throwable t) { return null; } } /** Gets the version of Octave available, or null if none. */ public static String getOctaveVersion() { OctaveContext cx = getOctave(); if (cx == null) return null; OctaveValueList ovl = cx.evalString("version"); return ovl.get(0).stringValue(); } // -- FlatField methods -- /** * Executes the given MATLAB/Octave function, converting the specified VisAD * FlatField into a series of 2D double arrays. Returns results as a new * FlatField. */ public static FlatField exec(String function, FlatField ff) { Set set = ff.getDomainSet(); if (!(set instanceof GriddedSet)) return null; GriddedSet gset = (GriddedSet) set; int[] len = gset.getLengths(); double[][] samples = null; try { samples = ff.getValues(false); } catch (VisADException exc) { exc.printStackTrace(); return null; } int num = samples.length; int cols = len[0]; int rows = len[1]; int size = cols * rows; // convert arguments into command string StringBuffer sb = new StringBuffer(); sb.append(function); sb.append("("); for (int i=0; i<num; i++) { if (i > 0) sb.append(","); sb.append("["); for (int j=0; j<size; j++) { if (j > 0 && j % len[0] == 0) sb.append(";"); sb.append(" "); sb.append(samples[i][j]); } sb.append("]"); } sb.append(")"); String command = sb.toString(); double[][] samps = null; - OctaveContext octave = getOctave(); - if (octave != null) { // try Octave + OctaveContext oc = getOctave(); + if (oc != null) { // try Octave // execute command - OctaveValueList ovl = octave.evalString(command); + OctaveValueList ovl = oc.evalString(command); // convert result to samples array samps = new double[ovl.size()][]; for (int i=0; i<samps.length; i++) { OctaveMatrix m = ovl.get(i).matrixValue(); samps[i] = m.toArray(); // samples are already rasterized } } - MatlabControl matlab = getMatlab(); - if (samps == null && matlab != null) { // try MATLAB + MatlabControl mc = getMatlab(); + if (samps == null && mc != null) { // try MATLAB // prepend return value variables sb = new StringBuffer(); sb.append("["); for (int i=0; i<num; i++) { sb.append(" "); sb.append(VAR); sb.append(i); } sb.append("] = "); sb.append(command); command = sb.toString(); // execute command String ans = null; - try { ans = matlab.blockingEval(command); } + try { ans = mc.blockingEval(command); } catch (InterruptedException exc) { exc.printStackTrace(); return null; } // convert result to samples array samps = new double[num][size]; StringTokenizer st = new StringTokenizer(ans); String matlabError = "Invalid MATLAB output: expected "; int v = -1, r = -1, c = -1, clo = -1, chi = -1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.startsWith(VAR)) { // parse variable name token = token.substring(VAR.length()); int n = -1; try { n = Integer.parseInt(token); } catch (NumberFormatException exc) { } String eq = st.hasMoreTokens() ? st.nextToken() : ""; if (n != v + 1 || !eq.equals("=")) { System.err.println(matlabError + "variable assignment"); return null; } v++; r = 0; c = 0; } else if (token.equals("Columns")) { // parse columns range String first = st.hasMoreTokens() ? st.nextToken() : ""; String through = st.hasMoreTokens() ? st.nextToken() : ""; String last = st.hasMoreTokens() ? st.nextToken() : ""; clo = -1; try { clo = Integer.parseInt(first) - 1; } catch (NumberFormatException exc) { } chi = -1; try { chi = Integer.parseInt(last) - 1; } catch (NumberFormatException exc) { } if (chi < clo || !through.equals("through")) { System.err.println(matlabError + "columns range"); return null; } c = clo; r = 0; } else if (v < 0) { System.err.println(matlabError + "variable assignment"); return null; } else { // parse matrix entry double value = Double.NaN; try { value = Double.parseDouble(token); } catch (NumberFormatException exc) { } if (value != value) { System.err.println(matlabError + "matrix entry"); return null; } samps[v][r * cols + c] = value; c++; if (c > chi) { r++; c = clo; } } } } try { FlatField result = new FlatField((FunctionType) ff.getType(), set); result.setSamples(samps, false); return result; } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } return null; } }
false
true
public static FlatField exec(String function, FlatField ff) { Set set = ff.getDomainSet(); if (!(set instanceof GriddedSet)) return null; GriddedSet gset = (GriddedSet) set; int[] len = gset.getLengths(); double[][] samples = null; try { samples = ff.getValues(false); } catch (VisADException exc) { exc.printStackTrace(); return null; } int num = samples.length; int cols = len[0]; int rows = len[1]; int size = cols * rows; // convert arguments into command string StringBuffer sb = new StringBuffer(); sb.append(function); sb.append("("); for (int i=0; i<num; i++) { if (i > 0) sb.append(","); sb.append("["); for (int j=0; j<size; j++) { if (j > 0 && j % len[0] == 0) sb.append(";"); sb.append(" "); sb.append(samples[i][j]); } sb.append("]"); } sb.append(")"); String command = sb.toString(); double[][] samps = null; OctaveContext octave = getOctave(); if (octave != null) { // try Octave // execute command OctaveValueList ovl = octave.evalString(command); // convert result to samples array samps = new double[ovl.size()][]; for (int i=0; i<samps.length; i++) { OctaveMatrix m = ovl.get(i).matrixValue(); samps[i] = m.toArray(); // samples are already rasterized } } MatlabControl matlab = getMatlab(); if (samps == null && matlab != null) { // try MATLAB // prepend return value variables sb = new StringBuffer(); sb.append("["); for (int i=0; i<num; i++) { sb.append(" "); sb.append(VAR); sb.append(i); } sb.append("] = "); sb.append(command); command = sb.toString(); // execute command String ans = null; try { ans = matlab.blockingEval(command); } catch (InterruptedException exc) { exc.printStackTrace(); return null; } // convert result to samples array samps = new double[num][size]; StringTokenizer st = new StringTokenizer(ans); String matlabError = "Invalid MATLAB output: expected "; int v = -1, r = -1, c = -1, clo = -1, chi = -1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.startsWith(VAR)) { // parse variable name token = token.substring(VAR.length()); int n = -1; try { n = Integer.parseInt(token); } catch (NumberFormatException exc) { } String eq = st.hasMoreTokens() ? st.nextToken() : ""; if (n != v + 1 || !eq.equals("=")) { System.err.println(matlabError + "variable assignment"); return null; } v++; r = 0; c = 0; } else if (token.equals("Columns")) { // parse columns range String first = st.hasMoreTokens() ? st.nextToken() : ""; String through = st.hasMoreTokens() ? st.nextToken() : ""; String last = st.hasMoreTokens() ? st.nextToken() : ""; clo = -1; try { clo = Integer.parseInt(first) - 1; } catch (NumberFormatException exc) { } chi = -1; try { chi = Integer.parseInt(last) - 1; } catch (NumberFormatException exc) { } if (chi < clo || !through.equals("through")) { System.err.println(matlabError + "columns range"); return null; } c = clo; r = 0; } else if (v < 0) { System.err.println(matlabError + "variable assignment"); return null; } else { // parse matrix entry double value = Double.NaN; try { value = Double.parseDouble(token); } catch (NumberFormatException exc) { } if (value != value) { System.err.println(matlabError + "matrix entry"); return null; } samps[v][r * cols + c] = value; c++; if (c > chi) { r++; c = clo; } } } } try { FlatField result = new FlatField((FunctionType) ff.getType(), set); result.setSamples(samps, false); return result; } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } return null; }
public static FlatField exec(String function, FlatField ff) { Set set = ff.getDomainSet(); if (!(set instanceof GriddedSet)) return null; GriddedSet gset = (GriddedSet) set; int[] len = gset.getLengths(); double[][] samples = null; try { samples = ff.getValues(false); } catch (VisADException exc) { exc.printStackTrace(); return null; } int num = samples.length; int cols = len[0]; int rows = len[1]; int size = cols * rows; // convert arguments into command string StringBuffer sb = new StringBuffer(); sb.append(function); sb.append("("); for (int i=0; i<num; i++) { if (i > 0) sb.append(","); sb.append("["); for (int j=0; j<size; j++) { if (j > 0 && j % len[0] == 0) sb.append(";"); sb.append(" "); sb.append(samples[i][j]); } sb.append("]"); } sb.append(")"); String command = sb.toString(); double[][] samps = null; OctaveContext oc = getOctave(); if (oc != null) { // try Octave // execute command OctaveValueList ovl = oc.evalString(command); // convert result to samples array samps = new double[ovl.size()][]; for (int i=0; i<samps.length; i++) { OctaveMatrix m = ovl.get(i).matrixValue(); samps[i] = m.toArray(); // samples are already rasterized } } MatlabControl mc = getMatlab(); if (samps == null && mc != null) { // try MATLAB // prepend return value variables sb = new StringBuffer(); sb.append("["); for (int i=0; i<num; i++) { sb.append(" "); sb.append(VAR); sb.append(i); } sb.append("] = "); sb.append(command); command = sb.toString(); // execute command String ans = null; try { ans = mc.blockingEval(command); } catch (InterruptedException exc) { exc.printStackTrace(); return null; } // convert result to samples array samps = new double[num][size]; StringTokenizer st = new StringTokenizer(ans); String matlabError = "Invalid MATLAB output: expected "; int v = -1, r = -1, c = -1, clo = -1, chi = -1; while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.startsWith(VAR)) { // parse variable name token = token.substring(VAR.length()); int n = -1; try { n = Integer.parseInt(token); } catch (NumberFormatException exc) { } String eq = st.hasMoreTokens() ? st.nextToken() : ""; if (n != v + 1 || !eq.equals("=")) { System.err.println(matlabError + "variable assignment"); return null; } v++; r = 0; c = 0; } else if (token.equals("Columns")) { // parse columns range String first = st.hasMoreTokens() ? st.nextToken() : ""; String through = st.hasMoreTokens() ? st.nextToken() : ""; String last = st.hasMoreTokens() ? st.nextToken() : ""; clo = -1; try { clo = Integer.parseInt(first) - 1; } catch (NumberFormatException exc) { } chi = -1; try { chi = Integer.parseInt(last) - 1; } catch (NumberFormatException exc) { } if (chi < clo || !through.equals("through")) { System.err.println(matlabError + "columns range"); return null; } c = clo; r = 0; } else if (v < 0) { System.err.println(matlabError + "variable assignment"); return null; } else { // parse matrix entry double value = Double.NaN; try { value = Double.parseDouble(token); } catch (NumberFormatException exc) { } if (value != value) { System.err.println(matlabError + "matrix entry"); return null; } samps[v][r * cols + c] = value; c++; if (c > chi) { r++; c = clo; } } } } try { FlatField result = new FlatField((FunctionType) ff.getType(), set); result.setSamples(samps, false); return result; } catch (VisADException exc) { exc.printStackTrace(); } catch (RemoteException exc) { exc.printStackTrace(); } return null; }
diff --git a/hot-deploy/opentaps-common/src/common/org/opentaps/common/domain/product/ProductRepository.java b/hot-deploy/opentaps-common/src/common/org/opentaps/common/domain/product/ProductRepository.java index 48cb685f2..7a02a69d2 100644 --- a/hot-deploy/opentaps-common/src/common/org/opentaps/common/domain/product/ProductRepository.java +++ b/hot-deploy/opentaps-common/src/common/org/opentaps/common/domain/product/ProductRepository.java @@ -1,152 +1,152 @@ /* * Copyright (c) 2008 - 2009 Open Source Strategies, Inc. * * Opentaps 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. * * Opentaps 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 Opentaps. If not, see <http://www.gnu.org/licenses/>. */ package org.opentaps.common.domain.product; import java.math.BigDecimal; import java.util.List; import java.util.Map; import org.ofbiz.base.util.UtilMisc; import org.ofbiz.base.util.UtilValidate; import org.ofbiz.entity.GenericValue; import org.ofbiz.entity.condition.EntityCondition; import org.ofbiz.entity.condition.EntityConditionList; import org.ofbiz.entity.condition.EntityOperator; import org.ofbiz.entity.util.EntityUtil; import org.ofbiz.service.GenericServiceException; import org.ofbiz.service.ServiceUtil; import org.opentaps.domain.base.entities.GoodIdentification; import org.opentaps.domain.base.entities.ProductAssoc; import org.opentaps.domain.base.services.GetProductByComprehensiveSearch; import org.opentaps.domain.product.Product; import org.opentaps.domain.product.ProductRepositoryInterface; import org.opentaps.foundation.entity.Entity; import org.opentaps.foundation.entity.EntityNotFoundException; import org.opentaps.foundation.entity.hibernate.Query; import org.opentaps.foundation.entity.hibernate.Session; import org.opentaps.foundation.infrastructure.InfrastructureException; import org.opentaps.foundation.repository.RepositoryException; import org.opentaps.foundation.repository.ofbiz.Repository; /** {@inheritDoc} */ public class ProductRepository extends Repository implements ProductRepositoryInterface { /** * Default constructor. */ public ProductRepository() { super(); } /** {@inheritDoc} */ public Product getProductById(String productId) throws RepositoryException, EntityNotFoundException { if (UtilValidate.isEmpty(productId)) { return null; } return findOneNotNull(Product.class, map(Product.Fields.productId, productId), "OpentapsError_ProductNotFound", UtilMisc.toMap("productId", productId)); } /** {@inheritDoc} */ public BigDecimal getUnitPrice(Product product, String currencyUomId) throws RepositoryException { return getUnitPrice(product, null, currencyUomId, null); } /** {@inheritDoc} */ public BigDecimal getUnitPrice(Product product, BigDecimal quantity, String currencyUomId, String partyId) throws RepositoryException { try { Map<String, ?> results = getDispatcher().runSync("calculateProductPrice", UtilMisc.toMap( "userLogin", getUser().getOfbizUserLogin(), "product", Repository.genericValueFromEntity(product), "partyId", partyId, "quantity", quantity, "currencyUomId", currencyUomId), -1, false); if (ServiceUtil.isError(results)) { throw new RepositoryException(ServiceUtil.getErrorMessage(results)); } return (BigDecimal) results.get("price"); } catch (GenericServiceException e) { throw new RepositoryException(e); } } /** {@inheritDoc} */ @SuppressWarnings("unchecked") public BigDecimal getStandardCost(Product product, String currencyUomId) throws RepositoryException { try { Map results = getDispatcher().runSync("getProductCost", UtilMisc.toMap( "userLogin", getUser().getOfbizUserLogin(), "productId", product.getProductId(), "currencyUomId", currencyUomId, "costComponentTypePrefix", "EST_STD")); if (ServiceUtil.isError(results)) { throw new RepositoryException(ServiceUtil.getErrorMessage(results)); } return (BigDecimal) results.get("productCost"); } catch (GenericServiceException e) { throw new RepositoryException(e); } } /** {@inheritDoc} */ public List<Product> getVariants(Product product) throws RepositoryException { EntityConditionList<EntityCondition> conditions = EntityCondition.makeCondition(EntityOperator.AND, EntityCondition.makeCondition(ProductAssoc.Fields.productId.name(), product.getProductId()), EntityCondition.makeCondition(ProductAssoc.Fields.productAssocTypeId.name(), "PRODUCT_VARIANT"), EntityUtil.getFilterByDateExpr()); List<ProductAssoc> variants = findList(ProductAssoc.class, conditions); return findList(Product.class, EntityCondition.makeCondition(Product.Fields.productId.name(), EntityOperator.IN, Entity.getDistinctFieldValues(variants, ProductAssoc.Fields.productIdTo))); } /** {@inheritDoc} */ public Product getProductByComprehensiveSearch(String id) throws RepositoryException { try { Product product = null; // use Pojo service wrappers to call GetProductByComprehensiveSearch service GetProductByComprehensiveSearch service = new GetProductByComprehensiveSearch(); service.setInProductId(id); Map results = getDispatcher().runSync(service.name(), service.inputMap()); if (!(ServiceUtil.isError(results) || ServiceUtil.isFailure(results))) { service.putAllOutput(results); GenericValue productGv = service.getOutProduct(); if (productGv != null) { // construct Product domain object and return - product = loadFromGeneric(Product.class, productGv); + product = loadFromGeneric(Product.class, productGv, this); } } return product; } catch (GenericServiceException e) { throw new RepositoryException(e); } } /** {@inheritDoc} */ public List<GoodIdentification> getAlternateProductIds(String productId) throws RepositoryException { String hql = "from GoodIdentification eo where eo.id.productId = :productId"; try { Session session = getInfrastructure().getSession(); Query query = session.createQuery(hql); query.setParameter("productId", productId); List<GoodIdentification> goodIdentifications = query.list(); return goodIdentifications; } catch (InfrastructureException e) { throw new RepositoryException(e); } } }
true
true
public Product getProductByComprehensiveSearch(String id) throws RepositoryException { try { Product product = null; // use Pojo service wrappers to call GetProductByComprehensiveSearch service GetProductByComprehensiveSearch service = new GetProductByComprehensiveSearch(); service.setInProductId(id); Map results = getDispatcher().runSync(service.name(), service.inputMap()); if (!(ServiceUtil.isError(results) || ServiceUtil.isFailure(results))) { service.putAllOutput(results); GenericValue productGv = service.getOutProduct(); if (productGv != null) { // construct Product domain object and return product = loadFromGeneric(Product.class, productGv); } } return product; } catch (GenericServiceException e) { throw new RepositoryException(e); } }
public Product getProductByComprehensiveSearch(String id) throws RepositoryException { try { Product product = null; // use Pojo service wrappers to call GetProductByComprehensiveSearch service GetProductByComprehensiveSearch service = new GetProductByComprehensiveSearch(); service.setInProductId(id); Map results = getDispatcher().runSync(service.name(), service.inputMap()); if (!(ServiceUtil.isError(results) || ServiceUtil.isFailure(results))) { service.putAllOutput(results); GenericValue productGv = service.getOutProduct(); if (productGv != null) { // construct Product domain object and return product = loadFromGeneric(Product.class, productGv, this); } } return product; } catch (GenericServiceException e) { throw new RepositoryException(e); } }
diff --git a/src/java/com/idega/block/news/presentation/NewsEditorWindow.java b/src/java/com/idega/block/news/presentation/NewsEditorWindow.java index 1944198..8d32a55 100644 --- a/src/java/com/idega/block/news/presentation/NewsEditorWindow.java +++ b/src/java/com/idega/block/news/presentation/NewsEditorWindow.java @@ -1,783 +1,783 @@ package com.idega.block.news.presentation; import java.io.IOException; import java.rmi.RemoteException; import java.sql.SQLException; import java.sql.Timestamp; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Vector; import com.idega.block.media.presentation.ImageInserter; import com.idega.block.news.business.NewsBusiness; import com.idega.block.news.business.NewsFinder; import com.idega.block.news.data.NewsCategoryAttribute; import com.idega.block.news.data.NwNews; import com.idega.block.text.business.ContentBusiness; import com.idega.block.text.business.ContentFinder; import com.idega.block.text.business.ContentHelper; import com.idega.block.text.business.TextFinder; import com.idega.block.text.data.Content; import com.idega.block.text.data.LocalizedText; import com.idega.core.business.CategoryFinder; import com.idega.core.data.ICCategory; import com.idega.core.data.ICFile; import com.idega.core.localisation.business.ICLocaleBusiness; import com.idega.core.localisation.presentation.ICLocalePresentation; import com.idega.core.user.data.User; import com.idega.idegaweb.IWBundle; import com.idega.idegaweb.IWResourceBundle; import com.idega.idegaweb.presentation.IWAdminWindow; import com.idega.presentation.IWContext; import com.idega.presentation.Image; import com.idega.presentation.Table; import com.idega.presentation.text.Link; import com.idega.presentation.text.Text; import com.idega.presentation.texteditor.TextEditor; import com.idega.presentation.ui.CloseButton; import com.idega.presentation.ui.DropdownMenu; import com.idega.presentation.ui.HiddenInput; import com.idega.presentation.ui.Parameter; import com.idega.presentation.ui.SubmitButton; import com.idega.presentation.ui.TextArea; import com.idega.presentation.ui.TextInput; import com.idega.presentation.ui.TimestampInput; import com.idega.util.IWTimestamp; /** * Title: * Description: * Copyright: Copyright (c) 2000-2001 idega.is All Rights Reserved * Company: idega *@author <a href="mailto:[email protected]">Aron Birkir</a> * @version 1.1 */ public class NewsEditorWindow extends IWAdminWindow{ private final static String IW_BUNDLE_IDENTIFIER="com.idega.block.news"; private String Error; private boolean isAdmin=false; private int iUserId = -1; private User eUser = null; private int iObjInsId = -1; private int defaultPublishDays = 50; private int SAVECATEGORY = 1,SAVENEWS = 2; private static String YEARS_AHEAD_PROPERTY = "publish_to_years"; private static String prmHeadline = "nwep_headline"; private static String prmTeaser = "nwep_teaser"; private static String prmAuthor = "nwep_author"; private static String prmSource = "nwep_source"; private static String prmDaysshown = "nwep_daysshown"; private static String prmBody = "nwe_body"; public static String prmCategory = "nwep_category"; private static String prmLocale = "nwep_locale"; private static String prmLocalizedTextId = "nwep_loctextid"; public static String prmObjInstId = "nwep_icobjinstid"; public static String prmAttribute = "nwep_attribute"; private static String prmUseImage = "insertImage";//nwep.useimage public static String prmDelete = "nwep_txdeleteid"; private static String prmImageId = "nwep_imageid"; public static String prmNwNewsId = "nwep_nwnewsid"; private static String actDelete = "nwea_delete"; private static String actSave = "nwea_save"; private static String actClose = "nwea_close"; private static String modeDelete = "nwem_delete"; private static String prmFormProcess = "nwe_formprocess"; private static String prmNewCategory = "nwep_newcategory"; private static String prmEditCategory = "nwep_editcategory"; private static String prmDeleteFile = "nwep_deletefile"; private static String prmSaveFile = "nwep_savefile"; private static String prmCatName= "nwep_categoryname"; private static String prmCatDesc = "nwep_categorydesc"; private static String prmPubFrom = "nwep_publishfrom"; private static String prmPubTo = "nwep_publishto"; private static String prmNewsDate = "nwep_newsdate"; private static String prmMoveToCat = "nwep_movtocat"; public static final String imageAttributeKey = "newsimage"; private String sNewsId = null; private int iCategoryId = -1; private String sEditor,sHeadline,sTeaser,sNews,sNewsDate,sCategory,sAuthor,sSource,sDaysShown,sImage,sLocale,sPublisFrom,sPublisTo; private int attributeId = 3; private IWBundle iwb,core; private IWResourceBundle iwrb; public NewsEditorWindow(){ setWidth(570); setHeight(620); setResizable(true); setScrollbar(true); setUnMerged(); } private void init(){ sHeadline = iwrb.getLocalizedString("headline","Headline"); sLocale = iwrb.getLocalizedString("locale","Locale"); sTeaser = iwrb.getLocalizedString("teaser","Teaser"); sNews = iwrb.getLocalizedString("news","News"); sCategory = iwrb.getLocalizedString("category","Category"); sAuthor = iwrb.getLocalizedString("author","Author"); sSource = iwrb.getLocalizedString("source","Source"); sDaysShown = iwrb.getLocalizedString("visible_days","Number of days visible"); sImage = iwrb.getLocalizedString("image","Image"); sEditor = iwrb.getLocalizedString("news_editor","News Editor"); sPublisFrom = iwrb.getLocalizedString("publish_from","Publish from"); sPublisTo = iwrb.getLocalizedString("publish_to","Publish to"); sNewsDate = iwrb.getLocalizedString("news_date","News date"); setAllMargins(0); setTitle(sEditor); } private void control(IWContext iwc)throws Exception{ init(); //debugParameters(iwc); boolean doView = true; Locale currentLocale = iwc.getCurrentLocale(),chosenLocale; if(iwc.isParameterSet(actClose) || iwc.isParameterSet(actClose+".x")){ setParentToReload(); close(); } else{ String sLocaleId = iwc.getParameter(prmLocale); String sCategoryId = iwc.getParameter(prmCategory); iCategoryId = sCategoryId !=null?Integer.parseInt(sCategoryId):-1; int saveInfo = getSaveInfo(iwc); // LocaleHandling int iLocaleId = -1; if(sLocaleId!= null){ iLocaleId = Integer.parseInt(sLocaleId); chosenLocale = NewsFinder.getLocale(iLocaleId); } else{ chosenLocale = currentLocale; iLocaleId = ICLocaleBusiness.getLocaleId(chosenLocale); } if ( isAdmin ) { // end of LocaleHandling // Text initialization String sAttribute = null; String sLocTextId = iwc.getParameter(prmLocalizedTextId); String sObjInstId = iwc.getParameter(prmObjInstId); sAttribute = iwc.getParameter(prmAttribute); if(sObjInstId!=null) iObjInsId = Integer.parseInt(sObjInstId); // News Id Request : if(iwc.getParameter(prmNwNewsId) != null){ sNewsId = iwc.getParameter(prmNwNewsId); } // Delete Request : else if(iwc.getParameter(prmDelete)!=null){ sNewsId = iwc.getParameter(prmDelete); confirmDelete(sNewsId,iObjInsId); doView = false; } // Object Instance Request : else if(sObjInstId!=null){ //doView = false; if(iObjInsId > 0 && saveInfo != SAVECATEGORY) iCategoryId = CategoryFinder.getInstance().getObjectInstanceCategoryId(iObjInsId ); } //add("category id "+iCategoryId); //add(" instance id "+iObjInsId); // end of News initialization // Form processing if(saveInfo == SAVENEWS) processForm(iwc,sNewsId,sLocTextId, sCategoryId); else if(saveInfo == SAVECATEGORY) processCategoryForm(iwc,sCategoryId,iObjInsId); /* old stuff if(iwc.isParameterSet(prmObjInstId)){ addCategoryFields(CategoryFinder.getInstance().getCategory(iCategoryId),iObjInsId ); } */ //doView = false; if(doView) doViewNews(sNewsId,sAttribute,chosenLocale,iLocaleId,iCategoryId ); } else { noAccess(); } } } private int getSaveInfo(IWContext iwc){ if(iwc.getParameter(prmFormProcess)!=null){ if(iwc.getParameter(prmFormProcess).equals("Y")) return SAVENEWS; else if(iwc.getParameter(prmFormProcess).equals("C")) return SAVECATEGORY; //doView = false; } return 0; } private Parameter getParameterSaveNews(){ return new Parameter(prmFormProcess,"Y"); } private Parameter getParameterSaveCategory(){ return new Parameter(prmFormProcess,"C"); } // Form Processing : private void processForm(IWContext iwc,String sNewsId,String sLocTextId,String sCategory){ // Save : if(iwc.getParameter(actSave)!=null || iwc.getParameter(actSave+".x")!=null ){ iwc.getApplication().getIWCacheManager().invalidateCache(NewsReader.CACHE_KEY); saveNews(iwc,sNewsId,sLocTextId,sCategory); } // Delete : else if(iwc.getParameter( actDelete )!=null || iwc.getParameter(actDelete+".x")!=null){ iwc.getApplication().getIWCacheManager().invalidateCache(NewsReader.CACHE_KEY); try { if(iwc.getParameter(modeDelete)!=null){ int I = Integer.parseInt(iwc.getParameter(modeDelete)); deleteNews(I); } } catch (Exception ex) { ex.printStackTrace(); } } else if(iwc.getParameter(prmDeleteFile)!=null){ if(sNewsId!=null){ String sFileId = iwc.getParameter(prmDeleteFile); deleteFile(sNewsId,sFileId); } } else if(iwc.getParameter(prmSaveFile)!= null || iwc.getParameter(prmSaveFile+".x")!=null){ if(sNewsId!=null){ String sFileId = iwc.getParameter(prmImageId); saveFile(sNewsId,sFileId); } } // New: /** @todo make possible */ /*else if(iwc.getParameter( actNew ) != null || iwc.getParameter(actNew+".x")!= null){ sNewsId = null; } */ // end of Form Actions } private void processCategoryForm(IWContext iwc,String sCategoryId,int iObjInsId){ String sName = iwc.getParameter(prmCatName); String sDesc = iwc.getParameter(prmCatDesc); String sMoveCat = iwc.getParameter(prmMoveToCat); int iMoveCat = sMoveCat !=null ? Integer.parseInt(sMoveCat):-1; int iCatId = sCategoryId != null ? Integer.parseInt(sCategoryId):-1; if(iwc.getParameter(actSave)!=null || iwc.getParameter(actSave+".x")!=null ){ if(sName!=null){ //System.err.println("saving CATId = "+iCatId +" ObjInstId = "+iObjInsId); try{ NewsBusiness.saveNewsCategory(iCatId,sName,sDesc,iObjInsId); if(iMoveCat > 0){ NewsBusiness.moveNewsBetweenCategories(iCatId,iMoveCat); } }catch(RemoteException ex){ex.printStackTrace();} } } else if(iwc.getParameter(actDelete)!=null || iwc.getParameter(actDelete+".x")!=null ){ //System.err.println("deleteing CATId = "+iCatId +" ObjInstId = "+iObjInsId); NewsBusiness.deleteNewsCategory(iCatId); } } private void doViewNews(String sNewsId,String sAttribute,Locale locale,int iLocaleId,int iCategoryId){ ContentHelper contentHelper = null; NwNews news = null; if(sNewsId != null){ int iNewsId = Integer.parseInt(sNewsId); news = NewsFinder.getNews(iNewsId); if(news != null && locale != null) contentHelper = ContentFinder.getContentHelper(news.getContentId(),locale); } addNewsFields(news,contentHelper,iLocaleId,iObjInsId,iCategoryId); } private void saveNews(IWContext iwc,String sNwNewsId,String sLocalizedTextId,String sCategoryId){ String sHeadline = iwc.getParameter( prmHeadline ); String sTeaser = iwc.getParameter( prmTeaser); String sBody = iwc.getParameter(prmBody ); String sImageId = iwc.getParameter(prmImageId); String sLocaleId = iwc.getParameter(prmLocale); String sAuthor = iwc.getParameter(prmAuthor); String sSource = iwc.getParameter(prmSource); String sPubFrom = iwc.getParameter(prmPubFrom); String sPubTo = iwc.getParameter(prmPubTo); String sNewsDate = iwc.getParameter(prmNewsDate); //System.err.println("publish from" + sPubFrom); //System.err.println("publish to" + sPubTo); if(sHeadline != null || sBody != null){ int iNwNewsId = sNwNewsId!=null?Integer.parseInt(sNwNewsId): -1; int iLocalizedTextId = sLocalizedTextId != null ? Integer.parseInt(sLocalizedTextId): -1; int iLocaleId = sLocaleId != null ? Integer.parseInt(sLocaleId):-1; int iImageId = sImageId != null ? Integer.parseInt(sImageId):-1; int iCategoryId = sCategoryId !=null ? Integer.parseInt(sCategoryId):-1; IWTimestamp today = IWTimestamp.RightNow(); IWTimestamp pubFrom = sPubFrom!=null ? new IWTimestamp(sPubFrom):today; Timestamp newsDate = sNewsDate != null ? new IWTimestamp(sNewsDate).getTimestamp() : null; today.addDays(defaultPublishDays); IWTimestamp pubTo = sPubTo!=null ?new IWTimestamp(sPubTo):today; Vector V = null; ICFile F = null; if(iImageId > 0){ try { /** @todo use finder */ F = ((com.idega.core.data.ICFileHome)com.idega.data.IDOLookup.getHome(ICFile.class)).findByPrimaryKey(new Integer(iImageId)); V = new Vector(1); V.add(F); } catch (Exception ex) { ex.printStackTrace(); } } //System.err.println(pubFrom.toSQLString()); //System.err.println(pubTo.toString()); NwNews news = NewsBusiness.saveNews(iNwNewsId,iLocalizedTextId,iCategoryId ,sHeadline,sTeaser,sAuthor,sSource,sBody,iLocaleId,iUserId,iObjInsId,pubFrom.getTimestamp(),pubTo.getTimestamp(),V, newsDate); if(news!=null) sNewsId = String.valueOf(news.getID()); } } private void saveFile(String sNewsId,String sFileId){ NwNews nw = NewsFinder.getNews(Integer.parseInt(sNewsId)); ContentBusiness.addFileToContent(nw.getContentId(),Integer.parseInt(sFileId)); } private void deleteFile(String sNewsId,String sFileId){ NwNews nw = NewsFinder.getNews(Integer.parseInt(sNewsId)); ContentBusiness.removeFileFromContent(nw.getContentId(),Integer.parseInt(sFileId)); } private void deleteNews(int iNewsId ) { NewsBusiness.deleteNews(iNewsId); setParentToReload(); close(); } public String getColumnString(NewsCategoryAttribute[] attribs){ String values = ""; for (int i = 0 ; i < attribs.length ; i++) { values += com.idega.block.news.data.NewsCategoryBMPBean.getColumnName()+"_id = '"+attribs[i].getNewsCategoryId()+"'" ; if( i!= (attribs.length-1) ) values += " OR "; } return values; } public Text getHeaderText(String s){ Text textTemplate = new Text(s); textTemplate.setFontSize(Text.FONT_SIZE_7_HTML_1); textTemplate.setBold(); textTemplate.setFontFace(Text.FONT_FACE_VERDANA); return textTemplate; } private void addCategoryFields(ICCategory newsCategory,int iObjInst){ String sCategory= iwrb.getLocalizedString("category","Category"); String sName = iwrb.getLocalizedString("name","Name"); String sDesc = iwrb.getLocalizedString("description","Description"); String sMoveCat = iwrb.getLocalizedString("movenews","Move news to"); List L = NewsFinder.listOfValidNewsCategories(); DropdownMenu catDrop = new DropdownMenu(L,prmCategory); catDrop.addMenuElementFirst("-1",sCategory); catDrop.setToSubmit(); DropdownMenu MoveCatDrop = new DropdownMenu(L,prmMoveToCat); MoveCatDrop.addMenuElementFirst("-1",sCategory); Link newLink = new Link(iwb.getImage("/shared/create.gif")); newLink.addParameter(prmCategory,-1); newLink.addParameter(prmObjInstId,iObjInst); newLink.addParameter(prmFormProcess,"C"); boolean hasCategory = newsCategory !=null ? true:false; TextInput tiName = new TextInput(prmCatName); tiName.setLength(40); tiName.setMaxlength(255); Table catTable = new Table(5,1); catTable.setCellpadding(0); catTable.setCellspacing(0); setStyle(catDrop); catTable.add(catDrop,1,1); catTable.add(newLink,3,1); catTable.setWidth(2,1,"20"); catTable.setWidth(4,1,"20"); TextArea taDesc = new TextArea(prmCatDesc,65,5); if(hasCategory){ int id = newsCategory.getID(); catDrop.setSelectedElement(String.valueOf(newsCategory.getID())); if(newsCategory.getName()!=null) tiName.setContent(newsCategory.getName()); if(newsCategory.getDescription()!=null) taDesc.setContent(newsCategory.getDescription()); addHiddenInput(new HiddenInput(prmCategory ,String.valueOf(id))); int iNewsCount = NewsFinder.countNewsInCategory(id); int iUnPublishedCount = NewsFinder.countNewsInCategory(id,NewsFinder.UNPUBLISHED); int iPublishingCount = NewsFinder.countNewsInCategory(id,NewsFinder.PUBLISHISING); int iPublishedCount = NewsFinder.countNewsInCategory(id,NewsFinder.PUBLISHED); String sNewsCount = iwrb.getLocalizedString("newscount","News count"); String sUnPublishedCount = iwrb.getLocalizedString("unpublished","Unpublished"); String sPublishingCount = iwrb.getLocalizedString("publishing","In publish"); String sPublishedCount = iwrb.getLocalizedString("published","Published"); Table table = new Table(3,4); table.setCellpadding(2); table.setCellspacing(1); table.setWidth(2,"10"); String colon = " : "; table.add(formatText(sNewsCount+colon),1,1); table.add(String.valueOf(iNewsCount),3,1); table.add(formatText(sUnPublishedCount+colon),1,2); table.add(String.valueOf(iUnPublishedCount),3,2); table.add(formatText(sPublishingCount+colon),1,3); table.add(String.valueOf(iPublishingCount),3,3); table.add(formatText(sPublishedCount+colon),1,4); table.add(String.valueOf(iPublishedCount),3,4); String sInfo = iwrb.getLocalizedString("info","Info"); addRight(sInfo,table,false,false); if(iNewsCount == 0){ Link deleteLink = new Link(iwb.getImage("/shared/delete.gif")); deleteLink.addParameter(actDelete,"true"); deleteLink.addParameter(prmCategory,newsCategory.getID()); deleteLink.addParameter(prmObjInstId,iObjInst); deleteLink.addParameter(prmFormProcess,"C"); catTable.add(deleteLink,5,1); } } addLeft(sCategory,catTable,true,false); addLeft(sName,tiName,true); addLeft(sDesc,taDesc,true); if(hasCategory) addLeft(sMoveCat,MoveCatDrop,true); SubmitButton save = new SubmitButton(iwrb.getLocalizedImageButton("save","Save"),actSave); SubmitButton close = new SubmitButton(iwrb.getLocalizedImageButton("close","Close"),actClose); addSubmitButton(save); addSubmitButton(close); addHiddenInput( new HiddenInput (prmObjInstId,String.valueOf(iObjInst))); addHiddenInput( new HiddenInput (prmFormProcess,"C")); } private void addNewsFields(NwNews nwNews ,ContentHelper contentHelper, int iLocaleId,int iObjInsId,int iCategoryId){ LocalizedText locText = null; boolean hasContent = ( contentHelper != null) ? true:false; if(hasContent) locText = contentHelper.getLocalizedText(TextFinder.getLocale(iLocaleId)); boolean hasNwNews = ( nwNews != null ) ? true: false; boolean hasLocalizedText = ( locText != null ) ? true: false; TextInput tiHeadline = new TextInput(prmHeadline); tiHeadline.setLength(40); tiHeadline.setMaxlength(255); IWTimestamp now = IWTimestamp.RightNow(); TimestampInput publishFrom = new TimestampInput(prmPubFrom,true); publishFrom.setTimestamp(now.getTimestamp()); TimestampInput newsDate = new TimestampInput(prmNewsDate,true); newsDate.setTimestamp(now.getTimestamp()); newsDate.setYearRange(now.getYear()-4,now.getYear()+2); // add default publishing days: int addYears = 0; try { addYears = Integer.parseInt(iwb.getProperty(YEARS_AHEAD_PROPERTY, "0")); } catch (NullPointerException ne) { addYears = 0; } catch (NumberFormatException nfe) { addYears = 0; } now.addYears(addYears); TimestampInput publishTo = new TimestampInput(prmPubTo,true); publishTo.setTimestamp(now.getTimestamp()); DropdownMenu LocaleDrop = ICLocalePresentation.getLocaleDropdownIdKeyed(prmLocale); LocaleDrop.setToSubmit(); LocaleDrop.setSelectedElement(Integer.toString(iLocaleId)); //TextArea taBody = new TextArea(prmBody,65,18); TextEditor taBody = new TextEditor(); taBody.setInputName(prmBody); TextArea taTeaser = new TextArea(prmTeaser,65,2); List cats = CategoryFinder.getInstance().listOfCategoryForObjectInstanceId(iObjInsId); DropdownMenu catDrop = new DropdownMenu(cats,prmCategory); //catDrop.addMenuElementFirst("-1",sCategory); TextInput tiAuthor = new TextInput(prmAuthor); tiAuthor.setLength(22); tiAuthor.setMaxlength(255); TextInput tiSource = new TextInput(prmSource); tiAuthor.setLength(22); tiAuthor.setMaxlength(255); //DropdownMenu drpDaysShown = counterDropdown(prmDaysshown, 1, 30); //drpDaysShown.addMenuElementFirst("-1", iwrb.getLocalizedString("undetermined","Undetermined") ); /* ImageInserter imageInsert = new ImageInserter(); imageInsert.setImSessionImageName(prmImageId); Link propslink = null; */ // Fill or not Fill if ( hasLocalizedText ) { if ( locText.getHeadline() != null ) { tiHeadline.setContent(locText.getHeadline()); } if ( locText.getTitle() != null ) { taTeaser.setContent(locText.getTitle()); } if ( locText.getBody() != null ) { taBody.setContent(locText.getBody()); } addHiddenInput(new HiddenInput(prmLocalizedTextId,String.valueOf(locText.getID()))); } if( hasNwNews ){ if("".equals(nwNews.getAuthor())&& eUser !=null) tiAuthor.setContent(eUser.getFirstName()); else tiAuthor.setContent(nwNews.getAuthor()); tiSource.setContent(nwNews.getSource()); //drpCategories.setSelectedElement(String.valueOf(nwNews.getNewsCategoryId())); if ( hasContent ) { /* List files = contentHelper.getFiles(); if(files != null){ ICFile file1 = (ICFile) files.get(0); imageInsert.setImageId(file1.getID()); Text properties = new Text("properties"); propslink = com.idega.block.media.presentation.ImageAttributeSetter.getLink(properties,file1.getID(),imageAttributeKey); } */ Content content = contentHelper.getContent(); if(content.getPublishFrom()!=null){ publishFrom.setTimestamp(content.getPublishFrom()); } if(content.getPublishTo()!=null){ publishTo.setTimestamp(content.getPublishTo()); } if(content.getLastUpdated()!=null){ newsDate.setTimestamp(content.getLastUpdated()); } } catDrop.setSelectedElement(String.valueOf(nwNews.getNewsCategoryId())); addHiddenInput(new HiddenInput(prmNwNewsId,Integer.toString(nwNews.getID()))); //addHiddenInput(new HiddenInput(prmCategory ,String.valueOf(nwNews.getNewsCategoryId()))); } else{ if( eUser !=null){ tiAuthor.setContent(eUser.getFirstName()); } IWTimestamp today = IWTimestamp.RightNow(); publishFrom.setTimestamp(today.getTimestamp()); if (addYears > 0) today.addYears(addYears); else today.addDays(defaultPublishDays); publishTo.setTimestamp(today.getTimestamp()); addHiddenInput(new HiddenInput(prmCategory ,String.valueOf(iCategoryId))); } addHiddenInput(new HiddenInput(prmObjInstId ,String.valueOf(iObjInsId))); SubmitButton addButton = new SubmitButton(core.getImage("/shared/create.gif","Add to news"),prmSaveFile); //SubmitButton leftButton = new SubmitButton(core.getImage("/shared/frew.gif","Insert image"),prmSaveFile); ImageInserter imageInsert = new ImageInserter(); imageInsert.setImSessionImageName(prmImageId); imageInsert.setUseBoxParameterName(prmUseImage); imageInsert.setMaxImageWidth(130); imageInsert.setHasUseBox(false); imageInsert.setSelected(false); Table imageTable = new Table(); int row = 1; //imageTable.mergeCells(1,row,3,row); //imageTable.add(formatText(iwrb.getLocalizedString("image","Chosen image :")),1,row++); imageTable.mergeCells(1,row,3,row); imageTable.add(imageInsert,1,row++); imageTable.mergeCells(1,row,3,row); //imageTable.add(leftButton,1,row); imageTable.add(addButton,1,row++); if ( hasContent ) { List files = contentHelper.getFiles(); - if(files != null){ + if(files != null && !files.isEmpty()){ imageTable.mergeCells(1,row,3,row); imageTable.add( formatText(iwrb.getLocalizedString("newsimages","News images :")),1,row++); ICFile file1 = (ICFile) files.get(0); imageInsert.setImageId(((Integer)file1.getPrimaryKey()).intValue()); Iterator I = files.iterator(); while(I.hasNext()){ try { ICFile f = (ICFile) I.next(); Image immi = new Image(((Integer)f.getPrimaryKey()).intValue()); immi.setMaxImageWidth(50); imageTable.add(immi,1,row); //Link edit = new Link(iwb.getImage("/shared/edit.gif")); Link edit = com.idega.block.image.presentation.ImageAttributeSetter.getLink(iwb.getImage("/shared/edit.gif"),((Integer)file1.getPrimaryKey()).intValue(),imageAttributeKey); Link delete = new Link(core.getImage("/shared/delete.gif")); delete.addParameter(prmDeleteFile,f.getPrimaryKey().toString()); delete.addParameter(prmNwNewsId,nwNews.getID()); delete.addParameter(getParameterSaveNews()); imageTable.add(edit,2,row); imageTable.add(delete,3,row); row++; } catch (Exception ex) { } } } } addLeft(sHeadline,tiHeadline,true); addLeft(sLocale, LocaleDrop,true); addLeft(sTeaser,taTeaser,true); addLeft(sNews,taBody,true); addLeft(sNewsDate,newsDate,true); addLeft(sPublisFrom, publishFrom,true); addLeft(sPublisTo,publishTo,true); addRight(sCategory,catDrop,true); addRight(sAuthor,tiAuthor,true); addRight(sSource,tiSource,true); //addRight(iwrb.getLocalizedString("image","Image"),imageInsert,true); //if(addButton!=null){ //addRight("",addButton,true,false); //} addRight(iwrb.getLocalizedString("images","Images"),imageTable,true,false); /* addRight(sImage,imageInsert,true); if(propslink != null) addRight("props",propslink,true); */ SubmitButton save = new SubmitButton(iwrb.getLocalizedImageButton("save","Save"),actSave); SubmitButton close = new SubmitButton(iwrb.getLocalizedImageButton("close","Close"),actClose); addSubmitButton(save); addSubmitButton(close); addHiddenInput( new HiddenInput (prmFormProcess,"Y")); } private void deleteCat(int iCatId){ } private void confirmDelete(String sNewsId,int iObjInsId ) throws IOException,SQLException { int iNewsId = Integer.parseInt(sNewsId); NwNews nwNews = NewsFinder.getNews(iNewsId); if ( nwNews != null ) { addLeft(iwrb.getLocalizedString("news_to_delete","News to delete")); addLeft(iwrb.getLocalizedString("confirm_delete","Are you sure?")); //addSubmitButton(new SubmitButton(iwrb.getImage("delete.gif"),actDelete)); addSubmitButton(new SubmitButton(iwrb.getLocalizedImageButton("delete","Delete"),actDelete)); addHiddenInput(new HiddenInput(modeDelete,String.valueOf(nwNews.getID()))); addHiddenInput( new HiddenInput (prmFormProcess,"Y")); } else { addLeft(iwrb.getLocalizedString("not_exists","News already deleted or not available.")); //addSubmitButton(new CloseButton(iwrb.getImage("close.gif"))); addSubmitButton(new CloseButton()); } } private void noAccess() throws IOException,SQLException { addLeft(iwrb.getLocalizedString("no_access","Login first!")); this.addSubmitButton(new CloseButton()); } public DropdownMenu counterDropdown(String dropdownName, int countFrom, int countTo) { DropdownMenu myDropdown = new DropdownMenu(dropdownName); for(; countFrom <= countTo; countFrom++){ myDropdown.addMenuElement(Integer.toString(countFrom), Integer.toString(countFrom)); } myDropdown.keepStatusOnAction(); return myDropdown; } private DropdownMenu drpNewsCategories(String name,String valueIfEmpty,String displayIfEmpty){ List L = NewsFinder.listOfNewsCategories(); if(L != null){ DropdownMenu drp = new DropdownMenu(L,name); return drp; } else{ DropdownMenu drp = new DropdownMenu(name); drp.addDisabledMenuElement("",""); return drp; } } public void main(IWContext iwc) throws Exception { super.main(iwc); isAdmin = true; eUser = com.idega.core.accesscontrol.business.LoginBusinessBean.getUser(iwc); iUserId = eUser != null?eUser.getID():-1; iwb = getBundle(iwc); iwrb = getResourceBundle(iwc); core = iwc.getApplication().getBundle(NewsReader.IW_CORE_BUNDLE_IDENTIFIER); addTitle(iwrb.getLocalizedString("news_editor","News Editor")); control(iwc); } public String getBundleIdentifier(){ return IW_BUNDLE_IDENTIFIER; } }
true
true
private void addNewsFields(NwNews nwNews ,ContentHelper contentHelper, int iLocaleId,int iObjInsId,int iCategoryId){ LocalizedText locText = null; boolean hasContent = ( contentHelper != null) ? true:false; if(hasContent) locText = contentHelper.getLocalizedText(TextFinder.getLocale(iLocaleId)); boolean hasNwNews = ( nwNews != null ) ? true: false; boolean hasLocalizedText = ( locText != null ) ? true: false; TextInput tiHeadline = new TextInput(prmHeadline); tiHeadline.setLength(40); tiHeadline.setMaxlength(255); IWTimestamp now = IWTimestamp.RightNow(); TimestampInput publishFrom = new TimestampInput(prmPubFrom,true); publishFrom.setTimestamp(now.getTimestamp()); TimestampInput newsDate = new TimestampInput(prmNewsDate,true); newsDate.setTimestamp(now.getTimestamp()); newsDate.setYearRange(now.getYear()-4,now.getYear()+2); // add default publishing days: int addYears = 0; try { addYears = Integer.parseInt(iwb.getProperty(YEARS_AHEAD_PROPERTY, "0")); } catch (NullPointerException ne) { addYears = 0; } catch (NumberFormatException nfe) { addYears = 0; } now.addYears(addYears); TimestampInput publishTo = new TimestampInput(prmPubTo,true); publishTo.setTimestamp(now.getTimestamp()); DropdownMenu LocaleDrop = ICLocalePresentation.getLocaleDropdownIdKeyed(prmLocale); LocaleDrop.setToSubmit(); LocaleDrop.setSelectedElement(Integer.toString(iLocaleId)); //TextArea taBody = new TextArea(prmBody,65,18); TextEditor taBody = new TextEditor(); taBody.setInputName(prmBody); TextArea taTeaser = new TextArea(prmTeaser,65,2); List cats = CategoryFinder.getInstance().listOfCategoryForObjectInstanceId(iObjInsId); DropdownMenu catDrop = new DropdownMenu(cats,prmCategory); //catDrop.addMenuElementFirst("-1",sCategory); TextInput tiAuthor = new TextInput(prmAuthor); tiAuthor.setLength(22); tiAuthor.setMaxlength(255); TextInput tiSource = new TextInput(prmSource); tiAuthor.setLength(22); tiAuthor.setMaxlength(255); //DropdownMenu drpDaysShown = counterDropdown(prmDaysshown, 1, 30); //drpDaysShown.addMenuElementFirst("-1", iwrb.getLocalizedString("undetermined","Undetermined") ); /* ImageInserter imageInsert = new ImageInserter(); imageInsert.setImSessionImageName(prmImageId); Link propslink = null; */ // Fill or not Fill if ( hasLocalizedText ) { if ( locText.getHeadline() != null ) { tiHeadline.setContent(locText.getHeadline()); } if ( locText.getTitle() != null ) { taTeaser.setContent(locText.getTitle()); } if ( locText.getBody() != null ) { taBody.setContent(locText.getBody()); } addHiddenInput(new HiddenInput(prmLocalizedTextId,String.valueOf(locText.getID()))); } if( hasNwNews ){ if("".equals(nwNews.getAuthor())&& eUser !=null) tiAuthor.setContent(eUser.getFirstName()); else tiAuthor.setContent(nwNews.getAuthor()); tiSource.setContent(nwNews.getSource()); //drpCategories.setSelectedElement(String.valueOf(nwNews.getNewsCategoryId())); if ( hasContent ) { /* List files = contentHelper.getFiles(); if(files != null){ ICFile file1 = (ICFile) files.get(0); imageInsert.setImageId(file1.getID()); Text properties = new Text("properties"); propslink = com.idega.block.media.presentation.ImageAttributeSetter.getLink(properties,file1.getID(),imageAttributeKey); } */ Content content = contentHelper.getContent(); if(content.getPublishFrom()!=null){ publishFrom.setTimestamp(content.getPublishFrom()); } if(content.getPublishTo()!=null){ publishTo.setTimestamp(content.getPublishTo()); } if(content.getLastUpdated()!=null){ newsDate.setTimestamp(content.getLastUpdated()); } } catDrop.setSelectedElement(String.valueOf(nwNews.getNewsCategoryId())); addHiddenInput(new HiddenInput(prmNwNewsId,Integer.toString(nwNews.getID()))); //addHiddenInput(new HiddenInput(prmCategory ,String.valueOf(nwNews.getNewsCategoryId()))); } else{ if( eUser !=null){ tiAuthor.setContent(eUser.getFirstName()); } IWTimestamp today = IWTimestamp.RightNow(); publishFrom.setTimestamp(today.getTimestamp()); if (addYears > 0) today.addYears(addYears); else today.addDays(defaultPublishDays); publishTo.setTimestamp(today.getTimestamp()); addHiddenInput(new HiddenInput(prmCategory ,String.valueOf(iCategoryId))); } addHiddenInput(new HiddenInput(prmObjInstId ,String.valueOf(iObjInsId))); SubmitButton addButton = new SubmitButton(core.getImage("/shared/create.gif","Add to news"),prmSaveFile); //SubmitButton leftButton = new SubmitButton(core.getImage("/shared/frew.gif","Insert image"),prmSaveFile); ImageInserter imageInsert = new ImageInserter(); imageInsert.setImSessionImageName(prmImageId); imageInsert.setUseBoxParameterName(prmUseImage); imageInsert.setMaxImageWidth(130); imageInsert.setHasUseBox(false); imageInsert.setSelected(false); Table imageTable = new Table(); int row = 1; //imageTable.mergeCells(1,row,3,row); //imageTable.add(formatText(iwrb.getLocalizedString("image","Chosen image :")),1,row++); imageTable.mergeCells(1,row,3,row); imageTable.add(imageInsert,1,row++); imageTable.mergeCells(1,row,3,row); //imageTable.add(leftButton,1,row); imageTable.add(addButton,1,row++); if ( hasContent ) { List files = contentHelper.getFiles(); if(files != null){ imageTable.mergeCells(1,row,3,row); imageTable.add( formatText(iwrb.getLocalizedString("newsimages","News images :")),1,row++); ICFile file1 = (ICFile) files.get(0); imageInsert.setImageId(((Integer)file1.getPrimaryKey()).intValue()); Iterator I = files.iterator(); while(I.hasNext()){ try { ICFile f = (ICFile) I.next(); Image immi = new Image(((Integer)f.getPrimaryKey()).intValue()); immi.setMaxImageWidth(50); imageTable.add(immi,1,row); //Link edit = new Link(iwb.getImage("/shared/edit.gif")); Link edit = com.idega.block.image.presentation.ImageAttributeSetter.getLink(iwb.getImage("/shared/edit.gif"),((Integer)file1.getPrimaryKey()).intValue(),imageAttributeKey); Link delete = new Link(core.getImage("/shared/delete.gif")); delete.addParameter(prmDeleteFile,f.getPrimaryKey().toString()); delete.addParameter(prmNwNewsId,nwNews.getID()); delete.addParameter(getParameterSaveNews()); imageTable.add(edit,2,row); imageTable.add(delete,3,row); row++; } catch (Exception ex) { } } } } addLeft(sHeadline,tiHeadline,true); addLeft(sLocale, LocaleDrop,true); addLeft(sTeaser,taTeaser,true); addLeft(sNews,taBody,true); addLeft(sNewsDate,newsDate,true); addLeft(sPublisFrom, publishFrom,true); addLeft(sPublisTo,publishTo,true); addRight(sCategory,catDrop,true); addRight(sAuthor,tiAuthor,true); addRight(sSource,tiSource,true); //addRight(iwrb.getLocalizedString("image","Image"),imageInsert,true); //if(addButton!=null){ //addRight("",addButton,true,false); //} addRight(iwrb.getLocalizedString("images","Images"),imageTable,true,false); /* addRight(sImage,imageInsert,true); if(propslink != null) addRight("props",propslink,true); */ SubmitButton save = new SubmitButton(iwrb.getLocalizedImageButton("save","Save"),actSave); SubmitButton close = new SubmitButton(iwrb.getLocalizedImageButton("close","Close"),actClose); addSubmitButton(save); addSubmitButton(close); addHiddenInput( new HiddenInput (prmFormProcess,"Y")); }
private void addNewsFields(NwNews nwNews ,ContentHelper contentHelper, int iLocaleId,int iObjInsId,int iCategoryId){ LocalizedText locText = null; boolean hasContent = ( contentHelper != null) ? true:false; if(hasContent) locText = contentHelper.getLocalizedText(TextFinder.getLocale(iLocaleId)); boolean hasNwNews = ( nwNews != null ) ? true: false; boolean hasLocalizedText = ( locText != null ) ? true: false; TextInput tiHeadline = new TextInput(prmHeadline); tiHeadline.setLength(40); tiHeadline.setMaxlength(255); IWTimestamp now = IWTimestamp.RightNow(); TimestampInput publishFrom = new TimestampInput(prmPubFrom,true); publishFrom.setTimestamp(now.getTimestamp()); TimestampInput newsDate = new TimestampInput(prmNewsDate,true); newsDate.setTimestamp(now.getTimestamp()); newsDate.setYearRange(now.getYear()-4,now.getYear()+2); // add default publishing days: int addYears = 0; try { addYears = Integer.parseInt(iwb.getProperty(YEARS_AHEAD_PROPERTY, "0")); } catch (NullPointerException ne) { addYears = 0; } catch (NumberFormatException nfe) { addYears = 0; } now.addYears(addYears); TimestampInput publishTo = new TimestampInput(prmPubTo,true); publishTo.setTimestamp(now.getTimestamp()); DropdownMenu LocaleDrop = ICLocalePresentation.getLocaleDropdownIdKeyed(prmLocale); LocaleDrop.setToSubmit(); LocaleDrop.setSelectedElement(Integer.toString(iLocaleId)); //TextArea taBody = new TextArea(prmBody,65,18); TextEditor taBody = new TextEditor(); taBody.setInputName(prmBody); TextArea taTeaser = new TextArea(prmTeaser,65,2); List cats = CategoryFinder.getInstance().listOfCategoryForObjectInstanceId(iObjInsId); DropdownMenu catDrop = new DropdownMenu(cats,prmCategory); //catDrop.addMenuElementFirst("-1",sCategory); TextInput tiAuthor = new TextInput(prmAuthor); tiAuthor.setLength(22); tiAuthor.setMaxlength(255); TextInput tiSource = new TextInput(prmSource); tiAuthor.setLength(22); tiAuthor.setMaxlength(255); //DropdownMenu drpDaysShown = counterDropdown(prmDaysshown, 1, 30); //drpDaysShown.addMenuElementFirst("-1", iwrb.getLocalizedString("undetermined","Undetermined") ); /* ImageInserter imageInsert = new ImageInserter(); imageInsert.setImSessionImageName(prmImageId); Link propslink = null; */ // Fill or not Fill if ( hasLocalizedText ) { if ( locText.getHeadline() != null ) { tiHeadline.setContent(locText.getHeadline()); } if ( locText.getTitle() != null ) { taTeaser.setContent(locText.getTitle()); } if ( locText.getBody() != null ) { taBody.setContent(locText.getBody()); } addHiddenInput(new HiddenInput(prmLocalizedTextId,String.valueOf(locText.getID()))); } if( hasNwNews ){ if("".equals(nwNews.getAuthor())&& eUser !=null) tiAuthor.setContent(eUser.getFirstName()); else tiAuthor.setContent(nwNews.getAuthor()); tiSource.setContent(nwNews.getSource()); //drpCategories.setSelectedElement(String.valueOf(nwNews.getNewsCategoryId())); if ( hasContent ) { /* List files = contentHelper.getFiles(); if(files != null){ ICFile file1 = (ICFile) files.get(0); imageInsert.setImageId(file1.getID()); Text properties = new Text("properties"); propslink = com.idega.block.media.presentation.ImageAttributeSetter.getLink(properties,file1.getID(),imageAttributeKey); } */ Content content = contentHelper.getContent(); if(content.getPublishFrom()!=null){ publishFrom.setTimestamp(content.getPublishFrom()); } if(content.getPublishTo()!=null){ publishTo.setTimestamp(content.getPublishTo()); } if(content.getLastUpdated()!=null){ newsDate.setTimestamp(content.getLastUpdated()); } } catDrop.setSelectedElement(String.valueOf(nwNews.getNewsCategoryId())); addHiddenInput(new HiddenInput(prmNwNewsId,Integer.toString(nwNews.getID()))); //addHiddenInput(new HiddenInput(prmCategory ,String.valueOf(nwNews.getNewsCategoryId()))); } else{ if( eUser !=null){ tiAuthor.setContent(eUser.getFirstName()); } IWTimestamp today = IWTimestamp.RightNow(); publishFrom.setTimestamp(today.getTimestamp()); if (addYears > 0) today.addYears(addYears); else today.addDays(defaultPublishDays); publishTo.setTimestamp(today.getTimestamp()); addHiddenInput(new HiddenInput(prmCategory ,String.valueOf(iCategoryId))); } addHiddenInput(new HiddenInput(prmObjInstId ,String.valueOf(iObjInsId))); SubmitButton addButton = new SubmitButton(core.getImage("/shared/create.gif","Add to news"),prmSaveFile); //SubmitButton leftButton = new SubmitButton(core.getImage("/shared/frew.gif","Insert image"),prmSaveFile); ImageInserter imageInsert = new ImageInserter(); imageInsert.setImSessionImageName(prmImageId); imageInsert.setUseBoxParameterName(prmUseImage); imageInsert.setMaxImageWidth(130); imageInsert.setHasUseBox(false); imageInsert.setSelected(false); Table imageTable = new Table(); int row = 1; //imageTable.mergeCells(1,row,3,row); //imageTable.add(formatText(iwrb.getLocalizedString("image","Chosen image :")),1,row++); imageTable.mergeCells(1,row,3,row); imageTable.add(imageInsert,1,row++); imageTable.mergeCells(1,row,3,row); //imageTable.add(leftButton,1,row); imageTable.add(addButton,1,row++); if ( hasContent ) { List files = contentHelper.getFiles(); if(files != null && !files.isEmpty()){ imageTable.mergeCells(1,row,3,row); imageTable.add( formatText(iwrb.getLocalizedString("newsimages","News images :")),1,row++); ICFile file1 = (ICFile) files.get(0); imageInsert.setImageId(((Integer)file1.getPrimaryKey()).intValue()); Iterator I = files.iterator(); while(I.hasNext()){ try { ICFile f = (ICFile) I.next(); Image immi = new Image(((Integer)f.getPrimaryKey()).intValue()); immi.setMaxImageWidth(50); imageTable.add(immi,1,row); //Link edit = new Link(iwb.getImage("/shared/edit.gif")); Link edit = com.idega.block.image.presentation.ImageAttributeSetter.getLink(iwb.getImage("/shared/edit.gif"),((Integer)file1.getPrimaryKey()).intValue(),imageAttributeKey); Link delete = new Link(core.getImage("/shared/delete.gif")); delete.addParameter(prmDeleteFile,f.getPrimaryKey().toString()); delete.addParameter(prmNwNewsId,nwNews.getID()); delete.addParameter(getParameterSaveNews()); imageTable.add(edit,2,row); imageTable.add(delete,3,row); row++; } catch (Exception ex) { } } } } addLeft(sHeadline,tiHeadline,true); addLeft(sLocale, LocaleDrop,true); addLeft(sTeaser,taTeaser,true); addLeft(sNews,taBody,true); addLeft(sNewsDate,newsDate,true); addLeft(sPublisFrom, publishFrom,true); addLeft(sPublisTo,publishTo,true); addRight(sCategory,catDrop,true); addRight(sAuthor,tiAuthor,true); addRight(sSource,tiSource,true); //addRight(iwrb.getLocalizedString("image","Image"),imageInsert,true); //if(addButton!=null){ //addRight("",addButton,true,false); //} addRight(iwrb.getLocalizedString("images","Images"),imageTable,true,false); /* addRight(sImage,imageInsert,true); if(propslink != null) addRight("props",propslink,true); */ SubmitButton save = new SubmitButton(iwrb.getLocalizedImageButton("save","Save"),actSave); SubmitButton close = new SubmitButton(iwrb.getLocalizedImageButton("close","Close"),actClose); addSubmitButton(save); addSubmitButton(close); addHiddenInput( new HiddenInput (prmFormProcess,"Y")); }
diff --git a/src/main/java/com/novemberain/quartz/mongodb/MongoDBJobStore.java b/src/main/java/com/novemberain/quartz/mongodb/MongoDBJobStore.java index 0cc2e18..e7d7224 100755 --- a/src/main/java/com/novemberain/quartz/mongodb/MongoDBJobStore.java +++ b/src/main/java/com/novemberain/quartz/mongodb/MongoDBJobStore.java @@ -1,1014 +1,1014 @@ /* * $Id$ * -------------------------------------------------------------------------------------- * Copyright (c) MuleSoft, Inc. All rights reserved. http://www.mulesoft.com * * The software in this package is published under the terms of the CPAL v1.0 * license, a copy of which has been included with this distribution in the * LICENSE.txt file. */ package com.novemberain.quartz.mongodb; import com.mongodb.*; import com.mongodb.MongoException.DuplicateKey; import org.bson.types.ObjectId; import org.quartz.Calendar; import org.quartz.*; import org.quartz.Trigger.CompletedExecutionInstruction; import org.quartz.Trigger.TriggerState; import org.quartz.impl.matchers.GroupMatcher; import org.quartz.spi.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.UnknownHostException; import java.util.*; import com.novemberain.quartz.mongodb.Constants; import static com.novemberain.quartz.mongodb.Keys.*; public class MongoDBJobStore implements JobStore, Constants { protected final Logger log = LoggerFactory.getLogger(getClass()); public static final DBObject KEY_AND_GROUP_FIELDS = BasicDBObjectBuilder.start(). append(KEY_GROUP, 1). append(KEY_NAME, 1). get(); private Mongo mongo; private String collectionPrefix = "quartz_"; private String dbName; private DBCollection jobCollection; private DBCollection triggerCollection; private DBCollection calendarCollection; private ClassLoadHelper loadHelper; private DBCollection locksCollection; private DBCollection pausedTriggerGroupsCollection; private DBCollection pausedJobGroupsCollection; private String instanceId; private String[] addresses; private String username; private String password; private SchedulerSignaler signaler; protected long misfireThreshold = 5000l; private long triggerTimeoutMillis = 10 * 60 * 1000L; private List<TriggerPersistenceHelper> persistenceHelpers; private QueryHelper queryHelper; public void initialize(ClassLoadHelper loadHelper, SchedulerSignaler signaler) throws SchedulerConfigException { this.loadHelper = loadHelper; this.signaler = signaler; if (addresses == null || addresses.length == 0) { throw new SchedulerConfigException("At least one MongoDB address must be specified."); } this.mongo = connectToMongoDB(); DB db = selectDatabase(this.mongo); initializeCollections(db); ensureIndexes(); initializeHelpers(); } public void schedulerStarted() throws SchedulerException { // No-op } public void schedulerPaused() { // No-op } public void schedulerResumed() { } public void shutdown() { mongo.close(); } public boolean supportsPersistence() { return true; } public long getEstimatedTimeToReleaseAndAcquireTrigger() { // this will vary... return 200; } public boolean isClustered() { return true; } /** * Job and Trigger storage Methods */ public void storeJobAndTrigger(JobDetail newJob, OperableTrigger newTrigger) throws ObjectAlreadyExistsException, JobPersistenceException { ObjectId jobId = storeJobInMongo(newJob, false); log.debug("Storing job " + newJob.getKey() + " and trigger " + newTrigger.getKey()); storeTrigger(newTrigger, jobId, false); } public void storeJob(JobDetail newJob, boolean replaceExisting) throws ObjectAlreadyExistsException, JobPersistenceException { storeJobInMongo(newJob, replaceExisting); } public void storeJobsAndTriggers(Map<JobDetail, List<Trigger>> triggersAndJobs, boolean replace) throws ObjectAlreadyExistsException, JobPersistenceException { throw new UnsupportedOperationException(); } @SuppressWarnings("LoopStatementThatDoesntLoop") public boolean removeJob(JobKey jobKey) throws JobPersistenceException { BasicDBObject keyObject = Keys.keyToDBObject(jobKey); DBCursor find = jobCollection.find(keyObject); while (find.hasNext()) { DBObject jobObj = find.next(); jobCollection.remove(keyObject); triggerCollection.remove(new BasicDBObject(TRIGGER_JOB_ID, jobObj.get("_id"))); return true; } return false; } public boolean removeJobs(List<JobKey> jobKeys) throws JobPersistenceException { for (JobKey key : jobKeys) { removeJob(key); } return false; } @SuppressWarnings("unchecked") public JobDetail retrieveJob(JobKey jobKey) throws JobPersistenceException { DBObject dbObject = findJobDocumentByKey(jobKey); try { Class<Job> jobClass = (Class<Job>) getJobClassLoader().loadClass((String) dbObject.get(JOB_CLASS)); JobBuilder builder = JobBuilder.newJob(jobClass) .withIdentity((String) dbObject.get(JOB_KEY_NAME), (String) dbObject.get(JOB_KEY_GROUP)) .withDescription((String) dbObject.get(JOB_KEY_NAME)); JobDataMap jobData = new JobDataMap(); for (String key : dbObject.keySet()) { if (!key.equals(JOB_KEY_NAME) && !key.equals(JOB_KEY_GROUP) && !key.equals(JOB_CLASS) && !key.equals(JOB_DESCRIPTION) && !key.equals("_id")) { jobData.put(key, dbObject.get(key)); } } return builder.usingJobData(jobData).build(); } catch (ClassNotFoundException e) { throw new JobPersistenceException("Could not load job class " + dbObject.get(JOB_CLASS), e); } } public void storeTrigger(OperableTrigger newTrigger, boolean replaceExisting) throws ObjectAlreadyExistsException, JobPersistenceException { if (newTrigger.getJobKey() == null) { throw new JobPersistenceException("Trigger must be associated with a job. Please specify a JobKey."); } DBObject dbObject = jobCollection.findOne(Keys.keyToDBObject(newTrigger.getJobKey())); if (dbObject != null) { storeTrigger(newTrigger, (ObjectId) dbObject.get("_id"), replaceExisting); } else { throw new JobPersistenceException("Could not find job with key " + newTrigger.getJobKey()); } } public boolean removeTrigger(TriggerKey triggerKey) throws JobPersistenceException { BasicDBObject dbObject = Keys.keyToDBObject(triggerKey); DBCursor find = triggerCollection.find(dbObject); if (find.count() > 0) { triggerCollection.remove(dbObject); return true; } return false; } public boolean removeTriggers(List<TriggerKey> triggerKeys) throws JobPersistenceException { for (TriggerKey key : triggerKeys) { removeTrigger(key); } return false; } public boolean replaceTrigger(TriggerKey triggerKey, OperableTrigger newTrigger) throws JobPersistenceException { removeTrigger(triggerKey); storeTrigger(newTrigger, false); return true; } public OperableTrigger retrieveTrigger(TriggerKey triggerKey) throws JobPersistenceException { DBObject dbObject = triggerCollection.findOne(Keys.keyToDBObject(triggerKey)); if (dbObject == null) { return null; } return toTrigger(triggerKey, dbObject); } public boolean checkExists(JobKey jobKey) throws JobPersistenceException { return jobCollection.count(Keys.keyToDBObject(jobKey)) > 0; } public boolean checkExists(TriggerKey triggerKey) throws JobPersistenceException { return triggerCollection.count(Keys.keyToDBObject(triggerKey)) > 0; } public void clearAllSchedulingData() throws JobPersistenceException { jobCollection.remove(new BasicDBObject()); triggerCollection.remove(new BasicDBObject()); calendarCollection.remove(new BasicDBObject()); pausedJobGroupsCollection.remove(new BasicDBObject()); pausedTriggerGroupsCollection.remove(new BasicDBObject()); } public void storeCalendar(String name, Calendar calendar, boolean replaceExisting, boolean updateTriggers) throws ObjectAlreadyExistsException, JobPersistenceException { // TODO if (updateTriggers) { throw new UnsupportedOperationException("Updating triggers is not supported."); } BasicDBObject dbObject = new BasicDBObject(); dbObject.put(CALENDAR_NAME, name); dbObject.put(CALENDAR_SERIALIZED_OBJECT, serialize(calendar)); calendarCollection.insert(dbObject); } public boolean removeCalendar(String calName) throws JobPersistenceException { BasicDBObject searchObj = new BasicDBObject(CALENDAR_NAME, calName); if (calendarCollection.count(searchObj) > 0) { calendarCollection.remove(searchObj); return true; } return false; } public Calendar retrieveCalendar(String calName) throws JobPersistenceException { // TODO throw new UnsupportedOperationException(); } public int getNumberOfJobs() throws JobPersistenceException { return (int) jobCollection.count(); } public int getNumberOfTriggers() throws JobPersistenceException { return (int) triggerCollection.count(); } public int getNumberOfCalendars() throws JobPersistenceException { return (int) calendarCollection.count(); } public int getNumberOfLocks() { return (int) locksCollection.count(); } public Set<JobKey> getJobKeys(GroupMatcher<JobKey> matcher) throws JobPersistenceException { DBCursor cursor = jobCollection.find(queryHelper.matchingKeysConditionFor(matcher), KEY_AND_GROUP_FIELDS); Set<JobKey> result = new HashSet<JobKey>(); while (cursor.hasNext()) { DBObject dbo = cursor.next(); JobKey key = Keys.dbObjectToJobKey(dbo); result.add(key); } return result; } public Set<TriggerKey> getTriggerKeys(GroupMatcher<TriggerKey> matcher) throws JobPersistenceException { DBCursor cursor = triggerCollection.find(queryHelper.matchingKeysConditionFor(matcher), KEY_AND_GROUP_FIELDS); Set<TriggerKey> result = new HashSet<TriggerKey>(); while (cursor.hasNext()) { DBObject dbo = cursor.next(); TriggerKey key = Keys.dbObjectToTriggerKey(dbo); result.add(key); } return result; } public List<String> getJobGroupNames() throws JobPersistenceException { return new ArrayList<String>(jobCollection.distinct(KEY_GROUP)); } public List<String> getTriggerGroupNames() throws JobPersistenceException { return new ArrayList<String>(triggerCollection.distinct(KEY_GROUP)); } public List<String> getCalendarNames() throws JobPersistenceException { throw new UnsupportedOperationException(); } public List<OperableTrigger> getTriggersForJob(JobKey jobKey) throws JobPersistenceException { DBObject dbObject = findJobDocumentByKey(jobKey); List<OperableTrigger> triggers = new ArrayList<OperableTrigger>(); DBCursor cursor = triggerCollection.find(new BasicDBObject(TRIGGER_JOB_ID, dbObject.get("_id"))); while (cursor.hasNext()) { triggers.add(toTrigger(cursor.next())); } return triggers; } public TriggerState getTriggerState(TriggerKey triggerKey) throws JobPersistenceException { DBObject doc = findTriggerDocumentByKey(triggerKey); return triggerStateForValue((String) doc.get(TRIGGER_STATE)); } public void pauseTrigger(TriggerKey triggerKey) throws JobPersistenceException { triggerCollection.update(Keys.keyToDBObject(triggerKey), updateThatSetsTriggerStateTo(STATE_PAUSED)); } public Collection<String> pauseTriggers(GroupMatcher<TriggerKey> matcher) throws JobPersistenceException { final GroupHelper groupHelper = new GroupHelper(triggerCollection, queryHelper); triggerCollection.update(queryHelper.matchingKeysConditionFor(matcher), updateThatSetsTriggerStateTo(STATE_PAUSED), false, true); final Set<String> set = groupHelper.groupsThatMatch(matcher); markTriggerGroupsAsPaused(set); return set; } public void resumeTrigger(TriggerKey triggerKey) throws JobPersistenceException { // TODO: port blocking behavior and misfired triggers handling from StdJDBCDelegate in Quartz triggerCollection.update(Keys.keyToDBObject(triggerKey), updateThatSetsTriggerStateTo(STATE_WAITING)); } public Collection<String> resumeTriggers(GroupMatcher<TriggerKey> matcher) throws JobPersistenceException { final GroupHelper groupHelper = new GroupHelper(triggerCollection, queryHelper); triggerCollection.update(queryHelper.matchingKeysConditionFor(matcher), updateThatSetsTriggerStateTo(STATE_WAITING), false, true); final Set<String> set = groupHelper.groupsThatMatch(matcher); this.unmarkTriggerGroupsAsPaused(set); return set; } @SuppressWarnings("unchecked") public Set<String> getPausedTriggerGroups() throws JobPersistenceException { return new HashSet<String>(pausedTriggerGroupsCollection.distinct(KEY_GROUP)); } @SuppressWarnings("unchecked") public Set<String> getPausedJobGroups() throws JobPersistenceException { return new HashSet<String>(pausedJobGroupsCollection.distinct(KEY_GROUP)); } public void pauseAll() throws JobPersistenceException { final GroupHelper groupHelper = new GroupHelper(triggerCollection, queryHelper); triggerCollection.update(new BasicDBObject(), updateThatSetsTriggerStateTo(STATE_PAUSED)); this.markTriggerGroupsAsPaused(groupHelper.allGroups()); } public void resumeAll() throws JobPersistenceException { final GroupHelper groupHelper = new GroupHelper(triggerCollection, queryHelper); triggerCollection.update(new BasicDBObject(), updateThatSetsTriggerStateTo(STATE_WAITING)); this.unmarkTriggerGroupsAsPaused(groupHelper.allGroups()); } public void pauseJob(JobKey jobKey) throws JobPersistenceException { final ObjectId jobId = (ObjectId) findJobDocumentByKey(jobKey).get("_id"); final TriggerGroupHelper groupHelper = new TriggerGroupHelper(triggerCollection, queryHelper); List<String> groups = groupHelper.groupsForJobId(jobId); triggerCollection.update(new BasicDBObject(TRIGGER_JOB_ID, jobId), updateThatSetsTriggerStateTo(STATE_PAUSED)); this.markTriggerGroupsAsPaused(groups); } public Collection<String> pauseJobs(GroupMatcher<JobKey> groupMatcher) throws JobPersistenceException { final TriggerGroupHelper groupHelper = new TriggerGroupHelper(triggerCollection, queryHelper); List<String> groups = groupHelper.groupsForJobIds(idsFrom(findJobDocumentsThatMatch(groupMatcher))); triggerCollection.update(queryHelper.inGroups(groups), updateThatSetsTriggerStateTo(STATE_PAUSED)); this.markJobGroupsAsPaused(groups); return groups; } public void resumeJob(JobKey jobKey) throws JobPersistenceException { final ObjectId jobId = (ObjectId) findJobDocumentByKey(jobKey).get("_id"); // TODO: port blocking behavior and misfired triggers handling from StdJDBCDelegate in Quartz triggerCollection.update(new BasicDBObject(TRIGGER_JOB_ID, jobId), updateThatSetsTriggerStateTo(STATE_WAITING)); } public Collection<String> resumeJobs(GroupMatcher<JobKey> groupMatcher) throws JobPersistenceException { final TriggerGroupHelper groupHelper = new TriggerGroupHelper(triggerCollection, queryHelper); List<String> groups = groupHelper.groupsForJobIds(idsFrom(findJobDocumentsThatMatch(groupMatcher))); triggerCollection.update(queryHelper.inGroups(groups), updateThatSetsTriggerStateTo(STATE_WAITING)); this.unmarkJobGroupsAsPaused(groups); return groups; } public List<OperableTrigger> acquireNextTriggers(long noLaterThan, int maxCount, long timeWindow) throws JobPersistenceException { BasicDBObject query = new BasicDBObject(); query.put(TRIGGER_NEXT_FIRE_TIME, new BasicDBObject("$lte", new Date(noLaterThan))); if (log.isDebugEnabled()) { log.debug("Finding up to " + maxCount + " triggers which have time less than " + new Date(noLaterThan)); } List<OperableTrigger> triggers = new ArrayList<OperableTrigger>(); DBCursor cursor = triggerCollection.find(query); BasicDBObject sort = new BasicDBObject(); sort.put(TRIGGER_NEXT_FIRE_TIME, Integer.valueOf(1)); cursor.sort(sort); if (log.isDebugEnabled()) { log.debug("Found " + cursor.count() + " triggers which are eligible to be run."); } while (cursor.hasNext() && maxCount > triggers.size()) { DBObject dbObj = cursor.next(); BasicDBObject lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); lock.put(LOCK_INSTANCE_ID, instanceId); lock.put(LOCK_TIME, new Date()); try { OperableTrigger trigger = toTrigger(dbObj); if (trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time."); } continue; } // deal with misfires if (applyMisfire(trigger) && trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time after the misfire was applied."); } continue; } log.debug("Inserting lock for trigger " + trigger.getKey()); locksCollection.insert(lock); log.debug("Aquired trigger " + trigger.getKey()); triggers.add(trigger); } catch (DuplicateKey e) { OperableTrigger trigger = toTrigger(dbObj); // someone else acquired this lock. Move on. log.debug("Failed to acquire trigger " + trigger.getKey() + " due to a lock"); lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); DBObject existingLock; DBCursor lockCursor = locksCollection.find(lock); if (lockCursor.hasNext()) { existingLock = lockCursor.next(); } else { - log.error("Error retrieving expired lock from the database. Maybe it was deleted"); + log.warn("Error retrieving expired lock from the database. Maybe it was deleted"); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } // support for trigger lock expirations if (isTriggerLockExpired(existingLock)) { log.error("Lock for trigger " + trigger.getKey() + " is expired - removing lock and retrying trigger acquisition"); removeTriggerLock(trigger); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } } } return triggers; } public void releaseAcquiredTrigger(OperableTrigger trigger) throws JobPersistenceException { try { removeTriggerLock(trigger); } catch (Exception e) { throw new JobPersistenceException(e.getLocalizedMessage(), e); } } public List<TriggerFiredResult> triggersFired(List<OperableTrigger> triggers) throws JobPersistenceException { List<TriggerFiredResult> results = new ArrayList<TriggerFiredResult>(); for (OperableTrigger trigger : triggers) { log.debug("Fired trigger " + trigger.getKey()); Calendar cal = null; if (trigger.getCalendarName() != null) { cal = retrieveCalendar(trigger.getCalendarName()); if (cal == null) continue; } trigger.triggered(cal); storeTrigger(trigger, true); Date prevFireTime = trigger.getPreviousFireTime(); TriggerFiredBundle bndle = new TriggerFiredBundle(retrieveJob( trigger), trigger, cal, false, new Date(), trigger.getPreviousFireTime(), prevFireTime, trigger.getNextFireTime()); JobDetail job = bndle.getJobDetail(); if (job.isConcurrentExectionDisallowed()) { throw new UnsupportedOperationException("ConcurrentExecutionDisallowed is not supported currently."); } results.add(new TriggerFiredResult(bndle)); } return results; } public void triggeredJobComplete(OperableTrigger trigger, JobDetail jobDetail, CompletedExecutionInstruction triggerInstCode) throws JobPersistenceException { log.debug("Trigger completed " + trigger.getKey()); // check for trigger deleted during execution... OperableTrigger trigger2 = retrieveTrigger(trigger.getKey()); if (trigger2 != null) { if (triggerInstCode == CompletedExecutionInstruction.DELETE_TRIGGER) { if (trigger.getNextFireTime() == null) { // double check for possible reschedule within job // execution, which would cancel the need to delete... if (trigger2.getNextFireTime() == null) { removeTrigger(trigger.getKey()); } } else { removeTrigger(trigger.getKey()); signaler.signalSchedulingChange(0L); } } else if (triggerInstCode == CompletedExecutionInstruction.SET_TRIGGER_COMPLETE) { // TODO: need to store state signaler.signalSchedulingChange(0L); } else if (triggerInstCode == CompletedExecutionInstruction.SET_TRIGGER_ERROR) { // TODO: need to store state signaler.signalSchedulingChange(0L); } else if (triggerInstCode == CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_ERROR) { // TODO: need to store state signaler.signalSchedulingChange(0L); } else if (triggerInstCode == CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_COMPLETE) { // TODO: need to store state signaler.signalSchedulingChange(0L); } } removeTriggerLock(trigger); } public void setInstanceId(String instanceId) { this.instanceId = instanceId; } public void setInstanceName(String schedName) { // No-op } public void setThreadPoolSize(int poolSize) { // No-op } public void setAddresses(String addresses) { this.addresses = addresses.split(","); } public DBCollection getJobCollection() { return jobCollection; } public DBCollection getTriggerCollection() { return triggerCollection; } public DBCollection getCalendarCollection() { return calendarCollection; } public DBCollection getLocksCollection() { return locksCollection; } public String getDbName() { return dbName; } public void setDbName(String dbName) { this.dbName = dbName; } public void setCollectionPrefix(String prefix) { collectionPrefix = prefix + "_"; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public long getMisfireThreshold() { return misfireThreshold; } public void setMisfireThreshold(long misfireThreshold) { this.misfireThreshold = misfireThreshold; } public void setTriggerTimeoutMillis(long triggerTimeoutMillis) { this.triggerTimeoutMillis = triggerTimeoutMillis; } // // Implementation // private void initializeCollections(DB db) { jobCollection = db.getCollection(collectionPrefix + "jobs"); triggerCollection = db.getCollection(collectionPrefix + "triggers"); calendarCollection = db.getCollection(collectionPrefix + "calendars"); locksCollection = db.getCollection(collectionPrefix + "locks"); pausedTriggerGroupsCollection = db.getCollection(collectionPrefix + "paused_trigger_groups"); pausedJobGroupsCollection = db.getCollection(collectionPrefix + "paused_job_groups"); } private DB selectDatabase(Mongo mongo) { DB db = this.mongo.getDB(dbName); // MongoDB defaults are insane, set a reasonable write concern explicitly. MK. db.setWriteConcern(WriteConcern.JOURNAL_SAFE); if (username != null) { db.authenticate(username, password.toCharArray()); } return db; } private Mongo connectToMongoDB() throws SchedulerConfigException { MongoOptions options = new MongoOptions(); options.safe = true; try { ArrayList<ServerAddress> serverAddresses = new ArrayList<ServerAddress>(); for (String a : addresses) { serverAddresses.add(new ServerAddress(a)); } return new Mongo(serverAddresses, options); } catch (UnknownHostException e) { throw new SchedulerConfigException("Could not connect to MongoDB.", e); } catch (MongoException e) { throw new SchedulerConfigException("Could not connect to MongoDB.", e); } } protected OperableTrigger toTrigger(DBObject dbObj) throws JobPersistenceException { TriggerKey key = new TriggerKey((String) dbObj.get(KEY_NAME), (String) dbObj.get(KEY_GROUP)); return toTrigger(key, dbObj); } protected OperableTrigger toTrigger(TriggerKey triggerKey, DBObject dbObject) throws JobPersistenceException { OperableTrigger trigger; try { Class<OperableTrigger> triggerClass = (Class<OperableTrigger>) getTriggerClassLoader().loadClass((String) dbObject.get(TRIGGER_CLASS)); trigger = triggerClass.newInstance(); } catch (ClassNotFoundException e) { throw new JobPersistenceException("Could not find trigger class " + (String) dbObject.get(TRIGGER_CLASS)); } catch (Exception e) { throw new JobPersistenceException("Could not instantiate trigger class " + (String) dbObject.get(TRIGGER_CLASS)); } TriggerPersistenceHelper tpd = triggerPersistenceDelegateFor(trigger); trigger.setKey(triggerKey); trigger.setCalendarName((String) dbObject.get(TRIGGER_CALENDAR_NAME)); trigger.setDescription((String) dbObject.get(TRIGGER_DESCRIPTION)); trigger.setStartTime((Date) dbObject.get(TRIGGER_START_TIME)); trigger.setEndTime((Date) dbObject.get(TRIGGER_END_TIME)); trigger.setFireInstanceId((String) dbObject.get(TRIGGER_FIRE_INSTANCE_ID)); trigger.setMisfireInstruction((Integer) dbObject.get(TRIGGER_MISFIRE_INSTRUCTION)); trigger.setNextFireTime((Date) dbObject.get(TRIGGER_NEXT_FIRE_TIME)); trigger.setPreviousFireTime((Date) dbObject.get(TRIGGER_PREVIOUS_FIRE_TIME)); trigger.setPriority((Integer) dbObject.get(TRIGGER_PRIORITY)); trigger = tpd.setExtraPropertiesAfterInstantiation(trigger, dbObject); DBObject job = jobCollection.findOne(new BasicDBObject("_id", dbObject.get(TRIGGER_JOB_ID))); if (job != null) { trigger.setJobKey(new JobKey((String) job.get(JOB_KEY_NAME), (String) job.get(JOB_KEY_GROUP))); return trigger; } else { // job was deleted return null; } } protected ClassLoader getTriggerClassLoader() { return org.quartz.Job.class.getClassLoader(); } private TriggerPersistenceHelper triggerPersistenceDelegateFor(OperableTrigger trigger) { TriggerPersistenceHelper result = null; for (TriggerPersistenceHelper d : persistenceHelpers) { if (d.canHandleTriggerType(trigger)) { result = d; break; } } assert result != null; return result; } protected boolean isTriggerLockExpired(DBObject lock) { Date lockTime = (Date) lock.get(LOCK_TIME); long elaspedTime = System.currentTimeMillis() - lockTime.getTime(); return (elaspedTime > triggerTimeoutMillis); } protected boolean applyMisfire(OperableTrigger trigger) throws JobPersistenceException { long misfireTime = System.currentTimeMillis(); if (getMisfireThreshold() > 0) { misfireTime -= getMisfireThreshold(); } Date tnft = trigger.getNextFireTime(); if (tnft == null || tnft.getTime() > misfireTime || trigger.getMisfireInstruction() == Trigger.MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY) { return false; } Calendar cal = null; if (trigger.getCalendarName() != null) { cal = retrieveCalendar(trigger.getCalendarName()); } signaler.notifyTriggerListenersMisfired((OperableTrigger) trigger.clone()); trigger.updateAfterMisfire(cal); if (trigger.getNextFireTime() == null) { signaler.notifySchedulerListenersFinalized(trigger); } else if (tnft.equals(trigger.getNextFireTime())) { return false; } storeTrigger(trigger, true); return true; } private Object serialize(Calendar calendar) throws JobPersistenceException { ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); try { ObjectOutputStream objectStream = new ObjectOutputStream(byteStream); objectStream.writeObject(calendar); objectStream.close(); return byteStream.toByteArray(); } catch (IOException e) { throw new JobPersistenceException("Could not serialize Calendar.", e); } } private void ensureIndexes() { BasicDBObject keys = new BasicDBObject(); keys.put(JOB_KEY_NAME, 1); keys.put(JOB_KEY_GROUP, 1); jobCollection.ensureIndex(keys, null, true); keys = new BasicDBObject(); keys.put(KEY_NAME, 1); keys.put(KEY_GROUP, 1); triggerCollection.ensureIndex(keys, null, true); keys = new BasicDBObject(); keys.put(LOCK_KEY_NAME, 1); keys.put(LOCK_KEY_GROUP, 1); locksCollection.ensureIndex(keys, null, true); // remove all locks for this instance on startup locksCollection.remove(new BasicDBObject(LOCK_INSTANCE_ID, instanceId)); keys = new BasicDBObject(); keys.put(CALENDAR_NAME, 1); calendarCollection.ensureIndex(keys, null, true); } protected void storeTrigger(OperableTrigger newTrigger, ObjectId jobId, boolean replaceExisting) throws ObjectAlreadyExistsException { BasicDBObject trigger = new BasicDBObject(); trigger.put(TRIGGER_STATE, STATE_WAITING); trigger.put(TRIGGER_CALENDAR_NAME, newTrigger.getCalendarName()); trigger.put(TRIGGER_CLASS, newTrigger.getClass().getName()); trigger.put(TRIGGER_DESCRIPTION, newTrigger.getDescription()); trigger.put(TRIGGER_END_TIME, newTrigger.getEndTime()); trigger.put(TRIGGER_FINAL_FIRE_TIME, newTrigger.getFinalFireTime()); trigger.put(TRIGGER_FIRE_INSTANCE_ID, newTrigger.getFireInstanceId()); trigger.put(TRIGGER_JOB_ID, jobId); trigger.put(KEY_NAME, newTrigger.getKey().getName()); trigger.put(KEY_GROUP, newTrigger.getKey().getGroup()); trigger.put(TRIGGER_MISFIRE_INSTRUCTION, newTrigger.getMisfireInstruction()); trigger.put(TRIGGER_NEXT_FIRE_TIME, newTrigger.getNextFireTime()); trigger.put(TRIGGER_PREVIOUS_FIRE_TIME, newTrigger.getPreviousFireTime()); trigger.put(TRIGGER_PRIORITY, newTrigger.getPriority()); trigger.put(TRIGGER_START_TIME, newTrigger.getStartTime()); TriggerPersistenceHelper tpd = triggerPersistenceDelegateFor(newTrigger); trigger = (BasicDBObject) tpd.injectExtraPropertiesForInsert(newTrigger, trigger); try { triggerCollection.insert(trigger); } catch (DuplicateKey key) { if (replaceExisting) { trigger.remove("_id"); triggerCollection.update(keyToDBObject(newTrigger.getKey()), trigger); } else { throw new ObjectAlreadyExistsException(newTrigger); } } } protected ObjectId storeJobInMongo(JobDetail newJob, boolean replaceExisting) throws ObjectAlreadyExistsException { JobKey key = newJob.getKey(); BasicDBObject job = keyToDBObject(key); if (replaceExisting) { DBObject result = jobCollection.findOne(job); if (result != null) { result = job; } } job.put(JOB_KEY_NAME, key.getName()); job.put(JOB_KEY_GROUP, key.getGroup()); job.put(JOB_DESCRIPTION, newJob.getDescription()); job.put(JOB_CLASS, newJob.getJobClass().getName()); job.putAll(newJob.getJobDataMap()); try { jobCollection.insert(job); return (ObjectId) job.get("_id"); } catch (DuplicateKey e) { throw new ObjectAlreadyExistsException(e.getMessage()); } } protected void removeTriggerLock(OperableTrigger trigger) { log.debug("Removing trigger lock " + trigger.getKey() + "." + instanceId); BasicDBObject lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, trigger.getKey().getName()); lock.put(LOCK_KEY_GROUP, trigger.getKey().getGroup()); lock.put(LOCK_INSTANCE_ID, instanceId); locksCollection.remove(lock); log.debug("Trigger lock " + trigger.getKey() + "." + instanceId + " removed."); } protected ClassLoader getJobClassLoader() { return loadHelper.getClassLoader(); } private JobDetail retrieveJob(OperableTrigger trigger) throws JobPersistenceException { try { return retrieveJob(trigger.getJobKey()); } catch (JobPersistenceException e) { removeTriggerLock(trigger); throw e; } } protected DBObject findJobDocumentByKey(JobKey key) { return jobCollection.findOne(keyToDBObject(key)); } protected DBObject findTriggerDocumentByKey(TriggerKey key) { return triggerCollection.findOne(keyToDBObject(key)); } private void initializeHelpers() { this.persistenceHelpers = new ArrayList<TriggerPersistenceHelper>(); persistenceHelpers.add(new SimpleTriggerPersistenceHelper()); persistenceHelpers.add(new CalendarIntervalTriggerPersistenceHelper()); persistenceHelpers.add(new CronTriggerPersistenceHelper()); persistenceHelpers.add(new DailyTimeIntervalTriggerPersistenceHelper()); this.queryHelper = new QueryHelper(); } private TriggerState triggerStateForValue(String ts) { if (ts == null) { return TriggerState.NONE; } if (ts.equals(STATE_DELETED)) { return TriggerState.NONE; } if (ts.equals(STATE_COMPLETE)) { return TriggerState.COMPLETE; } if (ts.equals(STATE_PAUSED)) { return TriggerState.PAUSED; } if (ts.equals(STATE_PAUSED_BLOCKED)) { return TriggerState.PAUSED; } if (ts.equals(STATE_ERROR)) { return TriggerState.ERROR; } if (ts.equals(STATE_BLOCKED)) { return TriggerState.BLOCKED; } // waiting or acquired return TriggerState.NORMAL; } private DBObject updateThatSetsTriggerStateTo(String state) { return BasicDBObjectBuilder. start("$set", new BasicDBObject(TRIGGER_STATE, state)). get(); } private void markTriggerGroupsAsPaused(Collection<String> groups) { List<DBObject> list = new ArrayList<DBObject>(); for (String s : groups) { list.add(new BasicDBObject(KEY_GROUP, s)); } pausedTriggerGroupsCollection.insert(list); } private void unmarkTriggerGroupsAsPaused(Collection<String> groups) { pausedTriggerGroupsCollection.remove(QueryBuilder.start(KEY_GROUP).in(groups).get()); } private void markJobGroupsAsPaused(List<String> groups) { if (groups == null) { throw new IllegalArgumentException("groups cannot be null!"); } List<DBObject> list = new ArrayList<DBObject>(); for (String s : groups) { list.add(new BasicDBObject(KEY_GROUP, s)); } pausedJobGroupsCollection.insert(list); } private void unmarkJobGroupsAsPaused(Collection<String> groups) { pausedJobGroupsCollection.remove(QueryBuilder.start(KEY_GROUP).in(groups).get()); } private Collection<ObjectId> idsFrom(Collection<DBObject> docs) { // so much repetitive code would be gone if Java collections just had .map and .filter… List<ObjectId> list = new ArrayList<ObjectId>(); for (DBObject doc : docs) { list.add((ObjectId) doc.get("_id")); } return list; } private Collection<DBObject> findJobDocumentsThatMatch(GroupMatcher<JobKey> matcher) { final GroupHelper groupHelper = new GroupHelper(jobCollection, queryHelper); return groupHelper.inGroupsThatMatch(matcher); } }
true
true
public List<OperableTrigger> acquireNextTriggers(long noLaterThan, int maxCount, long timeWindow) throws JobPersistenceException { BasicDBObject query = new BasicDBObject(); query.put(TRIGGER_NEXT_FIRE_TIME, new BasicDBObject("$lte", new Date(noLaterThan))); if (log.isDebugEnabled()) { log.debug("Finding up to " + maxCount + " triggers which have time less than " + new Date(noLaterThan)); } List<OperableTrigger> triggers = new ArrayList<OperableTrigger>(); DBCursor cursor = triggerCollection.find(query); BasicDBObject sort = new BasicDBObject(); sort.put(TRIGGER_NEXT_FIRE_TIME, Integer.valueOf(1)); cursor.sort(sort); if (log.isDebugEnabled()) { log.debug("Found " + cursor.count() + " triggers which are eligible to be run."); } while (cursor.hasNext() && maxCount > triggers.size()) { DBObject dbObj = cursor.next(); BasicDBObject lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); lock.put(LOCK_INSTANCE_ID, instanceId); lock.put(LOCK_TIME, new Date()); try { OperableTrigger trigger = toTrigger(dbObj); if (trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time."); } continue; } // deal with misfires if (applyMisfire(trigger) && trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time after the misfire was applied."); } continue; } log.debug("Inserting lock for trigger " + trigger.getKey()); locksCollection.insert(lock); log.debug("Aquired trigger " + trigger.getKey()); triggers.add(trigger); } catch (DuplicateKey e) { OperableTrigger trigger = toTrigger(dbObj); // someone else acquired this lock. Move on. log.debug("Failed to acquire trigger " + trigger.getKey() + " due to a lock"); lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); DBObject existingLock; DBCursor lockCursor = locksCollection.find(lock); if (lockCursor.hasNext()) { existingLock = lockCursor.next(); } else { log.error("Error retrieving expired lock from the database. Maybe it was deleted"); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } // support for trigger lock expirations if (isTriggerLockExpired(existingLock)) { log.error("Lock for trigger " + trigger.getKey() + " is expired - removing lock and retrying trigger acquisition"); removeTriggerLock(trigger); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } } } return triggers; }
public List<OperableTrigger> acquireNextTriggers(long noLaterThan, int maxCount, long timeWindow) throws JobPersistenceException { BasicDBObject query = new BasicDBObject(); query.put(TRIGGER_NEXT_FIRE_TIME, new BasicDBObject("$lte", new Date(noLaterThan))); if (log.isDebugEnabled()) { log.debug("Finding up to " + maxCount + " triggers which have time less than " + new Date(noLaterThan)); } List<OperableTrigger> triggers = new ArrayList<OperableTrigger>(); DBCursor cursor = triggerCollection.find(query); BasicDBObject sort = new BasicDBObject(); sort.put(TRIGGER_NEXT_FIRE_TIME, Integer.valueOf(1)); cursor.sort(sort); if (log.isDebugEnabled()) { log.debug("Found " + cursor.count() + " triggers which are eligible to be run."); } while (cursor.hasNext() && maxCount > triggers.size()) { DBObject dbObj = cursor.next(); BasicDBObject lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); lock.put(LOCK_INSTANCE_ID, instanceId); lock.put(LOCK_TIME, new Date()); try { OperableTrigger trigger = toTrigger(dbObj); if (trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time."); } continue; } // deal with misfires if (applyMisfire(trigger) && trigger.getNextFireTime() == null) { if (log.isDebugEnabled()) { log.debug("Skipping trigger " + trigger.getKey() + " as it has no next fire time after the misfire was applied."); } continue; } log.debug("Inserting lock for trigger " + trigger.getKey()); locksCollection.insert(lock); log.debug("Aquired trigger " + trigger.getKey()); triggers.add(trigger); } catch (DuplicateKey e) { OperableTrigger trigger = toTrigger(dbObj); // someone else acquired this lock. Move on. log.debug("Failed to acquire trigger " + trigger.getKey() + " due to a lock"); lock = new BasicDBObject(); lock.put(LOCK_KEY_NAME, dbObj.get(KEY_NAME)); lock.put(LOCK_KEY_GROUP, dbObj.get(KEY_GROUP)); DBObject existingLock; DBCursor lockCursor = locksCollection.find(lock); if (lockCursor.hasNext()) { existingLock = lockCursor.next(); } else { log.warn("Error retrieving expired lock from the database. Maybe it was deleted"); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } // support for trigger lock expirations if (isTriggerLockExpired(existingLock)) { log.error("Lock for trigger " + trigger.getKey() + " is expired - removing lock and retrying trigger acquisition"); removeTriggerLock(trigger); return acquireNextTriggers(noLaterThan, maxCount, timeWindow); } } } return triggers; }
diff --git a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java index 01d8403..1c388b1 100644 --- a/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java +++ b/src/uk/org/ponder/rsf/renderer/html/BasicHTMLRenderSystem.java @@ -1,436 +1,439 @@ /* * Created on Jul 27, 2005 */ package uk.org.ponder.rsf.renderer.html; import java.io.InputStream; import java.io.Reader; import java.util.HashMap; import java.util.Map; import uk.org.ponder.rsf.components.UIAnchor; import uk.org.ponder.rsf.components.UIBound; import uk.org.ponder.rsf.components.UIBoundBoolean; import uk.org.ponder.rsf.components.UIBoundList; import uk.org.ponder.rsf.components.UICommand; import uk.org.ponder.rsf.components.UIComponent; import uk.org.ponder.rsf.components.UIForm; import uk.org.ponder.rsf.components.UIInput; import uk.org.ponder.rsf.components.UILink; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.components.UIOutputMultiline; import uk.org.ponder.rsf.components.UIParameter; import uk.org.ponder.rsf.components.UISelect; import uk.org.ponder.rsf.components.UISelectChoice; import uk.org.ponder.rsf.components.UISelectLabel; import uk.org.ponder.rsf.components.UIVerbatim; import uk.org.ponder.rsf.renderer.ComponentRenderer; import uk.org.ponder.rsf.renderer.DecoratorManager; import uk.org.ponder.rsf.renderer.RenderSystem; import uk.org.ponder.rsf.renderer.RenderUtil; import uk.org.ponder.rsf.renderer.StaticComponentRenderer; import uk.org.ponder.rsf.renderer.StaticRendererCollection; import uk.org.ponder.rsf.renderer.TagRenderContext; import uk.org.ponder.rsf.request.FossilizedConverter; import uk.org.ponder.rsf.request.SubmittedValueEntry; import uk.org.ponder.rsf.template.XMLLump; import uk.org.ponder.rsf.template.XMLLumpList; import uk.org.ponder.rsf.uitype.UITypes; import uk.org.ponder.rsf.view.View; import uk.org.ponder.streamutil.StreamCopyUtil; import uk.org.ponder.streamutil.write.PrintOutputStream; import uk.org.ponder.stringutil.StringList; import uk.org.ponder.stringutil.URLUtil; import uk.org.ponder.util.Logger; import uk.org.ponder.xml.XMLUtil; import uk.org.ponder.xml.XMLWriter; /** * The implementation of the standard XHTML rendering System. This class is due * for basic refactoring since it contains logic that belongs in a) a "base * System-independent" lookup bean, and b) in a number of individual * ComponentRenderer objects. * * @author Antranig Basman ([email protected]) * */ public class BasicHTMLRenderSystem implements RenderSystem { private StaticRendererCollection scrc; private DecoratorManager decoratormanager; public void setStaticRenderers(StaticRendererCollection scrc) { this.scrc = scrc; } public void setDecoratorManager(DecoratorManager decoratormanager) { this.decoratormanager = decoratormanager; } // two methods for the RenderSystemDecoder interface public void normalizeRequestMap(Map requestparams) { String key = RenderUtil.findCommandParams(requestparams); if (key != null) { String params = key.substring(FossilizedConverter.COMMAND_LINK_PARAMETERS .length()); RenderUtil.unpackCommandLink(params, requestparams); requestparams.remove(key); } } public void fixupUIType(SubmittedValueEntry sve) { if (sve.oldvalue instanceof Boolean) { if (sve.newvalue == null) sve.newvalue = Boolean.FALSE; } else if (sve.oldvalue instanceof String[]) { if (sve.newvalue == null) sve.newvalue = new String[] {}; } } private void closeTag(PrintOutputStream pos, XMLLump uselump) { pos.print("</"); pos.write(uselump.buffer, uselump.start + 1, uselump.length - 2); pos.print(">"); } private void dumpBoundFields(UIBound torender, XMLWriter xmlw) { if (torender != null) { if (torender.fossilizedbinding != null) { RenderUtil.dumpHiddenField(torender.fossilizedbinding.name, torender.fossilizedbinding.value, xmlw); } if (torender.fossilizedshaper != null) { RenderUtil.dumpHiddenField(torender.fossilizedshaper.name, torender.fossilizedshaper.value, xmlw); } } } // No, this method will not stay like this forever! We plan on an architecture // with renderer-per-component "class" as before, plus interceptors. // Although a lot of the parameterisation now lies in the allowable tag // set at target. public int renderComponent(UIComponent torendero, View view, XMLLump[] lumps, int lumpindex, PrintOutputStream pos) { XMLWriter xmlw = new XMLWriter(pos); XMLLump lump = lumps[lumpindex]; int nextpos = -1; XMLLump outerendopen = lump.open_end; XMLLump outerclose = lump.close_tag; nextpos = outerclose.lumpindex + 1; XMLLumpList payloadlist = lump.downmap == null ? null : lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap .headsForID(XMLLump.PAYLOAD_COMPONENT) : null; XMLLump payload = payloadlist == null ? null : payloadlist.lumpAt(0); // if there is no peer component, it might still be a static resource holder // that needs URLs rewriting. // we assume there is no payload component here, since there is no producer // ID that might govern selection. So we use "outer" indices. if (torendero == null) { if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) { String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length()); StaticComponentRenderer scr = scrc.getSCR(scrname); if (scr != null) { int tagtype = scr.render(lumps, lumpindex, xmlw); nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1 : outerendopen.lumpindex + 1; } } if (lump.textEquals("<form ")) { Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID + " and all children at " + lump.toDebugString() + " since no peer component"); } } else { // else there IS a component and we are going to render it. First make // sure we render any preamble. XMLLump endopen = outerendopen; XMLLump close = outerclose; XMLLump uselump = lump; if (payload != null) { endopen = payload.open_end; close = payload.close_tag; uselump = payload; RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos); lumpindex = payload.lumpindex; } String fullID = torendero.getFullID(); HashMap attrcopy = new HashMap(); attrcopy.putAll(uselump.attributemap); attrcopy.put("id", fullID); attrcopy.remove(XMLLump.ID_ATTRIBUTE); decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy); TagRenderContext rendercontext = new TagRenderContext(attrcopy, lumps, uselump, endopen, close, pos, xmlw); // ALWAYS dump the tag name, this can never be rewritten. (probably?!) pos.write(uselump.buffer, uselump.start, uselump.length); // TODO: Note that these are actually BOUND now. Create some kind of // defaultBoundRenderer. if (torendero instanceof UIBound) { UIBound torender = (UIBound) torendero; if (!torender.willinput) { if (torendero.getClass() == UIOutput.class) { String value = ((UIOutput) torendero).getValue(); rewriteLeaf(value, rendercontext); } else if (torendero.getClass() == UIOutputMultiline.class) { StringList value = ((UIOutputMultiline) torendero).getValue(); if (value == null) { RenderUtil.dumpTillLump(lumps, lumpindex + 1, close.lumpindex + 1, pos); } else { XMLUtil.dumpAttributes(attrcopy, xmlw); pos.print(">"); for (int i = 0; i < value.size(); ++i) { if (i != 0) { pos.print("<br/>"); } xmlw.write(value.stringAt(i)); } closeTag(pos, uselump); } } else if (torender.getClass() == UIAnchor.class) { String value = ((UIAnchor) torendero).getValue(); if (UITypes.isPlaceholder(value)) { renderUnchanged(rendercontext); } else { attrcopy.put("name", value); replaceAttributes(rendercontext); } } } // factor out component-invariant processing of UIBound. else { // Bound with willinput = true attrcopy.put("name", fullID); // attrcopy.put("id", fullID); String value = ""; String body = null; if (torendero instanceof UIInput) { value = ((UIInput) torender).getValue(); if (uselump.textEquals("<textarea ")) { body = value; } else { attrcopy.put("value", value); } } else if (torendero instanceof UIBoundBoolean) { if (((UIBoundBoolean) torender).getValue()) { attrcopy.put("checked", "yes"); } else { attrcopy.remove("checked"); } attrcopy.put("value", "true"); } rewriteLeaf(body, rendercontext); // unify hidden field processing? ANY parameter children found must // be dumped as hidden fields. } // dump any fossilized binding for this component. dumpBoundFields(torender, xmlw); } // end if UIBound else if (torendero instanceof UISelect) { UISelect select = (UISelect) torendero; // The HTML submitted value from a <select> actually corresponds // with the selection member, not the top-level component. attrcopy.put("name", select.selection.submittingname); attrcopy.put("id", select.selection.getFullID()); boolean ishtmlselect = uselump.textEquals("<select "); if (select.selection instanceof UIBoundList && ishtmlselect) { attrcopy.put("multiple", "true"); } XMLUtil.dumpAttributes(attrcopy, xmlw); if (ishtmlselect) { pos.print(">"); String[] values = select.optionlist.getValue(); String[] names = select.optionnames == null ? values : select.optionnames.getValue(); for (int i = 0; i < names.length; ++i) { pos.print("<option value=\""); xmlw.write(values[i]); if (select.selected.contains(values[i])) { pos.print("\" selected=\"true"); } pos.print("\">"); xmlw.write(names[i]); pos.print("</option>\n"); } closeTag(pos, uselump); } else { dumpTemplateBody(rendercontext); } dumpBoundFields(select.selection, xmlw); dumpBoundFields(select.optionlist, xmlw); dumpBoundFields(select.optionnames, xmlw); } else if (torendero instanceof UISelectChoice) { UISelectChoice torender = (UISelectChoice) torendero; UISelect parent = (UISelect) view.getComponent(torender.parentFullID); String value = parent.optionlist.getValue()[torender.choiceindex]; // currently only peers with "input type="radio"". attrcopy.put("name", torender.parentFullID +"-selection"); attrcopy.put("value", value); attrcopy.remove("checked"); if (parent.selected.contains(value)) { attrcopy.put("checked", "true"); } replaceAttributes(rendercontext); } else if (torendero instanceof UISelectLabel) { UISelectLabel torender = (UISelectLabel) torendero; UISelect parent = (UISelect) view.getComponent(torender.parentFullID); String value = parent.optionnames.getValue()[torender.choiceindex]; replaceBody(value, rendercontext); } else if (torendero instanceof UILink) { UILink torender = (UILink) torendero; String attrname = URLRewriteSCR.getLinkAttribute(uselump); if (attrname != null) { String target = torender.target.getValue(); + if (target == null || target.length() == 0) { + throw new IllegalArgumentException("Empty URL in UILink at " + uselump.toDebugString()); + } URLRewriteSCR urlrewriter = (URLRewriteSCR) scrc.getSCR(URLRewriteSCR.NAME); if (!URLUtil.isAbsolute(target)) { String rewritten = urlrewriter.resolveURL(target); if (rewritten != null) target = rewritten; } attrcopy.put(attrname, target); } String value = torender.linktext == null ? null : torender.linktext.getValue(); rewriteLeaf(value, rendercontext); } else if (torendero instanceof UICommand) { UICommand torender = (UICommand) torendero; String value = RenderUtil.makeURLAttributes(torender.parameters); // any desired "attributes" decoded for JUST THIS ACTION must be // secretly // bundled as this special attribute. attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS + value); String text = torender.commandtext; boolean isbutton = lump.textEquals("<button "); if (text != null && !isbutton) { attrcopy.put("value", torender.commandtext); text = null; } rewriteLeaf(text, rendercontext); // RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD, // torender.actionhandler, pos); } // Forms behave slightly oddly in the hierarchy - by the time they reach // the renderer, they have been "shunted out" of line with their children, // i.e. any "submitting" controls, if indeed they ever were there. else if (torendero instanceof UIForm) { UIForm torender = (UIForm) torendero; if (attrcopy.get("method") == null) { // forms DEFAULT to be post attrcopy.put("method", "post"); } // form fixer guarantees that this URL is attribute free. attrcopy.put("action", torender.targetURL); XMLUtil.dumpAttributes(attrcopy, xmlw); pos.println(">"); for (int i = 0; i < torender.parameters.size(); ++i) { UIParameter param = torender.parameters.parameterAt(i); RenderUtil.dumpHiddenField(param.name, param.value, xmlw); } // override "nextpos" - form is expected to contain numerous nested // Components. // this is the only ANOMALY!! Forms together with payload cannot work. // the fact we are at the wrong recursion level will "come out in the // wash" // since we must return to the base recursion level before we exit this // domain. // Assuming there are no paths *IN* through forms that do not also lead // *OUT* there will be no problem. Check what this *MEANS* tomorrow. nextpos = endopen.lumpindex + 1; } else if (torendero instanceof UIVerbatim) { UIVerbatim torender = (UIVerbatim) torendero; String rendered = null; // inefficient implementation for now, upgrade when we write bulk POS // utils. if (torender.markup instanceof InputStream) { rendered = StreamCopyUtil .streamToString((InputStream) torender.markup); } else if (torender.markup instanceof Reader) { rendered = StreamCopyUtil.readerToString((Reader) torender.markup); } else if (torender.markup != null) { rendered = torender.markup.toString(); } if (rendered == null) { renderUnchanged(rendercontext); } else { XMLUtil.dumpAttributes(attrcopy, xmlw); pos.print(">"); pos.print(rendered); closeTag(pos, uselump); } } // if there is a payload, dump the postamble. if (payload != null) { RenderUtil.dumpTillLump(lumps, close.lumpindex + 1, outerclose.lumpindex + 1, pos); } } return nextpos; } private void renderUnchanged(TagRenderContext c) { RenderUtil.dumpTillLump(c.lumps, c.uselump.lumpindex + 1, c.close.lumpindex + 1, c.pos); } private void rewriteLeaf(String value, TagRenderContext c) { if (value != null && !UITypes.isPlaceholder(value)) replaceBody(value, c); else replaceAttributes(c); } private void replaceBody(String value, TagRenderContext c) { XMLUtil.dumpAttributes(c.attrcopy, c.xmlw); c.pos.print(">"); c.xmlw.write(value); closeTag(c.pos, c.uselump); } private void replaceAttributes(TagRenderContext c) { XMLUtil.dumpAttributes(c.attrcopy, c.xmlw); dumpTemplateBody(c); } private void dumpTemplateBody(TagRenderContext c) { if (c.endopen.lumpindex == c.close.lumpindex) { c.pos.print("/>"); } else { c.pos.print(">"); RenderUtil.dumpTillLump(c.lumps, c.endopen.lumpindex + 1, c.close.lumpindex + 1, c.pos); } } }
true
true
public int renderComponent(UIComponent torendero, View view, XMLLump[] lumps, int lumpindex, PrintOutputStream pos) { XMLWriter xmlw = new XMLWriter(pos); XMLLump lump = lumps[lumpindex]; int nextpos = -1; XMLLump outerendopen = lump.open_end; XMLLump outerclose = lump.close_tag; nextpos = outerclose.lumpindex + 1; XMLLumpList payloadlist = lump.downmap == null ? null : lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap .headsForID(XMLLump.PAYLOAD_COMPONENT) : null; XMLLump payload = payloadlist == null ? null : payloadlist.lumpAt(0); // if there is no peer component, it might still be a static resource holder // that needs URLs rewriting. // we assume there is no payload component here, since there is no producer // ID that might govern selection. So we use "outer" indices. if (torendero == null) { if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) { String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length()); StaticComponentRenderer scr = scrc.getSCR(scrname); if (scr != null) { int tagtype = scr.render(lumps, lumpindex, xmlw); nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1 : outerendopen.lumpindex + 1; } } if (lump.textEquals("<form ")) { Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID + " and all children at " + lump.toDebugString() + " since no peer component"); } } else { // else there IS a component and we are going to render it. First make // sure we render any preamble. XMLLump endopen = outerendopen; XMLLump close = outerclose; XMLLump uselump = lump; if (payload != null) { endopen = payload.open_end; close = payload.close_tag; uselump = payload; RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos); lumpindex = payload.lumpindex; } String fullID = torendero.getFullID(); HashMap attrcopy = new HashMap(); attrcopy.putAll(uselump.attributemap); attrcopy.put("id", fullID); attrcopy.remove(XMLLump.ID_ATTRIBUTE); decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy); TagRenderContext rendercontext = new TagRenderContext(attrcopy, lumps, uselump, endopen, close, pos, xmlw); // ALWAYS dump the tag name, this can never be rewritten. (probably?!) pos.write(uselump.buffer, uselump.start, uselump.length); // TODO: Note that these are actually BOUND now. Create some kind of // defaultBoundRenderer. if (torendero instanceof UIBound) { UIBound torender = (UIBound) torendero; if (!torender.willinput) { if (torendero.getClass() == UIOutput.class) { String value = ((UIOutput) torendero).getValue(); rewriteLeaf(value, rendercontext); } else if (torendero.getClass() == UIOutputMultiline.class) { StringList value = ((UIOutputMultiline) torendero).getValue(); if (value == null) { RenderUtil.dumpTillLump(lumps, lumpindex + 1, close.lumpindex + 1, pos); } else { XMLUtil.dumpAttributes(attrcopy, xmlw); pos.print(">"); for (int i = 0; i < value.size(); ++i) { if (i != 0) { pos.print("<br/>"); } xmlw.write(value.stringAt(i)); } closeTag(pos, uselump); } } else if (torender.getClass() == UIAnchor.class) { String value = ((UIAnchor) torendero).getValue(); if (UITypes.isPlaceholder(value)) { renderUnchanged(rendercontext); } else { attrcopy.put("name", value); replaceAttributes(rendercontext); } } } // factor out component-invariant processing of UIBound. else { // Bound with willinput = true attrcopy.put("name", fullID); // attrcopy.put("id", fullID); String value = ""; String body = null; if (torendero instanceof UIInput) { value = ((UIInput) torender).getValue(); if (uselump.textEquals("<textarea ")) { body = value; } else { attrcopy.put("value", value); } } else if (torendero instanceof UIBoundBoolean) { if (((UIBoundBoolean) torender).getValue()) { attrcopy.put("checked", "yes"); } else { attrcopy.remove("checked"); } attrcopy.put("value", "true"); } rewriteLeaf(body, rendercontext); // unify hidden field processing? ANY parameter children found must // be dumped as hidden fields. } // dump any fossilized binding for this component. dumpBoundFields(torender, xmlw); } // end if UIBound else if (torendero instanceof UISelect) { UISelect select = (UISelect) torendero; // The HTML submitted value from a <select> actually corresponds // with the selection member, not the top-level component. attrcopy.put("name", select.selection.submittingname); attrcopy.put("id", select.selection.getFullID()); boolean ishtmlselect = uselump.textEquals("<select "); if (select.selection instanceof UIBoundList && ishtmlselect) { attrcopy.put("multiple", "true"); } XMLUtil.dumpAttributes(attrcopy, xmlw); if (ishtmlselect) { pos.print(">"); String[] values = select.optionlist.getValue(); String[] names = select.optionnames == null ? values : select.optionnames.getValue(); for (int i = 0; i < names.length; ++i) { pos.print("<option value=\""); xmlw.write(values[i]); if (select.selected.contains(values[i])) { pos.print("\" selected=\"true"); } pos.print("\">"); xmlw.write(names[i]); pos.print("</option>\n"); } closeTag(pos, uselump); } else { dumpTemplateBody(rendercontext); } dumpBoundFields(select.selection, xmlw); dumpBoundFields(select.optionlist, xmlw); dumpBoundFields(select.optionnames, xmlw); } else if (torendero instanceof UISelectChoice) { UISelectChoice torender = (UISelectChoice) torendero; UISelect parent = (UISelect) view.getComponent(torender.parentFullID); String value = parent.optionlist.getValue()[torender.choiceindex]; // currently only peers with "input type="radio"". attrcopy.put("name", torender.parentFullID +"-selection"); attrcopy.put("value", value); attrcopy.remove("checked"); if (parent.selected.contains(value)) { attrcopy.put("checked", "true"); } replaceAttributes(rendercontext); } else if (torendero instanceof UISelectLabel) { UISelectLabel torender = (UISelectLabel) torendero; UISelect parent = (UISelect) view.getComponent(torender.parentFullID); String value = parent.optionnames.getValue()[torender.choiceindex]; replaceBody(value, rendercontext); } else if (torendero instanceof UILink) { UILink torender = (UILink) torendero; String attrname = URLRewriteSCR.getLinkAttribute(uselump); if (attrname != null) { String target = torender.target.getValue(); URLRewriteSCR urlrewriter = (URLRewriteSCR) scrc.getSCR(URLRewriteSCR.NAME); if (!URLUtil.isAbsolute(target)) { String rewritten = urlrewriter.resolveURL(target); if (rewritten != null) target = rewritten; } attrcopy.put(attrname, target); } String value = torender.linktext == null ? null : torender.linktext.getValue(); rewriteLeaf(value, rendercontext); } else if (torendero instanceof UICommand) { UICommand torender = (UICommand) torendero; String value = RenderUtil.makeURLAttributes(torender.parameters); // any desired "attributes" decoded for JUST THIS ACTION must be // secretly // bundled as this special attribute. attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS + value); String text = torender.commandtext; boolean isbutton = lump.textEquals("<button "); if (text != null && !isbutton) { attrcopy.put("value", torender.commandtext); text = null; } rewriteLeaf(text, rendercontext); // RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD, // torender.actionhandler, pos); } // Forms behave slightly oddly in the hierarchy - by the time they reach // the renderer, they have been "shunted out" of line with their children, // i.e. any "submitting" controls, if indeed they ever were there. else if (torendero instanceof UIForm) { UIForm torender = (UIForm) torendero; if (attrcopy.get("method") == null) { // forms DEFAULT to be post attrcopy.put("method", "post"); } // form fixer guarantees that this URL is attribute free. attrcopy.put("action", torender.targetURL); XMLUtil.dumpAttributes(attrcopy, xmlw); pos.println(">"); for (int i = 0; i < torender.parameters.size(); ++i) { UIParameter param = torender.parameters.parameterAt(i); RenderUtil.dumpHiddenField(param.name, param.value, xmlw); } // override "nextpos" - form is expected to contain numerous nested // Components. // this is the only ANOMALY!! Forms together with payload cannot work. // the fact we are at the wrong recursion level will "come out in the // wash" // since we must return to the base recursion level before we exit this // domain. // Assuming there are no paths *IN* through forms that do not also lead // *OUT* there will be no problem. Check what this *MEANS* tomorrow. nextpos = endopen.lumpindex + 1; } else if (torendero instanceof UIVerbatim) { UIVerbatim torender = (UIVerbatim) torendero; String rendered = null; // inefficient implementation for now, upgrade when we write bulk POS // utils. if (torender.markup instanceof InputStream) { rendered = StreamCopyUtil .streamToString((InputStream) torender.markup); } else if (torender.markup instanceof Reader) { rendered = StreamCopyUtil.readerToString((Reader) torender.markup); } else if (torender.markup != null) { rendered = torender.markup.toString(); } if (rendered == null) { renderUnchanged(rendercontext); } else { XMLUtil.dumpAttributes(attrcopy, xmlw); pos.print(">"); pos.print(rendered); closeTag(pos, uselump); } } // if there is a payload, dump the postamble. if (payload != null) { RenderUtil.dumpTillLump(lumps, close.lumpindex + 1, outerclose.lumpindex + 1, pos); } } return nextpos; }
public int renderComponent(UIComponent torendero, View view, XMLLump[] lumps, int lumpindex, PrintOutputStream pos) { XMLWriter xmlw = new XMLWriter(pos); XMLLump lump = lumps[lumpindex]; int nextpos = -1; XMLLump outerendopen = lump.open_end; XMLLump outerclose = lump.close_tag; nextpos = outerclose.lumpindex + 1; XMLLumpList payloadlist = lump.downmap == null ? null : lump.downmap.hasID(XMLLump.PAYLOAD_COMPONENT) ? lump.downmap .headsForID(XMLLump.PAYLOAD_COMPONENT) : null; XMLLump payload = payloadlist == null ? null : payloadlist.lumpAt(0); // if there is no peer component, it might still be a static resource holder // that needs URLs rewriting. // we assume there is no payload component here, since there is no producer // ID that might govern selection. So we use "outer" indices. if (torendero == null) { if (lump.rsfID.startsWith(XMLLump.SCR_PREFIX)) { String scrname = lump.rsfID.substring(XMLLump.SCR_PREFIX.length()); StaticComponentRenderer scr = scrc.getSCR(scrname); if (scr != null) { int tagtype = scr.render(lumps, lumpindex, xmlw); nextpos = tagtype == ComponentRenderer.LEAF_TAG ? outerclose.lumpindex + 1 : outerendopen.lumpindex + 1; } } if (lump.textEquals("<form ")) { Logger.log.warn("Warning: skipping form tag with rsf:id " + lump.rsfID + " and all children at " + lump.toDebugString() + " since no peer component"); } } else { // else there IS a component and we are going to render it. First make // sure we render any preamble. XMLLump endopen = outerendopen; XMLLump close = outerclose; XMLLump uselump = lump; if (payload != null) { endopen = payload.open_end; close = payload.close_tag; uselump = payload; RenderUtil.dumpTillLump(lumps, lumpindex, payload.lumpindex, pos); lumpindex = payload.lumpindex; } String fullID = torendero.getFullID(); HashMap attrcopy = new HashMap(); attrcopy.putAll(uselump.attributemap); attrcopy.put("id", fullID); attrcopy.remove(XMLLump.ID_ATTRIBUTE); decoratormanager.decorate(torendero.decorators, uselump.getTag(), attrcopy); TagRenderContext rendercontext = new TagRenderContext(attrcopy, lumps, uselump, endopen, close, pos, xmlw); // ALWAYS dump the tag name, this can never be rewritten. (probably?!) pos.write(uselump.buffer, uselump.start, uselump.length); // TODO: Note that these are actually BOUND now. Create some kind of // defaultBoundRenderer. if (torendero instanceof UIBound) { UIBound torender = (UIBound) torendero; if (!torender.willinput) { if (torendero.getClass() == UIOutput.class) { String value = ((UIOutput) torendero).getValue(); rewriteLeaf(value, rendercontext); } else if (torendero.getClass() == UIOutputMultiline.class) { StringList value = ((UIOutputMultiline) torendero).getValue(); if (value == null) { RenderUtil.dumpTillLump(lumps, lumpindex + 1, close.lumpindex + 1, pos); } else { XMLUtil.dumpAttributes(attrcopy, xmlw); pos.print(">"); for (int i = 0; i < value.size(); ++i) { if (i != 0) { pos.print("<br/>"); } xmlw.write(value.stringAt(i)); } closeTag(pos, uselump); } } else if (torender.getClass() == UIAnchor.class) { String value = ((UIAnchor) torendero).getValue(); if (UITypes.isPlaceholder(value)) { renderUnchanged(rendercontext); } else { attrcopy.put("name", value); replaceAttributes(rendercontext); } } } // factor out component-invariant processing of UIBound. else { // Bound with willinput = true attrcopy.put("name", fullID); // attrcopy.put("id", fullID); String value = ""; String body = null; if (torendero instanceof UIInput) { value = ((UIInput) torender).getValue(); if (uselump.textEquals("<textarea ")) { body = value; } else { attrcopy.put("value", value); } } else if (torendero instanceof UIBoundBoolean) { if (((UIBoundBoolean) torender).getValue()) { attrcopy.put("checked", "yes"); } else { attrcopy.remove("checked"); } attrcopy.put("value", "true"); } rewriteLeaf(body, rendercontext); // unify hidden field processing? ANY parameter children found must // be dumped as hidden fields. } // dump any fossilized binding for this component. dumpBoundFields(torender, xmlw); } // end if UIBound else if (torendero instanceof UISelect) { UISelect select = (UISelect) torendero; // The HTML submitted value from a <select> actually corresponds // with the selection member, not the top-level component. attrcopy.put("name", select.selection.submittingname); attrcopy.put("id", select.selection.getFullID()); boolean ishtmlselect = uselump.textEquals("<select "); if (select.selection instanceof UIBoundList && ishtmlselect) { attrcopy.put("multiple", "true"); } XMLUtil.dumpAttributes(attrcopy, xmlw); if (ishtmlselect) { pos.print(">"); String[] values = select.optionlist.getValue(); String[] names = select.optionnames == null ? values : select.optionnames.getValue(); for (int i = 0; i < names.length; ++i) { pos.print("<option value=\""); xmlw.write(values[i]); if (select.selected.contains(values[i])) { pos.print("\" selected=\"true"); } pos.print("\">"); xmlw.write(names[i]); pos.print("</option>\n"); } closeTag(pos, uselump); } else { dumpTemplateBody(rendercontext); } dumpBoundFields(select.selection, xmlw); dumpBoundFields(select.optionlist, xmlw); dumpBoundFields(select.optionnames, xmlw); } else if (torendero instanceof UISelectChoice) { UISelectChoice torender = (UISelectChoice) torendero; UISelect parent = (UISelect) view.getComponent(torender.parentFullID); String value = parent.optionlist.getValue()[torender.choiceindex]; // currently only peers with "input type="radio"". attrcopy.put("name", torender.parentFullID +"-selection"); attrcopy.put("value", value); attrcopy.remove("checked"); if (parent.selected.contains(value)) { attrcopy.put("checked", "true"); } replaceAttributes(rendercontext); } else if (torendero instanceof UISelectLabel) { UISelectLabel torender = (UISelectLabel) torendero; UISelect parent = (UISelect) view.getComponent(torender.parentFullID); String value = parent.optionnames.getValue()[torender.choiceindex]; replaceBody(value, rendercontext); } else if (torendero instanceof UILink) { UILink torender = (UILink) torendero; String attrname = URLRewriteSCR.getLinkAttribute(uselump); if (attrname != null) { String target = torender.target.getValue(); if (target == null || target.length() == 0) { throw new IllegalArgumentException("Empty URL in UILink at " + uselump.toDebugString()); } URLRewriteSCR urlrewriter = (URLRewriteSCR) scrc.getSCR(URLRewriteSCR.NAME); if (!URLUtil.isAbsolute(target)) { String rewritten = urlrewriter.resolveURL(target); if (rewritten != null) target = rewritten; } attrcopy.put(attrname, target); } String value = torender.linktext == null ? null : torender.linktext.getValue(); rewriteLeaf(value, rendercontext); } else if (torendero instanceof UICommand) { UICommand torender = (UICommand) torendero; String value = RenderUtil.makeURLAttributes(torender.parameters); // any desired "attributes" decoded for JUST THIS ACTION must be // secretly // bundled as this special attribute. attrcopy.put("name", FossilizedConverter.COMMAND_LINK_PARAMETERS + value); String text = torender.commandtext; boolean isbutton = lump.textEquals("<button "); if (text != null && !isbutton) { attrcopy.put("value", torender.commandtext); text = null; } rewriteLeaf(text, rendercontext); // RenderUtil.dumpHiddenField(SubmittedValueEntry.ACTION_METHOD, // torender.actionhandler, pos); } // Forms behave slightly oddly in the hierarchy - by the time they reach // the renderer, they have been "shunted out" of line with their children, // i.e. any "submitting" controls, if indeed they ever were there. else if (torendero instanceof UIForm) { UIForm torender = (UIForm) torendero; if (attrcopy.get("method") == null) { // forms DEFAULT to be post attrcopy.put("method", "post"); } // form fixer guarantees that this URL is attribute free. attrcopy.put("action", torender.targetURL); XMLUtil.dumpAttributes(attrcopy, xmlw); pos.println(">"); for (int i = 0; i < torender.parameters.size(); ++i) { UIParameter param = torender.parameters.parameterAt(i); RenderUtil.dumpHiddenField(param.name, param.value, xmlw); } // override "nextpos" - form is expected to contain numerous nested // Components. // this is the only ANOMALY!! Forms together with payload cannot work. // the fact we are at the wrong recursion level will "come out in the // wash" // since we must return to the base recursion level before we exit this // domain. // Assuming there are no paths *IN* through forms that do not also lead // *OUT* there will be no problem. Check what this *MEANS* tomorrow. nextpos = endopen.lumpindex + 1; } else if (torendero instanceof UIVerbatim) { UIVerbatim torender = (UIVerbatim) torendero; String rendered = null; // inefficient implementation for now, upgrade when we write bulk POS // utils. if (torender.markup instanceof InputStream) { rendered = StreamCopyUtil .streamToString((InputStream) torender.markup); } else if (torender.markup instanceof Reader) { rendered = StreamCopyUtil.readerToString((Reader) torender.markup); } else if (torender.markup != null) { rendered = torender.markup.toString(); } if (rendered == null) { renderUnchanged(rendercontext); } else { XMLUtil.dumpAttributes(attrcopy, xmlw); pos.print(">"); pos.print(rendered); closeTag(pos, uselump); } } // if there is a payload, dump the postamble. if (payload != null) { RenderUtil.dumpTillLump(lumps, close.lumpindex + 1, outerclose.lumpindex + 1, pos); } } return nextpos; }
diff --git a/geoportal_1/src/main/java/org/OpenGeoPortal/Ogc/Wfs/WfsGetFeature.java b/geoportal_1/src/main/java/org/OpenGeoPortal/Ogc/Wfs/WfsGetFeature.java index 85e6dc7..71b7b63 100644 --- a/geoportal_1/src/main/java/org/OpenGeoPortal/Ogc/Wfs/WfsGetFeature.java +++ b/geoportal_1/src/main/java/org/OpenGeoPortal/Ogc/Wfs/WfsGetFeature.java @@ -1,80 +1,80 @@ package org.OpenGeoPortal.Ogc.Wfs; import org.OpenGeoPortal.Download.Types.BoundingBox; import org.OpenGeoPortal.Utilities.OgpUtils; public class WfsGetFeature { public static String createWfsGetFeatureRequest(String layerName, String workSpace, String nameSpace, String outputFormat, String filter) throws Exception { return createWfsGetFeatureRequest(layerName, workSpace, nameSpace, -1, "", outputFormat, filter); } private static String getAttributeString(String attrName, int value){ String attrString = ""; if(value > 0){ attrString = " " + attrName + "=\"" + Integer.toString(value) + "\""; } return attrString; } private static String getAttributeString(String attrName, String value){ String attrString = ""; if(!value.trim().isEmpty()){ attrString = " " + attrName + "=\"" + value.trim() + "\""; } return attrString; } public static String createWfsGetFeatureRequest(String layerName, String workSpace, String nameSpace, int maxFeatures, String epsgCode, String outputFormat, String filter) throws Exception { //--generate POST message //info needed: geometry column, bbox coords, epsg code, workspace & layername - String layerNameNS = OgpUtils.getLayerNameNS(layerName, workSpace); + String layerNameNS = OgpUtils.getLayerNameNS(workSpace, layerName); String getFeatureRequest = "<wfs:GetFeature service=\"WFS\" version=\"1.0.0\"" + " outputFormat=\"" + outputFormat + "\"" + getAttributeString("maxfeatures", maxFeatures) + getAttributeString("srsName", epsgCode) + getNameSpaceString(workSpace, nameSpace) + " xmlns:wfs=\"http://www.opengis.net/wfs\"" + " xmlns:ogc=\"http://www.opengis.net/ogc\"" + " xmlns:gml=\"http://www.opengis.net/gml\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"http://www.opengis.net/wfs" + " http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd\">" + "<wfs:Query typeName=\"" + layerNameNS + "\">" + filter + "</wfs:Query>" + "</wfs:GetFeature>"; return getFeatureRequest; } public static String getMethod(){ return "POST"; } private static String getNameSpaceString(String workSpace, String nameSpace){ //if either is missing, skip the whole thing String nsString = ""; if (!workSpace.trim().isEmpty() && !nameSpace.trim().isEmpty()){ nsString = " xmlns:" + workSpace + "=\"" + nameSpace + "\""; } return nsString; } public static String getBboxFilter(BoundingBox bounds, String geometryColumn, int epsgCode){ String bboxFilter = "<ogc:Filter>" + "<ogc:BBOX>" + "<ogc:PropertyName>" + geometryColumn + "</ogc:PropertyName>" + bounds.generateGMLBox(epsgCode) + "</ogc:BBOX>" + "</ogc:Filter>"; return bboxFilter; } }
true
true
public static String createWfsGetFeatureRequest(String layerName, String workSpace, String nameSpace, int maxFeatures, String epsgCode, String outputFormat, String filter) throws Exception { //--generate POST message //info needed: geometry column, bbox coords, epsg code, workspace & layername String layerNameNS = OgpUtils.getLayerNameNS(layerName, workSpace); String getFeatureRequest = "<wfs:GetFeature service=\"WFS\" version=\"1.0.0\"" + " outputFormat=\"" + outputFormat + "\"" + getAttributeString("maxfeatures", maxFeatures) + getAttributeString("srsName", epsgCode) + getNameSpaceString(workSpace, nameSpace) + " xmlns:wfs=\"http://www.opengis.net/wfs\"" + " xmlns:ogc=\"http://www.opengis.net/ogc\"" + " xmlns:gml=\"http://www.opengis.net/gml\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"http://www.opengis.net/wfs" + " http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd\">" + "<wfs:Query typeName=\"" + layerNameNS + "\">" + filter + "</wfs:Query>" + "</wfs:GetFeature>"; return getFeatureRequest; }
public static String createWfsGetFeatureRequest(String layerName, String workSpace, String nameSpace, int maxFeatures, String epsgCode, String outputFormat, String filter) throws Exception { //--generate POST message //info needed: geometry column, bbox coords, epsg code, workspace & layername String layerNameNS = OgpUtils.getLayerNameNS(workSpace, layerName); String getFeatureRequest = "<wfs:GetFeature service=\"WFS\" version=\"1.0.0\"" + " outputFormat=\"" + outputFormat + "\"" + getAttributeString("maxfeatures", maxFeatures) + getAttributeString("srsName", epsgCode) + getNameSpaceString(workSpace, nameSpace) + " xmlns:wfs=\"http://www.opengis.net/wfs\"" + " xmlns:ogc=\"http://www.opengis.net/ogc\"" + " xmlns:gml=\"http://www.opengis.net/gml\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"http://www.opengis.net/wfs" + " http://schemas.opengis.net/wfs/1.0.0/WFS-basic.xsd\">" + "<wfs:Query typeName=\"" + layerNameNS + "\">" + filter + "</wfs:Query>" + "</wfs:GetFeature>"; return getFeatureRequest; }
diff --git a/src/rentalcar/MemberHomePanel.java b/src/rentalcar/MemberHomePanel.java index 9c78ebd..56fdf2b 100644 --- a/src/rentalcar/MemberHomePanel.java +++ b/src/rentalcar/MemberHomePanel.java @@ -1,83 +1,84 @@ package rentalcar; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import core.User.MemberUser; /** * @author Sahil Gupta This class is the home page for students and Georgia Tech * staff/faculty. */ public class MemberHomePanel extends JPanel { private static final long serialVersionUID = 1L; final static Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); private MemberUser member; private JFrame mainFrame; private JLabel heading; private JRadioButton carRental, enterViewPI, ViewRentalInfo; private String headingString = "Homepage"; private String carRentalString = "Rent a car"; private String enterViewPIString = "Enter/View Personal Information"; private String ViewRentalInfoString = "View Rental Information"; /** * Sets up a panel with a label and a set of radio buttons that control its * text. */ public MemberHomePanel(MemberUser member) { this.mainFrame = MainFrame.getMain(); this.member = member; this.setBackground(Color.green); this.setLayout(new FlowLayout()); setBounds(screenSize.width/2-200, screenSize.height/2-100, - 300, 200); + 250, 225); heading = new JLabel(headingString); heading.setFont(new Font("Helvetica", Font.BOLD, 40)); carRental = new JRadioButton(carRentalString); carRental.setBackground(Color.green); enterViewPI = new JRadioButton(enterViewPIString); enterViewPI.setBackground(Color.green); ViewRentalInfo = new JRadioButton(ViewRentalInfoString); ViewRentalInfo.setBackground(Color.green); JButton nextButton = new JButton("Next >>"); nextButton.addActionListener(new NextButtonListener()); this.add(heading); this.add(carRental); this.add(enterViewPI); this.add(ViewRentalInfo); + this.add(nextButton); } private class NextButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source == carRental) { mainFrame.setContentPane(new RentCarPanel(member)); mainFrame.setBounds(mainFrame.getContentPane().getBounds()); mainFrame.setVisible(true); mainFrame.repaint(); } else if (source == enterViewPI) { mainFrame.setContentPane(new MemberPInfoPanel(member)); mainFrame.setBounds(mainFrame.getContentPane().getBounds()); mainFrame.setVisible(true); mainFrame.repaint(); } else if (source == ViewRentalInfo) { mainFrame.setContentPane(new RentInfoPanel(member)); mainFrame.setBounds(mainFrame.getContentPane().getBounds()); mainFrame.setVisible(true); mainFrame.repaint(); } } } }
false
true
public MemberHomePanel(MemberUser member) { this.mainFrame = MainFrame.getMain(); this.member = member; this.setBackground(Color.green); this.setLayout(new FlowLayout()); setBounds(screenSize.width/2-200, screenSize.height/2-100, 300, 200); heading = new JLabel(headingString); heading.setFont(new Font("Helvetica", Font.BOLD, 40)); carRental = new JRadioButton(carRentalString); carRental.setBackground(Color.green); enterViewPI = new JRadioButton(enterViewPIString); enterViewPI.setBackground(Color.green); ViewRentalInfo = new JRadioButton(ViewRentalInfoString); ViewRentalInfo.setBackground(Color.green); JButton nextButton = new JButton("Next >>"); nextButton.addActionListener(new NextButtonListener()); this.add(heading); this.add(carRental); this.add(enterViewPI); this.add(ViewRentalInfo); }
public MemberHomePanel(MemberUser member) { this.mainFrame = MainFrame.getMain(); this.member = member; this.setBackground(Color.green); this.setLayout(new FlowLayout()); setBounds(screenSize.width/2-200, screenSize.height/2-100, 250, 225); heading = new JLabel(headingString); heading.setFont(new Font("Helvetica", Font.BOLD, 40)); carRental = new JRadioButton(carRentalString); carRental.setBackground(Color.green); enterViewPI = new JRadioButton(enterViewPIString); enterViewPI.setBackground(Color.green); ViewRentalInfo = new JRadioButton(ViewRentalInfoString); ViewRentalInfo.setBackground(Color.green); JButton nextButton = new JButton("Next >>"); nextButton.addActionListener(new NextButtonListener()); this.add(heading); this.add(carRental); this.add(enterViewPI); this.add(ViewRentalInfo); this.add(nextButton); }
diff --git a/grails/src/java/org/codehaus/groovy/grails/web/pages/SitemeshPreprocessor.java b/grails/src/java/org/codehaus/groovy/grails/web/pages/SitemeshPreprocessor.java index 77ec8cfb5..2846f1e6b 100644 --- a/grails/src/java/org/codehaus/groovy/grails/web/pages/SitemeshPreprocessor.java +++ b/grails/src/java/org/codehaus/groovy/grails/web/pages/SitemeshPreprocessor.java @@ -1,77 +1,79 @@ package org.codehaus.groovy.grails.web.pages; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * This class is used to add GSP Sitemesh integration directly to compiled GSP. * * head, meta, title, body and content tags are replaced with <sitemesh:capture*>...</sitemesh:capture*> taglibs * * The taglib is used to capture the content of each tag. This prevents the need to parse the content output like Sitemesh normally does. * * * @author <a href="mailto:[email protected]">Lari Hotari, Sagire Software Oy</a> * */ public class SitemeshPreprocessor { Pattern parameterPattern=Pattern.compile("<parameter(\\s+name[^>]+?)(/*?)>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Pattern metaPattern=Pattern.compile("<meta(\\s[^>]+?)(/*?)>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Pattern titlePattern=Pattern.compile("<title(\\s[^>]*)?>(.*?)</title>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Pattern headPattern=Pattern.compile("<head(\\s[^>]*)?>(.*?)</head>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Pattern bodyPattern=Pattern.compile("<body(\\s[^>]*)?>(.*?)</body>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Pattern contentPattern=Pattern.compile("<content(\\s+tag[^>]+)>(.*?)</content>", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); public static final String XML_CLOSING_FOR_EMPTY_TAG_ATTRIBUTE_NAME = "gsp_sm_xmlClosingForEmptyTag"; public String addGspSitemeshCapturing(String gspSource) { StringBuffer sb = addHeadCapturing(gspSource); sb = addBodyCapturing(sb); sb = addContentCapturing(sb); return sb.toString(); } StringBuffer addHeadCapturing(String gspSource) { StringBuffer sb=new StringBuffer((int)(gspSource.length() * 1.2)); Matcher m=headPattern.matcher(gspSource); if(m.find()) { m.appendReplacement(sb, ""); sb.append("<sitemesh:captureHead"); if(m.group(1) != null) sb.append(m.group(1)); sb.append(">"); sb.append(addMetaCapturing(addTitleCapturing(m.group(2)))); sb.append("</sitemesh:captureHead>"); m.appendTail(sb); } else if (!bodyPattern.matcher(gspSource).find()){ // no body either, so replace meta & title in the entire gsp source // fix title in sub-template -problem sb.append(addMetaCapturing(addTitleCapturing(gspSource))); + } else { + sb.append(gspSource); } return sb; } String addMetaCapturing(String headContent) { Matcher m=metaPattern.matcher(headContent); final String result = parameterPattern.matcher( m.replaceAll("<sitemesh:captureMeta " + XML_CLOSING_FOR_EMPTY_TAG_ATTRIBUTE_NAME + "=\"$2\"$1/>") ).replaceAll("<sitemesh:parameter$1/>"); return result; } String addTitleCapturing(String headContent) { Matcher m=titlePattern.matcher(headContent); return m.replaceAll("<sitemesh:captureTitle$1>$2</sitemesh:captureTitle>"); } StringBuffer addBodyCapturing(StringBuffer sb) { Matcher m=bodyPattern.matcher(sb); return new StringBuffer(m.replaceAll("<sitemesh:captureBody$1>$2</sitemesh:captureBody>")); } StringBuffer addContentCapturing(StringBuffer sb) { Matcher m=contentPattern.matcher(sb); return new StringBuffer(m.replaceAll("<sitemesh:captureContent$1>$2</sitemesh:captureContent>")); } }
true
true
StringBuffer addHeadCapturing(String gspSource) { StringBuffer sb=new StringBuffer((int)(gspSource.length() * 1.2)); Matcher m=headPattern.matcher(gspSource); if(m.find()) { m.appendReplacement(sb, ""); sb.append("<sitemesh:captureHead"); if(m.group(1) != null) sb.append(m.group(1)); sb.append(">"); sb.append(addMetaCapturing(addTitleCapturing(m.group(2)))); sb.append("</sitemesh:captureHead>"); m.appendTail(sb); } else if (!bodyPattern.matcher(gspSource).find()){ // no body either, so replace meta & title in the entire gsp source // fix title in sub-template -problem sb.append(addMetaCapturing(addTitleCapturing(gspSource))); } return sb; }
StringBuffer addHeadCapturing(String gspSource) { StringBuffer sb=new StringBuffer((int)(gspSource.length() * 1.2)); Matcher m=headPattern.matcher(gspSource); if(m.find()) { m.appendReplacement(sb, ""); sb.append("<sitemesh:captureHead"); if(m.group(1) != null) sb.append(m.group(1)); sb.append(">"); sb.append(addMetaCapturing(addTitleCapturing(m.group(2)))); sb.append("</sitemesh:captureHead>"); m.appendTail(sb); } else if (!bodyPattern.matcher(gspSource).find()){ // no body either, so replace meta & title in the entire gsp source // fix title in sub-template -problem sb.append(addMetaCapturing(addTitleCapturing(gspSource))); } else { sb.append(gspSource); } return sb; }
diff --git a/javamelody-core/src/main/java/net/bull/javamelody/HtmlJavaInformationsReport.java b/javamelody-core/src/main/java/net/bull/javamelody/HtmlJavaInformationsReport.java index 709f80e3..ae6d91c7 100644 --- a/javamelody-core/src/main/java/net/bull/javamelody/HtmlJavaInformationsReport.java +++ b/javamelody-core/src/main/java/net/bull/javamelody/HtmlJavaInformationsReport.java @@ -1,416 +1,418 @@ /* * Copyright 2008-2010 by Emeric Vernat * * This file is part of Java Melody. * * Java Melody 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. * * Java Melody 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 Java Melody. If not, see <http://www.gnu.org/licenses/>. */ package net.bull.javamelody; import java.io.IOException; import java.io.Writer; import java.text.DecimalFormat; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Partie du rapport html pour les informations systèmes sur le serveur. * @author Emeric Vernat */ class HtmlJavaInformationsReport { private static final String[] OS = { "linux", "windows", "mac", "solaris", "hp", "ibm", }; private static final String[] APPLICATION_SERVERS = { "tomcat", "glassfish", "jonas", "jetty", "oracle", "bea", "ibm", }; // constantes pour l'affichage d'une barre avec pourcentage private static final double MIN_VALUE = 0; private static final double MAX_VALUE = 100; private static final int PARTIAL_BLOCKS = 5; private static final int FULL_BLOCKS = 10; private static final double UNIT_SIZE = (MAX_VALUE - MIN_VALUE) / (FULL_BLOCKS * PARTIAL_BLOCKS); private static int uniqueByPageSequence; private final boolean noDatabase = Parameters.isNoDatabase(); private final DecimalFormat integerFormat = I18N.createIntegerFormat(); private final DecimalFormat decimalFormat = I18N.createPercentFormat(); private final List<JavaInformations> javaInformationsList; private final Writer writer; HtmlJavaInformationsReport(List<JavaInformations> javaInformationsList, Writer writer) { super(); assert javaInformationsList != null && !javaInformationsList.isEmpty(); assert writer != null; this.javaInformationsList = javaInformationsList; this.writer = writer; } void toHtml() throws IOException { for (final JavaInformations javaInformations : javaInformationsList) { writeSummary(javaInformations); } // sinon le tableau est décalé if (!noDatabase) { write("<br/><br/>"); } final String br = "<br/>"; if (javaInformationsList.get(0).getSessionCount() >= 0) { write(br); } if (javaInformationsList.get(0).getSystemLoadAverage() >= 0) { // sinon le tableau est décalé vers la droite sous unix write(br); } // pour l'alignement le nb de br doit correspondre au nb de lignes dans le résumé ci-dessus writeln("<br/><br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); writeShowHideLink("detailsJava", "#Details#"); writeln("<br/><br/>"); writeln("<div id='detailsJava' style='display: none;'>"); final boolean repeatHost = javaInformationsList.size() > 1; for (final JavaInformations javaInformations : javaInformationsList) { writeDetails(javaInformations, repeatHost); } writeln("</div>"); } private void writeSummary(JavaInformations javaInformations) throws IOException { final String lineEnd = "</td> </tr>"; final String columnAndLineEnd = "</td><td>" + lineEnd; writeln("<table align='left' border='0' cellspacing='0' cellpadding='2' summary='#Informations_systemes#'>"); writeln("<tr><td>#Host#: </td><td><b>" + javaInformations.getHost() + "</b>" + lineEnd); final MemoryInformations memoryInformations = javaInformations.getMemoryInformations(); final long usedMemory = memoryInformations.getUsedMemory(); final long maxMemory = memoryInformations.getMaxMemory(); write("<tr><td>#memoire_utilisee#: </td><td>"); writeGraph("usedMemory", integerFormat.format(usedMemory / 1024 / 1024)); writeln(" #Mo# / " + integerFormat.format(maxMemory / 1024 / 1024) + " #Mo#&nbsp;&nbsp;&nbsp;</td><td>"); writeln(toBar(memoryInformations.getUsedMemoryPercentage())); writeln(lineEnd); if (javaInformations.getSessionCount() >= 0) { write("<tr><td>#nb_sessions_http#: </td><td>"); writeGraph("httpSessions", integerFormat.format(javaInformations.getSessionCount())); writeln(columnAndLineEnd); } write("<tr><td>#nb_threads_actifs#<br/>(#Requetes_http_en_cours#): </td><td>"); writeGraph("activeThreads", integerFormat.format(javaInformations.getActiveThreadCount())); writeln(columnAndLineEnd); if (!noDatabase) { write("<tr><td>#nb_connexions_actives#: </td><td>"); writeGraph("activeConnections", integerFormat.format(javaInformations.getActiveConnectionCount())); writeln(columnAndLineEnd); final int usedConnectionCount = javaInformations.getUsedConnectionCount(); final int maxConnectionCount = javaInformations.getMaxConnectionCount(); write("<tr><td>#nb_connexions_utilisees#<br/>(#ouvertes#): </td><td>"); writeGraph("usedConnections", integerFormat.format(usedConnectionCount)); if (maxConnectionCount > 0) { writeln(" / " + integerFormat.format(maxConnectionCount) + "&nbsp;&nbsp;&nbsp;</td><td>"); writeln(toBar(javaInformations.getUsedConnectionPercentage())); } writeln(lineEnd); } if (javaInformations.getSystemLoadAverage() >= 0) { write("<tr><td>#Charge_systeme#</td><td>"); writeGraph("systemLoad", decimalFormat.format(javaInformations.getSystemLoadAverage())); writeln(columnAndLineEnd); } writeln("</table>"); } private void writeDetails(JavaInformations javaInformations, boolean repeatHost) throws IOException { final String columnEnd = "</td></tr>"; writeln("<table align='left' border='0' cellspacing='0' cellpadding='2' summary='#Details_systeme#'>"); if (repeatHost) { writeln("<tr><td>#Host#: </td><td><b>" + javaInformations.getHost() + "</b>" + columnEnd); } writeln("<tr><td>#OS#: </td><td>"); final String osIconName = getOSIconName(javaInformations.getOS()); if (osIconName != null) { writeln("<img src='?resource=servers/" + osIconName + "' alt='#OS#'/>"); } writeln(javaInformations.getOS() + " (" + javaInformations.getAvailableProcessors() + " #coeurs#)" + columnEnd); writeln("<tr><td>#Java#: </td><td>" + javaInformations.getJavaVersion() + columnEnd); write("<tr><td>#JVM#: </td><td>" + javaInformations.getJvmVersion()); if (javaInformations.getJvmVersion().contains("Client")) { write("&nbsp;&nbsp;&nbsp;<img src='?resource=alert.png' alt=\"#Client_JVM#\" title=\"#Client_JVM#\"/>"); } writeln(columnEnd); writeln("<tr><td>#PID#: </td><td>" + javaInformations.getPID() + columnEnd); final long unixOpenFileDescriptorCount = javaInformations.getUnixOpenFileDescriptorCount(); if (unixOpenFileDescriptorCount >= 0) { final long unixMaxFileDescriptorCount = javaInformations .getUnixMaxFileDescriptorCount(); write("<tr><td>#nb_fichiers#</td><td>"); writeGraph("fileDescriptors", integerFormat.format(unixOpenFileDescriptorCount)); writeln(" / " + integerFormat.format(unixMaxFileDescriptorCount) + "&nbsp;&nbsp;&nbsp;"); writeln(toBar(javaInformations.getUnixOpenFileDescriptorPercentage())); writeln(columnEnd); } final String serverInfo = javaInformations.getServerInfo(); if (serverInfo != null) { writeln("<tr><td>#Serveur#: </td><td>"); final String applicationServerIconName = getApplicationServerIconName(serverInfo); if (applicationServerIconName != null) { writeln("<img src='?resource=servers/" + applicationServerIconName + "' alt='#Serveur#'/>"); } writeln(serverInfo + columnEnd); writeln("<tr><td>#Contexte_webapp#: </td><td>" + javaInformations.getContextPath() + columnEnd); } writeln("<tr><td>#Demarrage#: </td><td>" + I18N.createDateAndTimeFormat().format(javaInformations.getStartDate()) + columnEnd); - writeln("<tr><td valign='top'>#Arguments_JVM#: </td><td>" - + replaceEolWithBr(javaInformations.getJvmArguments()) + columnEnd); + write("<tr><td valign='top'>#Arguments_JVM#: </td><td>"); + // writer.write pour ne pas gérer de traductions si la donnée contient '#' + writer.write(replaceEolWithBr(javaInformations.getJvmArguments()) + columnEnd); + writeln(""); writeTomcatInformations(javaInformations.getTomcatInformationsList()); writeMemoryInformations(javaInformations.getMemoryInformations()); if (javaInformations.getFreeDiskSpaceInTemp() >= 0) { // on considère que l'espace libre sur le disque dur est celui sur la partition du répertoire temporaire writeln("<tr><td>#Free_disk_space#: </td><td>" + integerFormat.format(javaInformations.getFreeDiskSpaceInTemp() / 1024 / 1024) + " #Mo# " + columnEnd); } writeDatabaseVersionAndDataSourceDetails(javaInformations); if (javaInformations.isDependenciesEnabled()) { writeln("<tr><td valign='top'>#Dependencies#: </td><td>"); writeDependencies(javaInformations); writeln(columnEnd); } writeln("</table>"); } private void writeDatabaseVersionAndDataSourceDetails(JavaInformations javaInformations) throws IOException { final String columnEnd = "</td></tr>"; if (!noDatabase && javaInformations.getDataBaseVersion() != null) { writeln("<tr><td valign='top'>#Base_de_donnees#: </td><td>"); // writer.write pour ne pas gérer de traductions si la donnée contient '#' writer.write(replaceEolWithBr(javaInformations.getDataBaseVersion()).replaceAll("[&]", "&amp;")); writeln(columnEnd); } if (javaInformations.getDataSourceDetails() != null) { writeln("<tr><td valign='top'>#DataSource_jdbc#: </td><td>"); // writer.write pour ne pas gérer de traductions si la donnée contient '#' writer.write(replaceEolWithBr(javaInformations.getDataSourceDetails()) + "<a href='http://commons.apache.org/dbcp/apidocs/org/apache/commons/dbcp/BasicDataSource.html'" + " class='noPrint' target='_blank'>DataSource reference</a>"); writeln(columnEnd); } } static String getOSIconName(String os) { final String tmp = os.toLowerCase(Locale.getDefault()); for (final String anOS : OS) { if (tmp.contains(anOS)) { return anOS + ".png"; } } return null; } static String getApplicationServerIconName(String appServer) { final String tmp = appServer.toLowerCase(Locale.getDefault()); for (final String applicationServer : APPLICATION_SERVERS) { if (tmp.contains(applicationServer)) { return applicationServer + ".png"; } } return null; } private void writeTomcatInformations(List<TomcatInformations> tomcatInformationsList) throws IOException { final List<TomcatInformations> list = new ArrayList<TomcatInformations>(); for (final TomcatInformations tomcatInformations : tomcatInformationsList) { if (tomcatInformations.getRequestCount() > 0) { list.add(tomcatInformations); } } final boolean onlyOne = list.size() == 1; for (final TomcatInformations tomcatInformations : list) { writer.write("<tr><td valign='top'>Tomcat " + tomcatInformations.getName() + ": </td><td>"); // rq: on n'affiche pas pour l'instant getCurrentThreadCount final int currentThreadsBusy = tomcatInformations.getCurrentThreadsBusy(); writeln("#busyThreads# = "); if (onlyOne) { writeGraph("tomcatBusyThreads", integerFormat.format(currentThreadsBusy)); } else { writeln(integerFormat.format(currentThreadsBusy)); } writeln(" / " + integerFormat.format(tomcatInformations.getMaxThreads())); writeln("&nbsp;&nbsp;&nbsp;"); writeln(toBar(100d * currentThreadsBusy / tomcatInformations.getMaxThreads())); writeln("<br/>#bytesReceived# = "); if (onlyOne) { writeGraph("tomcatBytesReceived", integerFormat.format(tomcatInformations.getBytesReceived())); } else { writeln(integerFormat.format(tomcatInformations.getBytesReceived())); } writeln("<br/>#bytesSent# = "); if (onlyOne) { writeGraph("tomcatBytesSent", integerFormat.format(tomcatInformations.getBytesSent())); } else { writeln(integerFormat.format(tomcatInformations.getBytesSent())); } writeln("<br/>#requestCount# = "); writeln(integerFormat.format(tomcatInformations.getRequestCount())); writeln("<br/>#errorCount# = "); writeln(integerFormat.format(tomcatInformations.getErrorCount())); writeln("<br/>#processingTime# = "); writeln(integerFormat.format(tomcatInformations.getProcessingTime())); writeln("<br/>#maxProcessingTime# = "); writeln(integerFormat.format(tomcatInformations.getMaxTime())); writeln("</td> </tr>"); } } private void writeMemoryInformations(MemoryInformations memoryInformations) throws IOException { final String columnEnd = "</td></tr>"; writeln("<tr><td valign='top'>#Gestion_memoire#: </td><td>" + replaceEolWithBr(memoryInformations.getMemoryDetails()).replace(" Mo", " #Mo#") + columnEnd); final long usedPermGen = memoryInformations.getUsedPermGen(); if (usedPermGen > 0) { // perm gen est à 0 sous jrockit final long maxPermGen = memoryInformations.getMaxPermGen(); writeln("<tr><td>#Memoire_Perm_Gen#: </td><td>" + integerFormat.format(usedPermGen / 1024 / 1024) + " #Mo#"); if (maxPermGen > 0) { writeln(" / " + integerFormat.format(maxPermGen / 1024 / 1024) + " #Mo#&nbsp;&nbsp;&nbsp;"); writeln(toBar(memoryInformations.getUsedPermGenPercentage())); } writeln(columnEnd); } } private void writeDependencies(JavaInformations javaInformations) throws IOException { final int nbDependencies = javaInformations.getDependenciesList().size(); writeln(I18N.getFormattedString("nb_dependencies", nbDependencies)); if (nbDependencies > 0) { uniqueByPageSequence++; writeln(" ; &nbsp;&nbsp;&nbsp;"); writeShowHideLink("detailsDependencies" + uniqueByPageSequence, "#Details#"); if (javaInformations.doesPomXmlExists() && Parameters.isSystemActionsEnabled()) { writeln("&nbsp;&nbsp;&nbsp;<a href='?part=pom.xml' class='noPrint'>"); writeln("<img src='?resource=xml.png' width='14' height='14' alt=\"#pom.xml#\"/> #pom.xml#</a>"); } writeln("<br/>"); writeln("<div id='detailsDependencies" + uniqueByPageSequence + "' style='display: none;'>"); writeln(replaceEolWithBr(javaInformations.getDependencies())); writeln("</div>"); } } private void writeGraph(String graph, String value) throws IOException { if (javaInformationsList.size() > 1) { write(value); return; } // la classe tooltip est configurée dans la css de HtmlReport write("<a class='tooltip' href='?part=graph&amp;graph="); write(graph); write("'"); // ce onmouseover sert à charger les graphs par requête un par un et à la demande // sans les charger tous au chargement de la page. // le onmouseover se désactive après chargement pour ne pas recharger une image déjà chargée write(" onmouseover=\"document.getElementById('"); final String id = "id" + graph; write(id); write("').src='?graph="); write(graph); write("&amp;width=100&amp;height=50'; this.onmouseover=null;\" >"); // avant mouseover on prend une image qui sera mise en cache write("<em><img src='?resource=systeminfo.png' id='"); write(id); write("' alt='graph'/></em>"); // writer.write pour ne pas gérer de traductions si le nom contient '#' writer.write(value); write("</a>"); } // méthode inspirée de VisualScoreTag dans LambdaProbe/JStripe (Licence GPL) static String toBar(double percentValue) { // NOPMD final double myPercent = Math.max(Math.min(percentValue, 100d), 0d); final StringBuilder sb = new StringBuilder(); final String body = "<img src=''?resource=bar/rb_{0}.gif'' alt=''+'' title=''" + I18N.createPercentFormat().format(myPercent) + "%'' />"; final int fullBlockCount = (int) Math.floor(myPercent / (UNIT_SIZE * PARTIAL_BLOCKS)); final int partialBlockIndex = (int) Math.floor((myPercent - fullBlockCount * UNIT_SIZE * PARTIAL_BLOCKS) / UNIT_SIZE); sb.append(MessageFormat.format(body, fullBlockCount > 0 || partialBlockIndex > 0 ? "a" : "a0")); final String fullBody = MessageFormat.format(body, PARTIAL_BLOCKS); for (int i = 0; i < fullBlockCount; i++) { sb.append(fullBody); } if (partialBlockIndex > 0) { final String partialBody = MessageFormat.format(body, partialBlockIndex); sb.append(partialBody); } final int emptyBlocks = FULL_BLOCKS - fullBlockCount - (partialBlockIndex > 0 ? 1 : 0); if (emptyBlocks > 0) { final String emptyBody = MessageFormat.format(body, 0); for (int i = 0; i < emptyBlocks; i++) { sb.append(emptyBody); } } sb.append(MessageFormat.format(body, fullBlockCount == FULL_BLOCKS ? "b" : "b0")); return sb.toString(); } private static String replaceEolWithBr(String string) { return string.replaceAll("[\n]", "<br/>"); } private void writeShowHideLink(String idToShow, String label) throws IOException { writeln("<a href=\"javascript:showHide('" + idToShow + "');\" class='noPrint'><img id='" + idToShow + "Img' src='?resource=bullets/plus.png' alt=''/> " + label + "</a>"); } private void write(String html) throws IOException { I18N.writeTo(html, writer); } private void writeln(String html) throws IOException { I18N.writelnTo(html, writer); } }
true
true
private void writeDetails(JavaInformations javaInformations, boolean repeatHost) throws IOException { final String columnEnd = "</td></tr>"; writeln("<table align='left' border='0' cellspacing='0' cellpadding='2' summary='#Details_systeme#'>"); if (repeatHost) { writeln("<tr><td>#Host#: </td><td><b>" + javaInformations.getHost() + "</b>" + columnEnd); } writeln("<tr><td>#OS#: </td><td>"); final String osIconName = getOSIconName(javaInformations.getOS()); if (osIconName != null) { writeln("<img src='?resource=servers/" + osIconName + "' alt='#OS#'/>"); } writeln(javaInformations.getOS() + " (" + javaInformations.getAvailableProcessors() + " #coeurs#)" + columnEnd); writeln("<tr><td>#Java#: </td><td>" + javaInformations.getJavaVersion() + columnEnd); write("<tr><td>#JVM#: </td><td>" + javaInformations.getJvmVersion()); if (javaInformations.getJvmVersion().contains("Client")) { write("&nbsp;&nbsp;&nbsp;<img src='?resource=alert.png' alt=\"#Client_JVM#\" title=\"#Client_JVM#\"/>"); } writeln(columnEnd); writeln("<tr><td>#PID#: </td><td>" + javaInformations.getPID() + columnEnd); final long unixOpenFileDescriptorCount = javaInformations.getUnixOpenFileDescriptorCount(); if (unixOpenFileDescriptorCount >= 0) { final long unixMaxFileDescriptorCount = javaInformations .getUnixMaxFileDescriptorCount(); write("<tr><td>#nb_fichiers#</td><td>"); writeGraph("fileDescriptors", integerFormat.format(unixOpenFileDescriptorCount)); writeln(" / " + integerFormat.format(unixMaxFileDescriptorCount) + "&nbsp;&nbsp;&nbsp;"); writeln(toBar(javaInformations.getUnixOpenFileDescriptorPercentage())); writeln(columnEnd); } final String serverInfo = javaInformations.getServerInfo(); if (serverInfo != null) { writeln("<tr><td>#Serveur#: </td><td>"); final String applicationServerIconName = getApplicationServerIconName(serverInfo); if (applicationServerIconName != null) { writeln("<img src='?resource=servers/" + applicationServerIconName + "' alt='#Serveur#'/>"); } writeln(serverInfo + columnEnd); writeln("<tr><td>#Contexte_webapp#: </td><td>" + javaInformations.getContextPath() + columnEnd); } writeln("<tr><td>#Demarrage#: </td><td>" + I18N.createDateAndTimeFormat().format(javaInformations.getStartDate()) + columnEnd); writeln("<tr><td valign='top'>#Arguments_JVM#: </td><td>" + replaceEolWithBr(javaInformations.getJvmArguments()) + columnEnd); writeTomcatInformations(javaInformations.getTomcatInformationsList()); writeMemoryInformations(javaInformations.getMemoryInformations()); if (javaInformations.getFreeDiskSpaceInTemp() >= 0) { // on considère que l'espace libre sur le disque dur est celui sur la partition du répertoire temporaire writeln("<tr><td>#Free_disk_space#: </td><td>" + integerFormat.format(javaInformations.getFreeDiskSpaceInTemp() / 1024 / 1024) + " #Mo# " + columnEnd); } writeDatabaseVersionAndDataSourceDetails(javaInformations); if (javaInformations.isDependenciesEnabled()) { writeln("<tr><td valign='top'>#Dependencies#: </td><td>"); writeDependencies(javaInformations); writeln(columnEnd); } writeln("</table>"); }
private void writeDetails(JavaInformations javaInformations, boolean repeatHost) throws IOException { final String columnEnd = "</td></tr>"; writeln("<table align='left' border='0' cellspacing='0' cellpadding='2' summary='#Details_systeme#'>"); if (repeatHost) { writeln("<tr><td>#Host#: </td><td><b>" + javaInformations.getHost() + "</b>" + columnEnd); } writeln("<tr><td>#OS#: </td><td>"); final String osIconName = getOSIconName(javaInformations.getOS()); if (osIconName != null) { writeln("<img src='?resource=servers/" + osIconName + "' alt='#OS#'/>"); } writeln(javaInformations.getOS() + " (" + javaInformations.getAvailableProcessors() + " #coeurs#)" + columnEnd); writeln("<tr><td>#Java#: </td><td>" + javaInformations.getJavaVersion() + columnEnd); write("<tr><td>#JVM#: </td><td>" + javaInformations.getJvmVersion()); if (javaInformations.getJvmVersion().contains("Client")) { write("&nbsp;&nbsp;&nbsp;<img src='?resource=alert.png' alt=\"#Client_JVM#\" title=\"#Client_JVM#\"/>"); } writeln(columnEnd); writeln("<tr><td>#PID#: </td><td>" + javaInformations.getPID() + columnEnd); final long unixOpenFileDescriptorCount = javaInformations.getUnixOpenFileDescriptorCount(); if (unixOpenFileDescriptorCount >= 0) { final long unixMaxFileDescriptorCount = javaInformations .getUnixMaxFileDescriptorCount(); write("<tr><td>#nb_fichiers#</td><td>"); writeGraph("fileDescriptors", integerFormat.format(unixOpenFileDescriptorCount)); writeln(" / " + integerFormat.format(unixMaxFileDescriptorCount) + "&nbsp;&nbsp;&nbsp;"); writeln(toBar(javaInformations.getUnixOpenFileDescriptorPercentage())); writeln(columnEnd); } final String serverInfo = javaInformations.getServerInfo(); if (serverInfo != null) { writeln("<tr><td>#Serveur#: </td><td>"); final String applicationServerIconName = getApplicationServerIconName(serverInfo); if (applicationServerIconName != null) { writeln("<img src='?resource=servers/" + applicationServerIconName + "' alt='#Serveur#'/>"); } writeln(serverInfo + columnEnd); writeln("<tr><td>#Contexte_webapp#: </td><td>" + javaInformations.getContextPath() + columnEnd); } writeln("<tr><td>#Demarrage#: </td><td>" + I18N.createDateAndTimeFormat().format(javaInformations.getStartDate()) + columnEnd); write("<tr><td valign='top'>#Arguments_JVM#: </td><td>"); // writer.write pour ne pas gérer de traductions si la donnée contient '#' writer.write(replaceEolWithBr(javaInformations.getJvmArguments()) + columnEnd); writeln(""); writeTomcatInformations(javaInformations.getTomcatInformationsList()); writeMemoryInformations(javaInformations.getMemoryInformations()); if (javaInformations.getFreeDiskSpaceInTemp() >= 0) { // on considère que l'espace libre sur le disque dur est celui sur la partition du répertoire temporaire writeln("<tr><td>#Free_disk_space#: </td><td>" + integerFormat.format(javaInformations.getFreeDiskSpaceInTemp() / 1024 / 1024) + " #Mo# " + columnEnd); } writeDatabaseVersionAndDataSourceDetails(javaInformations); if (javaInformations.isDependenciesEnabled()) { writeln("<tr><td valign='top'>#Dependencies#: </td><td>"); writeDependencies(javaInformations); writeln(columnEnd); } writeln("</table>"); }
diff --git a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/JRERuntimeClasspathEntryResolver.java b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/JRERuntimeClasspathEntryResolver.java index d1b57b273..f6b1b1a7e 100644 --- a/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/JRERuntimeClasspathEntryResolver.java +++ b/org.eclipse.jdt.launching/launching/org/eclipse/jdt/internal/launching/JRERuntimeClasspathEntryResolver.java @@ -1,135 +1,148 @@ /******************************************************************************* * Copyright (c) 2000, 2003 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.launching; import java.io.File; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.Path; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.launching.IRuntimeClasspathEntry; import org.eclipse.jdt.launching.IRuntimeClasspathEntryResolver; import org.eclipse.jdt.launching.IVMInstall; import org.eclipse.jdt.launching.JavaRuntime; import org.eclipse.jdt.launching.LibraryLocation; /** * Resolves for JRELIB_VARIABLE and JRE_CONTAINER */ public class JRERuntimeClasspathEntryResolver implements IRuntimeClasspathEntryResolver { /** * @see IRuntimeClasspathEntryResolver#resolveRuntimeClasspathEntry(IRuntimeClasspathEntry, ILaunchConfiguration) */ public IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry, ILaunchConfiguration configuration) throws CoreException { IVMInstall jre = null; if (entry.getType() == IRuntimeClasspathEntry.CONTAINER && entry.getPath().segmentCount() > 1) { // a specific VM jre = JREContainerInitializer.resolveVM(entry.getPath()); } else { // default VM for config jre = JavaRuntime.computeVMInstall(configuration); } if (jre == null) { // cannot resolve JRE return new IRuntimeClasspathEntry[0]; } return resolveLibraryLocations(jre, entry.getClasspathProperty()); } /** * @see IRuntimeClasspathEntryResolver#resolveRuntimeClasspathEntry(IRuntimeClasspathEntry, IJavaProject) */ public IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry entry, IJavaProject project) throws CoreException { IVMInstall jre = null; if (entry.getType() == IRuntimeClasspathEntry.CONTAINER && entry.getPath().segmentCount() > 1) { // a specific VM jre = JREContainerInitializer.resolveVM(entry.getPath()); } else { // default VM for project jre = JavaRuntime.getVMInstall(project); } if (jre == null) { // cannot resolve JRE return new IRuntimeClasspathEntry[0]; } return resolveLibraryLocations(jre, entry.getClasspathProperty()); } /** * Resolves libray locations for the given VM install */ protected IRuntimeClasspathEntry[] resolveLibraryLocations(IVMInstall vm, int kind) { IRuntimeClasspathEntry[] resolved = null; if (kind == IRuntimeClasspathEntry.BOOTSTRAP_CLASSES) { File vmInstallLocation= vm.getInstallLocation(); if (vmInstallLocation != null) { LibraryInfo libraryInfo= LaunchingPlugin.getLibraryInfo(vmInstallLocation.getAbsolutePath()); if (libraryInfo != null) { // only return bootstrap classpath entries if we have the info String[] bootpath= libraryInfo.getBootpath(); int length= bootpath.length; + // use libs to set source attachment properly + LibraryLocation[] libs = JavaRuntime.getLibraryLocations(vm); resolved= new IRuntimeClasspathEntry[length]; for (int i= 0; i < length; i++) { resolved[i]= JavaRuntime.newArchiveRuntimeClasspathEntry(new Path(bootpath[i])); resolved[i].setClasspathProperty(IRuntimeClasspathEntry.BOOTSTRAP_CLASSES); + for (int j = 0; j < libs.length; j++) { + String resolvedPath = resolved[i].getPath().toString(); + if (libs[j].getSystemLibraryPath().toString().equalsIgnoreCase(resolvedPath)) { + IPath path = libs[j].getSystemLibrarySourcePath(); + if (path != null && !path.isEmpty()) { + resolved[i].setSourceAttachmentPath(path); + resolved[i].setSourceAttachmentRootPath(libs[j].getPackageRootPath()); + } + break; + } + } } return resolved; } } } LibraryLocation[] libs = vm.getLibraryLocations(); if (libs == null) { // default system libs libs = vm.getVMInstallType().getDefaultLibraryLocations(vm.getInstallLocation()); } else { // custom system libs - place on bootpath explicitly kind = IRuntimeClasspathEntry.BOOTSTRAP_CLASSES; } resolved = new IRuntimeClasspathEntry[libs.length]; for (int i = 0; i < libs.length; i++) { resolved[i] = JavaRuntime.newArchiveRuntimeClasspathEntry(libs[i].getSystemLibraryPath()); IPath path = libs[i].getSystemLibrarySourcePath(); if (path != null && !path.isEmpty()) { resolved[i].setSourceAttachmentPath(path); resolved[i].setSourceAttachmentRootPath(libs[i].getPackageRootPath()); } resolved[i].setClasspathProperty(kind); } return resolved; } /** * @see IRuntimeClasspathEntryResolver#resolveVMInstall(IClasspathEntry) */ public IVMInstall resolveVMInstall(IClasspathEntry entry) { switch (entry.getEntryKind()) { case IClasspathEntry.CPE_VARIABLE: if (entry.getPath().segment(0).equals(JavaRuntime.JRELIB_VARIABLE)) { return JavaRuntime.getDefaultVMInstall(); } break; case IClasspathEntry.CPE_CONTAINER: if (entry.getPath().segment(0).equals(JavaRuntime.JRE_CONTAINER)) { return JREContainerInitializer.resolveVM(entry.getPath()); } break; default: break; } return null; } }
false
true
protected IRuntimeClasspathEntry[] resolveLibraryLocations(IVMInstall vm, int kind) { IRuntimeClasspathEntry[] resolved = null; if (kind == IRuntimeClasspathEntry.BOOTSTRAP_CLASSES) { File vmInstallLocation= vm.getInstallLocation(); if (vmInstallLocation != null) { LibraryInfo libraryInfo= LaunchingPlugin.getLibraryInfo(vmInstallLocation.getAbsolutePath()); if (libraryInfo != null) { // only return bootstrap classpath entries if we have the info String[] bootpath= libraryInfo.getBootpath(); int length= bootpath.length; resolved= new IRuntimeClasspathEntry[length]; for (int i= 0; i < length; i++) { resolved[i]= JavaRuntime.newArchiveRuntimeClasspathEntry(new Path(bootpath[i])); resolved[i].setClasspathProperty(IRuntimeClasspathEntry.BOOTSTRAP_CLASSES); } return resolved; } } } LibraryLocation[] libs = vm.getLibraryLocations(); if (libs == null) { // default system libs libs = vm.getVMInstallType().getDefaultLibraryLocations(vm.getInstallLocation()); } else { // custom system libs - place on bootpath explicitly kind = IRuntimeClasspathEntry.BOOTSTRAP_CLASSES; } resolved = new IRuntimeClasspathEntry[libs.length]; for (int i = 0; i < libs.length; i++) { resolved[i] = JavaRuntime.newArchiveRuntimeClasspathEntry(libs[i].getSystemLibraryPath()); IPath path = libs[i].getSystemLibrarySourcePath(); if (path != null && !path.isEmpty()) { resolved[i].setSourceAttachmentPath(path); resolved[i].setSourceAttachmentRootPath(libs[i].getPackageRootPath()); } resolved[i].setClasspathProperty(kind); } return resolved; }
protected IRuntimeClasspathEntry[] resolveLibraryLocations(IVMInstall vm, int kind) { IRuntimeClasspathEntry[] resolved = null; if (kind == IRuntimeClasspathEntry.BOOTSTRAP_CLASSES) { File vmInstallLocation= vm.getInstallLocation(); if (vmInstallLocation != null) { LibraryInfo libraryInfo= LaunchingPlugin.getLibraryInfo(vmInstallLocation.getAbsolutePath()); if (libraryInfo != null) { // only return bootstrap classpath entries if we have the info String[] bootpath= libraryInfo.getBootpath(); int length= bootpath.length; // use libs to set source attachment properly LibraryLocation[] libs = JavaRuntime.getLibraryLocations(vm); resolved= new IRuntimeClasspathEntry[length]; for (int i= 0; i < length; i++) { resolved[i]= JavaRuntime.newArchiveRuntimeClasspathEntry(new Path(bootpath[i])); resolved[i].setClasspathProperty(IRuntimeClasspathEntry.BOOTSTRAP_CLASSES); for (int j = 0; j < libs.length; j++) { String resolvedPath = resolved[i].getPath().toString(); if (libs[j].getSystemLibraryPath().toString().equalsIgnoreCase(resolvedPath)) { IPath path = libs[j].getSystemLibrarySourcePath(); if (path != null && !path.isEmpty()) { resolved[i].setSourceAttachmentPath(path); resolved[i].setSourceAttachmentRootPath(libs[j].getPackageRootPath()); } break; } } } return resolved; } } } LibraryLocation[] libs = vm.getLibraryLocations(); if (libs == null) { // default system libs libs = vm.getVMInstallType().getDefaultLibraryLocations(vm.getInstallLocation()); } else { // custom system libs - place on bootpath explicitly kind = IRuntimeClasspathEntry.BOOTSTRAP_CLASSES; } resolved = new IRuntimeClasspathEntry[libs.length]; for (int i = 0; i < libs.length; i++) { resolved[i] = JavaRuntime.newArchiveRuntimeClasspathEntry(libs[i].getSystemLibraryPath()); IPath path = libs[i].getSystemLibrarySourcePath(); if (path != null && !path.isEmpty()) { resolved[i].setSourceAttachmentPath(path); resolved[i].setSourceAttachmentRootPath(libs[i].getPackageRootPath()); } resolved[i].setClasspathProperty(kind); } return resolved; }
diff --git a/src/com/google/caja/demos/playground/client/ui/PlaygroundView.java b/src/com/google/caja/demos/playground/client/ui/PlaygroundView.java index fd259233..9e002dc8 100644 --- a/src/com/google/caja/demos/playground/client/ui/PlaygroundView.java +++ b/src/com/google/caja/demos/playground/client/ui/PlaygroundView.java @@ -1,527 +1,527 @@ // Copyright (C) 2009 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.caja.demos.playground.client.ui; import com.google.caja.demos.playground.client.Playground; import com.google.caja.demos.playground.client.PlaygroundResource; import com.google.caja.gwtbeans.shared.Caja; import com.google.caja.gwtbeans.shared.Frame; import com.google.caja.util.Maps; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.logical.shared.SelectionEvent; import com.google.gwt.event.logical.shared.SelectionHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.DockLayoutPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.MultiWordSuggestOracle; import com.google.gwt.user.client.ui.RootLayoutPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.TreeItem; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; /** * GUI elements of the playground client * * @author Jasvir Nagra ([email protected]) */ public class PlaygroundView { private final Playground controller; private final MultiWordSuggestOracle sourceExamples; private MultiWordSuggestOracle policyExamples; private final PlaygroundUI playgroundUI; private int idSeq = 0; private String genId() { return "CajaGadget" + (idSeq++) + "___"; } public void setVersion(String v) { playgroundUI.version.setText(v); } public void setPolicyUrl(String url) { playgroundUI.policyAddressField.setText(url); policyExamples.add(url); } public void setUrl(String url) { playgroundUI.addressField.setText(url); sourceExamples.add(url); } public void selectTab(Tabs tab) { playgroundUI.editorPanel.selectTab(tab.ordinal()); } private void initSourcePanel() { for (Example eg : Example.values()) { sourceExamples.add(eg.url); } playgroundUI.addressField.getTextBox().addFocusHandler(new FocusHandler() { public void onFocus(FocusEvent event) { playgroundUI.addressField.showSuggestionList(); } }); playgroundUI.addressField.setText("http://"); playgroundUI.goButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { controller.loadSource(playgroundUI.addressField.getText()); } }); playgroundUI.cajoleButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { playgroundUI.runtimeMessages.clear(); playgroundUI.compileMessages.clear(); playgroundUI.cajoledSource.setText(""); playgroundUI.renderPanel.setText(""); controller.cajole( playgroundUI.addressField.getText(), playgroundUI.sourceText.getText(), playgroundUI.policyText.getText(), true /* debug */, genId() ); } }); } private void initFeedbackPanel() { playgroundUI.feedbackPanel.setHorizontalAlignment( HasHorizontalAlignment.ALIGN_RIGHT); for (Menu menu : Menu.values()) { Anchor menuItem = new Anchor(); menuItem.setHTML(menu.description); menuItem.setHref(menu.url); menuItem.setWordWrap(false); menuItem.addStyleName("menuItems"); playgroundUI.feedbackPanel.add(menuItem); playgroundUI.feedbackPanel.setCellWidth(menuItem, "100%"); } } private void initPolicyPanel() { policyExamples = new MultiWordSuggestOracle(); playgroundUI.policyAddressField = new SuggestBox(policyExamples); playgroundUI.policyAddressField.getTextBox().addFocusHandler(new FocusHandler() { public void onFocus(FocusEvent event) { playgroundUI.policyAddressField.showSuggestionList(); } }); playgroundUI.policyAddressField.setText("http://"); playgroundUI.clearButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { controller.clearPolicy(); } }); playgroundUI.loadButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { controller.loadPolicy(playgroundUI.policyAddressField.getText()); } }); playgroundUI.defaultButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { setPolicySource(defaultPolicy()); } }); setPolicySource(defaultPolicy()); } private String defaultPolicy() { return PlaygroundResource.INSTANCE.defaultPolicy().getText(); } native static String encodeURIComponent(String uri) /*-{ return $wnd.encodeURIComponent(uri); }-*/; /** * Extracts the location map and original source from content cajoled in * debug mode. * The format is described at <a href= * "http://google-caja.googlecode.com/svn/trunk/doc/html/compiledModuleFormat/index.html" * ><tt>doc/html/compiledModuleFormat/index.html</tt></a>. */ private static native boolean srcLocMapAndOriginalSrc( String source, String[] out) /*-{ var str = "'(?:[^'\\\\]|\\\\.)*'"; var colon = "\\s*:\\s*"; var comma = "\\s*,\\s*"; var block = str + colon + "\\{(?:\\s*" + str + colon + str + comma + ")*?" + "\\s*'content'" + colon + "\\[\\s*" + str + "(?:" + comma + str + ")*\\s*\\]\\s*\\}"; // TODO(mikesamuel): extract this a better way once we're providing module // output in an easy to consume JSON format. var re = new RegExp( // sourceLocationMap in group 1 "'sourceLocationMap'" + colon + "\\{" + "(?:\\s*" + str + colon + str + comma + ")*?" // any number of pairs + "\\s*'content'" + colon + "\\[\\s*(" + str + "(?:" + comma + str + ")*)\\s*\\]\\s*\\}" + comma // originalSource in group 2 + "'originalSource'" + colon + "\\{\\s*(" + block + "(?:" + comma + block + ")*)\\s*\\}\\s*\\}\\s*\\)\\s*;?\\s*\\}\\s*<\\/script>\s*$"); var match = source.match(re); if (match) { out[0] = match[0]; out[1] = match[1]; return true; } else { return false; } }-*/; /* private Widget createSpeedtracerPanel() { FlowPanel hp = new FlowPanel(); hp.setSize("100%", "100%"); speedtracerManifestButton = new Button("Manifest URI", new ClickHandler() { PopupPanel panel; Label uriLbl; private String getManifestUri() { String[] locMapAndSrc = new String[2]; if (srcLocMapAndOriginalSrc(cajoledSource.getText(), locMapAndSrc)) { String json = "[[" + locMapAndSrc[0] + "],[" + locMapAndSrc[1] + "]]"; return "data:text/plain," + encodeURIComponent(json); } else { return null; } } public void onClick(ClickEvent event) { String dataUri = getManifestUri(); if (panel == null) { HorizontalPanel body = new HorizontalPanel(); body.add(uriLbl = new Label()); body.add(new Button("\u00d7", new ClickHandler() { public void onClick(ClickEvent ev) { panel.hide(); } })); panel = new PopupPanel(); panel.setWidget(body); panel.setTitle("Manifest URI"); } uriLbl.setText(dataUri); if (panel.isShowing()) { panel.hide(); } else { panel.show(); } } }); hp.add(speedtracerManifestButton); return hp; } */ private native void setupNativeSelectLineBridge() /*-{ var that = this; $wnd.selectLine = function (uri, start, sOffset, end, eOffset) { [email protected]::selectTab(Lcom/google/caja/demos/playground/client/ui/PlaygroundView$Tabs;)( @com.google.caja.demos.playground.client.ui.PlaygroundView.Tabs::SOURCE); [email protected]::highlightSource(Ljava/lang/String;IIII)(uri, start, sOffset, end, eOffset); } }-*/; private void initEditor() { setupNativeSelectLineBridge(); selectTab(Tabs.SOURCE); } private native void initPlusOne() /*-{ try { $wnd.gapi.plusone.render("plusone",{size: "medium"}); } catch (e) { // failure to initialize +1 button should not prevent load of page } }-*/; private static TreeItem addExampleItem(Map<Example.Type, TreeItem> menu, Example eg) { if (!menu.containsKey(eg.type)) { TreeItem menuItem = new TreeItem(eg.type.description); menu.put(eg.type, menuItem); } TreeItem egItem = new TreeItem(eg.description); menu.get(eg.type).addItem(egItem); return egItem; } private void initExamples() { Map<Example.Type, TreeItem> menuMap = new EnumMap<Example.Type, TreeItem>( Example.Type.class); final Map<TreeItem, Example> entryMap = new HashMap<TreeItem, Example>(); playgroundUI.exampleTree.setTitle("Select an example"); for (Example eg : Example.values()) { TreeItem it = addExampleItem(menuMap, eg); entryMap.put(it, eg); } boolean first = true; for (TreeItem menuItem : menuMap.values()) { if (first) { first = false; menuItem.setState(true); } playgroundUI.exampleTree.addItem(menuItem); } playgroundUI.exampleTree.addSelectionHandler(new SelectionHandler<TreeItem>() { public void onSelection(SelectionEvent<TreeItem> event) { Example eg = entryMap.get(event.getSelectedItem()); // No associated example - e.g. when opening a subtree menu if (null == eg) { return; } controller.loadSource(eg.url); } }); } private void initCaja() { Caja.initialize(".", true); } public PlaygroundView(Playground controller) { this.controller = controller; this.sourceExamples = new MultiWordSuggestOracle(); this.policyExamples = new MultiWordSuggestOracle(); this.playgroundUI = new com.google.caja.demos.playground.client.ui.PlaygroundUI( sourceExamples, policyExamples); RootLayoutPanel.get().add(playgroundUI); initSourcePanel(); initPolicyPanel(); initFeedbackPanel(); initExamples(); initEditor(); initCaja(); initPlusOne(); } public void setOriginalSource(String result) { if (result == null) { playgroundUI.sourceText.setText(""); } else { playgroundUI.sourceText.setText(result); } } public void setPolicySource(String result) { if (result == null) { playgroundUI.policyText.setText(""); } else { playgroundUI.policyText.setText(result); } } public void setCajoledSource(String html, String js) { if (html == null && js == null) { playgroundUI.cajoledSource.setText("There were cajoling errors"); return; } playgroundUI.cajoledSource.setHTML(prettyPrint(html, "html") + "&lt;script&gt;" + prettyPrint(js, "lang-js") + "&lt;/script&gt;"); } public void setLoading(boolean isLoading) { playgroundUI.loadingLabel.setVisible(isLoading); } private native String prettyPrint(String result, String lang) /*-{ return $wnd.prettyPrintOne($wnd.indentAndWrapCode(result), lang); }-*/; public void setRenderedResult( final String policy, final String html, final String js, final String idClass) { if (html == null && js == null) { playgroundUI.renderResult.setText("There were cajoling errors"); return; } // Make the cajoled content visible so that the DOM will be laid out before // the script checks DOM geometry. selectTab(Tabs.RENDER); Map<String, String> domOpts = new HashMap<String, String>(); domOpts.put("idClass", idClass); domOpts.put("title", "Playground Untrusted Content"); Caja.load( playgroundUI.renderPanel.getElement(), makeUriPolicy(), new AsyncCallback<Frame>() { @Override public void onFailure(Throwable t) { PlaygroundView.this.addCompileMessage(t.toString()); } @Override public void onSuccess(Frame frame) { JavaScriptObject tmp = makeExtraImports(Caja.getNative(), policy); augmentWith(tmp, "widgets", ((WidgetsTaming)GWT.create(WidgetsTaming.class)) .getJso(frame, new Widgets(playgroundUI.gwtShim))); augmentWith(tmp, "blivit", ((BlivitTaming)GWT.create(BlivitTaming.class)) .getJso(frame, new Blivit("hello world"))); frame .api(tmp) .cajoled("http://fake.url/", js, html) .run(new AsyncCallback<JavaScriptObject>() { @Override public void onFailure(Throwable t) { PlaygroundView.this.addCompileMessage(t.toString()); } @Override public void onSuccess(JavaScriptObject r) { - PlaygroundView.this.setRenderedResult(r.toString()); + PlaygroundView.this.setRenderedResult(r + ""); } }); } }, domOpts); } private void setRenderedResult(String result) { playgroundUI.renderResult.setText(result); } private void alert(String msg) { final DialogBox alertBox = new DialogBox(); alertBox.setGlassEnabled(true); alertBox.setText("Cajoled gadget says"); DockLayoutPanel dock = new DockLayoutPanel(Unit.PX); dock.add(new ScrollPanel(new Label(msg))); dock.addSouth(new Button("Ok", new ClickHandler() { @Override public void onClick(ClickEvent arg0) { alertBox.hide(); } }), 20); dock.setSize("200px", "200px"); alertBox.add(dock); alertBox.center(); alertBox.show(); } private native void augmentWith(JavaScriptObject o, String key, JavaScriptObject value) /*-{ o[key] = value; }-*/; private native JavaScriptObject makeExtraImports( JavaScriptObject caja, String policy) /*-{ var that = this; var extraImports = {}; try { var tamings___ = eval(policy); } catch (e) { [email protected]::addRuntimeMessage(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;) (e, "evaluating policy"); } for (var i=0; i < tamings___.length; i++) { try { tamings___[i].call(undefined, caja, extraImports); } catch (e) { [email protected]::addRuntimeMessage(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;) (e, "evaluating " + i + "th policy function"); } } extraImports.onerror = caja.tame(caja.markFunction( function (message, source, lineNum) { [email protected]::addRuntimeMessage(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;) (message, source, lineNum); })); extraImports.alert = caja.tame(caja.markFunction( function (message) { [email protected]::alert(Ljava/lang/String;) ('' + message); })); return extraImports; }-*/; private native JavaScriptObject makeUriPolicy() /*-{ return { rewrite: function (uri, uriEffect, loaderType, hints) { if (!/^https?:/i.test(uri)) { return void 0; } if (uriEffect === $wnd.html4.ueffects.NEW_DOCUMENT) { return uri; } if (uriEffect === $wnd.html4.ueffects.SAME_DOCUMENT && loaderType === $wnd.html4.ltypes.SANDBOXED) { return "http://www.gmodules.com/gadgets/proxy" + "?url=" + encodeURIComponent(uri) + "&container=caja"; } return null; } }; }-*/; public void addCompileMessage(String item) { // Rendered using HTMLSnippetProducer serverside HTML i = new HTML(item); playgroundUI.compileMessages.add(i); } public void addRuntimeMessage(String message, String source, String lineNum) { // Unsafe as HTML Label i = new Label( "Uncaught script error: '" + message + "' in source: '" + source + "' at line: " + lineNum + "\n"); playgroundUI.runtimeMessages.add(i); } /** @param uri unused but provided for consistency with native GWT caller. */ public void highlightSource(String uri, int start, int sOffset, int end, int eOffset) { playgroundUI.sourceText.setCursorPos(start); playgroundUI.sourceText.setSelectionRange(start, sOffset, end, eOffset); } public enum Tabs { SOURCE, POLICY, CAJOLED_SOURCE, RENDER, COMPILE_WARNINGS, RUNTIME_WARNINGS, TAMING, MANIFEST; } }
true
true
public void setRenderedResult( final String policy, final String html, final String js, final String idClass) { if (html == null && js == null) { playgroundUI.renderResult.setText("There were cajoling errors"); return; } // Make the cajoled content visible so that the DOM will be laid out before // the script checks DOM geometry. selectTab(Tabs.RENDER); Map<String, String> domOpts = new HashMap<String, String>(); domOpts.put("idClass", idClass); domOpts.put("title", "Playground Untrusted Content"); Caja.load( playgroundUI.renderPanel.getElement(), makeUriPolicy(), new AsyncCallback<Frame>() { @Override public void onFailure(Throwable t) { PlaygroundView.this.addCompileMessage(t.toString()); } @Override public void onSuccess(Frame frame) { JavaScriptObject tmp = makeExtraImports(Caja.getNative(), policy); augmentWith(tmp, "widgets", ((WidgetsTaming)GWT.create(WidgetsTaming.class)) .getJso(frame, new Widgets(playgroundUI.gwtShim))); augmentWith(tmp, "blivit", ((BlivitTaming)GWT.create(BlivitTaming.class)) .getJso(frame, new Blivit("hello world"))); frame .api(tmp) .cajoled("http://fake.url/", js, html) .run(new AsyncCallback<JavaScriptObject>() { @Override public void onFailure(Throwable t) { PlaygroundView.this.addCompileMessage(t.toString()); } @Override public void onSuccess(JavaScriptObject r) { PlaygroundView.this.setRenderedResult(r.toString()); } }); } }, domOpts); }
public void setRenderedResult( final String policy, final String html, final String js, final String idClass) { if (html == null && js == null) { playgroundUI.renderResult.setText("There were cajoling errors"); return; } // Make the cajoled content visible so that the DOM will be laid out before // the script checks DOM geometry. selectTab(Tabs.RENDER); Map<String, String> domOpts = new HashMap<String, String>(); domOpts.put("idClass", idClass); domOpts.put("title", "Playground Untrusted Content"); Caja.load( playgroundUI.renderPanel.getElement(), makeUriPolicy(), new AsyncCallback<Frame>() { @Override public void onFailure(Throwable t) { PlaygroundView.this.addCompileMessage(t.toString()); } @Override public void onSuccess(Frame frame) { JavaScriptObject tmp = makeExtraImports(Caja.getNative(), policy); augmentWith(tmp, "widgets", ((WidgetsTaming)GWT.create(WidgetsTaming.class)) .getJso(frame, new Widgets(playgroundUI.gwtShim))); augmentWith(tmp, "blivit", ((BlivitTaming)GWT.create(BlivitTaming.class)) .getJso(frame, new Blivit("hello world"))); frame .api(tmp) .cajoled("http://fake.url/", js, html) .run(new AsyncCallback<JavaScriptObject>() { @Override public void onFailure(Throwable t) { PlaygroundView.this.addCompileMessage(t.toString()); } @Override public void onSuccess(JavaScriptObject r) { PlaygroundView.this.setRenderedResult(r + ""); } }); } }, domOpts); }
diff --git a/src/gui/GameInfo.java b/src/gui/GameInfo.java index 610b253a..30542647 100644 --- a/src/gui/GameInfo.java +++ b/src/gui/GameInfo.java @@ -1,130 +1,130 @@ //----------------------------------------------------------------------------- // $Id$ // $Source$ //----------------------------------------------------------------------------- package gui; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import game.*; import go.*; import utils.*; //----------------------------------------------------------------------------- class GameInfo extends JPanel implements ActionListener { public GameInfo(TimeControl timeControl) { super(new GridLayout(0, 2, GuiUtils.SMALL_PAD, 0)); m_timeControl = timeControl; m_move = addEntry("To Play"); m_number = addEntry("Moves"); m_last = addEntry("Last Move"); m_captB = addEntry("Captured Black"); m_captW = addEntry("Captured White"); m_timeB = addEntry("Time Black"); m_timeW = addEntry("Time White"); m_timeB.setText("00:00"); m_timeW.setText("00:00"); new javax.swing.Timer(1000, this).start(); } public void actionPerformed(ActionEvent evt) { if (m_timeControl.isRunning()) { setTime(go.Color.BLACK); setTime(go.Color.WHITE); } } public void update(Node node, go.Board board) { if (board.getToMove() == go.Color.BLACK) m_move.setText("Black"); else m_move.setText("White"); String capturedB = Integer.toString(board.getCapturedB()); m_captB.setText(capturedB); String capturedW = Integer.toString(board.getCapturedW()); m_captW.setText(capturedW); int moveNumber = node.getMoveNumber(); String numberString = Integer.toString(moveNumber); int movesLeft = node.getMovesLeft(); if (movesLeft > 0) numberString += "/" + (moveNumber + movesLeft); m_number.setText(numberString); String lastMove = ""; Move move = node.getMove(); if (move != null) { go.Color c = move.getColor(); go.Point p = move.getPoint(); lastMove = (c == go.Color.BLACK ? "Black" : "White") + " "; if (p == null) lastMove += "PASS"; else lastMove += p.toString(); } m_last.setText(lastMove); float timeLeftBlack = node.getTimeLeftBlack(); int movesLeftBlack = node.getMovesLeftBlack(); if (! Float.isNaN(timeLeftBlack)) m_timeB.setText(TimeControl.getTimeString(timeLeftBlack, movesLeftBlack)); float timeLeftWhite = node.getTimeLeftWhite(); int movesLeftWhite = node.getMovesLeftWhite(); if (! Float.isNaN(timeLeftWhite)) m_timeW.setText(TimeControl.getTimeString(timeLeftWhite, - movesLeftBlack)); + movesLeftWhite)); } private JLabel m_move; private JLabel m_number; private JLabel m_last; private JLabel m_captB; private JLabel m_captW; private JLabel m_timeB; private JLabel m_timeW; private TimeControl m_timeControl; private JLabel addEntry(String text) { JLabel label = new JLabel(text); label.setHorizontalAlignment(SwingConstants.LEFT); add(label); JLabel entry = new JLabel(" "); entry.setHorizontalAlignment(SwingConstants.LEFT); entry.setBorder(BorderFactory.createLoweredBevelBorder()); add(entry); return entry; } private void setTime(go.Color c) { String text = m_timeControl.getTimeString(c); if (text == null) text = " "; if (c == go.Color.BLACK) m_timeB.setText(text); else m_timeW.setText(text); } } //-----------------------------------------------------------------------------
true
true
public void update(Node node, go.Board board) { if (board.getToMove() == go.Color.BLACK) m_move.setText("Black"); else m_move.setText("White"); String capturedB = Integer.toString(board.getCapturedB()); m_captB.setText(capturedB); String capturedW = Integer.toString(board.getCapturedW()); m_captW.setText(capturedW); int moveNumber = node.getMoveNumber(); String numberString = Integer.toString(moveNumber); int movesLeft = node.getMovesLeft(); if (movesLeft > 0) numberString += "/" + (moveNumber + movesLeft); m_number.setText(numberString); String lastMove = ""; Move move = node.getMove(); if (move != null) { go.Color c = move.getColor(); go.Point p = move.getPoint(); lastMove = (c == go.Color.BLACK ? "Black" : "White") + " "; if (p == null) lastMove += "PASS"; else lastMove += p.toString(); } m_last.setText(lastMove); float timeLeftBlack = node.getTimeLeftBlack(); int movesLeftBlack = node.getMovesLeftBlack(); if (! Float.isNaN(timeLeftBlack)) m_timeB.setText(TimeControl.getTimeString(timeLeftBlack, movesLeftBlack)); float timeLeftWhite = node.getTimeLeftWhite(); int movesLeftWhite = node.getMovesLeftWhite(); if (! Float.isNaN(timeLeftWhite)) m_timeW.setText(TimeControl.getTimeString(timeLeftWhite, movesLeftBlack)); }
public void update(Node node, go.Board board) { if (board.getToMove() == go.Color.BLACK) m_move.setText("Black"); else m_move.setText("White"); String capturedB = Integer.toString(board.getCapturedB()); m_captB.setText(capturedB); String capturedW = Integer.toString(board.getCapturedW()); m_captW.setText(capturedW); int moveNumber = node.getMoveNumber(); String numberString = Integer.toString(moveNumber); int movesLeft = node.getMovesLeft(); if (movesLeft > 0) numberString += "/" + (moveNumber + movesLeft); m_number.setText(numberString); String lastMove = ""; Move move = node.getMove(); if (move != null) { go.Color c = move.getColor(); go.Point p = move.getPoint(); lastMove = (c == go.Color.BLACK ? "Black" : "White") + " "; if (p == null) lastMove += "PASS"; else lastMove += p.toString(); } m_last.setText(lastMove); float timeLeftBlack = node.getTimeLeftBlack(); int movesLeftBlack = node.getMovesLeftBlack(); if (! Float.isNaN(timeLeftBlack)) m_timeB.setText(TimeControl.getTimeString(timeLeftBlack, movesLeftBlack)); float timeLeftWhite = node.getTimeLeftWhite(); int movesLeftWhite = node.getMovesLeftWhite(); if (! Float.isNaN(timeLeftWhite)) m_timeW.setText(TimeControl.getTimeString(timeLeftWhite, movesLeftWhite)); }
diff --git a/src/java/net/sf/jabref/imports/ImportCustomizationDialog.java b/src/java/net/sf/jabref/imports/ImportCustomizationDialog.java index 908005916..b4f4f7962 100644 --- a/src/java/net/sf/jabref/imports/ImportCustomizationDialog.java +++ b/src/java/net/sf/jabref/imports/ImportCustomizationDialog.java @@ -1,291 +1,299 @@ /* Copyright (C) 2005 Andreas Rudert, based on ExportCustomizationDialog by ?? All programs in this directory and subdirectories are published under the GNU General Public License as described below. 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Further information about the GNU GPL is available at: http://www.gnu.org/copyleft/gpl.ja.html */ package net.sf.jabref.imports; import javax.swing.JDialog; import java.awt.*; import net.sf.jabref.*; import javax.swing.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.util.zip.ZipFile; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumnModel; /** * Dialog to manage custom importers. */ public class ImportCustomizationDialog extends JDialog { private final JabRefFrame frame; private JButton addFromFolderButton = new JButton(Globals.lang("Add from folder")); private JButton addFromJarButton = new JButton(Globals.lang("Add from jar")); private JButton showDescButton = new JButton(Globals.lang("Show description")); private JButton removeButton = new JButton(Globals.lang("Remove")); private JButton closeButton = new JButton(Globals.lang("Close")); private JButton helpButton = new JButton(Globals.lang("Help")); private JPanel optionsPanel = new JPanel(); private JPanel mainPanel = new JPanel(); private JTable customImporterTable; private JabRefPreferences prefs = Globals.prefs; private ImportCustomizationDialog importCustomizationDialog; /* * (non-Javadoc) * @see java.awt.Component#getSize() */ public Dimension getSize() { int width = GUIGlobals.IMPORT_DIALOG_COL_0_WIDTH + GUIGlobals.IMPORT_DIALOG_COL_1_WIDTH + GUIGlobals.IMPORT_DIALOG_COL_2_WIDTH + GUIGlobals.IMPORT_DIALOG_COL_3_WIDTH; return new Dimension(width, width/2); } /** * Converts a path relative to a base-path into a class name. * * @param basePath base path * @param path path that includes base-path as a prefix * @return class name */ private String pathToClass(File basePath, File path) { String className = null; // remove leading basepath from path while (!path.equals(basePath)) { className = path.getName() + (className != null ? "." + className : ""); path = path.getParentFile(); } className = className.substring(0, className.lastIndexOf('.')); return className; } /** * Adds an importer to the model that underlies the custom importers. * * @param importer importer */ void addOrReplaceImporter(CustomImportList.Importer importer) { prefs.customImports.replaceImporter(importer); Globals.importFormatReader.resetImportFormats(); ((ImportTableModel)customImporterTable.getModel()).fireTableDataChanged(); } /** * * @param frame_ * @throws HeadlessException */ public ImportCustomizationDialog(JabRefFrame frame_) throws HeadlessException { super(frame_, Globals.lang("Manage custom imports"), false); this.importCustomizationDialog = this; frame = frame_; addFromFolderButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CustomImportList.Importer importer = prefs.customImports.new Importer(); importer.setBasePath( Globals.getNewDir(frame, prefs, new File(prefs.get("workingDirectory")), "", Globals.lang("Select Classpath of New Importer"), JFileChooser.CUSTOM_DIALOG, false) ); String chosenFileStr = Globals.getNewFile(frame, prefs, importer.getBasePath(), ".class", Globals.lang("Select new ImportFormat Subclass"), JFileChooser.CUSTOM_DIALOG, false); if (chosenFileStr != null) { try { importer.setClassName( pathToClass(importer.getBasePath(), new File(chosenFileStr)) ); importer.setName( importer.getInstance().getFormatName() ); importer.setCliId( importer.getInstance().getCLIId() ); } catch (Exception exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1", chosenFileStr + ":\n", exc.getMessage())); + } catch (NoClassDefFoundError exc) { + exc.printStackTrace(); + JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1. Have you chosen the correct package path?", chosenFileStr + ":\n", exc.getMessage())); } addOrReplaceImporter(importer); customImporterTable.revalidate(); customImporterTable.repaint(); frame.setUpImportMenus(); } } }); addFromFolderButton.setToolTipText(Globals.lang("Add a (compiled) custom ImportFormat class from a class path. \nThe path need not be on the classpath of JabRef.")); addFromJarButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String basePath = Globals.getNewFile(frame, prefs, new File(prefs.get("workingDirectory")), ".zip,.jar", Globals.lang("Select a Zip-archive"), JFileChooser.CUSTOM_DIALOG, false); ZipFile zipFile = null; if (basePath != null) { try { zipFile = new ZipFile(new File(basePath), ZipFile.OPEN_READ); } catch (IOException exc) { exc.printStackTrace(); - JOptionPane.showMessageDialog(frame, Globals.lang("Could not open %0 %1", basePath + ":\n", exc.getMessage())); + JOptionPane.showMessageDialog(frame, Globals.lang("Could not open %0 %1", basePath + ":\n", exc.getMessage()) + + "\n" + Globals.lang("Have you chosen the correct package path?")); return; + } catch (NoClassDefFoundError exc) { + exc.printStackTrace(); + JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1", basePath + ":\n", exc.getMessage()) + + "\n" + Globals.lang("Have you chosen the correct package path?")); } } if (zipFile != null) { ZipFileChooser zipFileChooser = new ZipFileChooser(importCustomizationDialog, zipFile); zipFileChooser.setVisible(true); } customImporterTable.revalidate(); customImporterTable.repaint(10); frame.setUpImportMenus(); } }); addFromJarButton.setToolTipText(Globals.lang("Add a (compiled) custom ImportFormat class from a Zip-archive.\nThe Zip-archive need not be on the classpath of JabRef.")); showDescButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = customImporterTable.getSelectedRow(); if (row != -1) { CustomImportList.Importer importer = ((ImportTableModel)customImporterTable.getModel()).getImporter(row); try { ImportFormat importFormat = importer.getInstance(); JOptionPane.showMessageDialog(frame, importFormat.getDescription()); } catch (Exception exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1", importer.getName() + ":\n", exc.getMessage())); } } else { JOptionPane.showMessageDialog(frame, Globals.lang("Please select an importer")); } } }); removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = customImporterTable.getSelectedRow(); if (row != -1) { customImporterTable.removeRowSelectionInterval(row,row); prefs.customImports.remove(((ImportTableModel)customImporterTable.getModel()).getImporter(row)); Globals.importFormatReader.resetImportFormats(); customImporterTable.revalidate(); customImporterTable.repaint(); frame.setUpImportMenus(); } else { JOptionPane.showMessageDialog(frame, Globals.lang("Please select an importer.")); } } }); AbstractAction closeAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dispose(); } }; closeButton.addActionListener(closeAction); helpButton.addActionListener(new HelpAction(frame.helpDiag, GUIGlobals.importCustomizationHelp, "Help")); ImportTableModel tableModel = new ImportTableModel(); customImporterTable = new JTable(tableModel); TableColumnModel cm = customImporterTable.getColumnModel(); cm.getColumn(0).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_0_WIDTH); cm.getColumn(1).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_1_WIDTH); cm.getColumn(2).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_2_WIDTH); cm.getColumn(3).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_3_WIDTH); JScrollPane sp = new JScrollPane(customImporterTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); customImporterTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); customImporterTable.setPreferredScrollableViewportSize(getSize()); if (customImporterTable.getRowCount() > 0) { customImporterTable.setRowSelectionInterval(0, 0); } // Key bindings: ActionMap am = mainPanel.getActionMap(); InputMap im = mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(frame.prefs().getKey("Close dialog"), "close"); am.put("close", closeAction); mainPanel.setLayout(new BorderLayout()); mainPanel.add(sp, BorderLayout.CENTER); optionsPanel.add(addFromFolderButton); optionsPanel.add(addFromJarButton); optionsPanel.add(showDescButton); optionsPanel.add(removeButton); optionsPanel.add(closeButton); optionsPanel.add(Box.createHorizontalStrut(5)); optionsPanel.add(helpButton); getContentPane().add(mainPanel, BorderLayout.CENTER); getContentPane().add(optionsPanel, BorderLayout.SOUTH); this.setSize(getSize()); pack(); Util.placeDialog(this, frame); new FocusRequester(customImporterTable); } /** * Table model for the custom importer table. */ class ImportTableModel extends AbstractTableModel { private String[] columnNames = new String[] { Globals.lang("Import name"), Globals.lang("Command line id"), Globals.lang("ImportFormat class"), Globals.lang("Contained in") }; public Object getValueAt(int rowIndex, int columnIndex) { Object value = null; CustomImportList.Importer importer = getImporter(rowIndex); if (columnIndex == 0) { value = importer.getName(); } else if (columnIndex == 1) { value = importer.getClidId(); } else if (columnIndex == 2) { value = importer.getClassName(); } else if (columnIndex == 3) { value = importer.getBasePath(); } return value; } public int getColumnCount() { return columnNames.length; } public int getRowCount() { return Globals.prefs.customImports.size(); } public String getColumnName(int col) { return columnNames[col]; } public CustomImportList.Importer getImporter(int rowIndex) { CustomImportList.Importer[] importers = (CustomImportList.Importer[])Globals.prefs.customImports.toArray(new CustomImportList.Importer[] {}); return importers[rowIndex]; } } }
false
true
public ImportCustomizationDialog(JabRefFrame frame_) throws HeadlessException { super(frame_, Globals.lang("Manage custom imports"), false); this.importCustomizationDialog = this; frame = frame_; addFromFolderButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CustomImportList.Importer importer = prefs.customImports.new Importer(); importer.setBasePath( Globals.getNewDir(frame, prefs, new File(prefs.get("workingDirectory")), "", Globals.lang("Select Classpath of New Importer"), JFileChooser.CUSTOM_DIALOG, false) ); String chosenFileStr = Globals.getNewFile(frame, prefs, importer.getBasePath(), ".class", Globals.lang("Select new ImportFormat Subclass"), JFileChooser.CUSTOM_DIALOG, false); if (chosenFileStr != null) { try { importer.setClassName( pathToClass(importer.getBasePath(), new File(chosenFileStr)) ); importer.setName( importer.getInstance().getFormatName() ); importer.setCliId( importer.getInstance().getCLIId() ); } catch (Exception exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1", chosenFileStr + ":\n", exc.getMessage())); } addOrReplaceImporter(importer); customImporterTable.revalidate(); customImporterTable.repaint(); frame.setUpImportMenus(); } } }); addFromFolderButton.setToolTipText(Globals.lang("Add a (compiled) custom ImportFormat class from a class path. \nThe path need not be on the classpath of JabRef.")); addFromJarButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String basePath = Globals.getNewFile(frame, prefs, new File(prefs.get("workingDirectory")), ".zip,.jar", Globals.lang("Select a Zip-archive"), JFileChooser.CUSTOM_DIALOG, false); ZipFile zipFile = null; if (basePath != null) { try { zipFile = new ZipFile(new File(basePath), ZipFile.OPEN_READ); } catch (IOException exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not open %0 %1", basePath + ":\n", exc.getMessage())); return; } } if (zipFile != null) { ZipFileChooser zipFileChooser = new ZipFileChooser(importCustomizationDialog, zipFile); zipFileChooser.setVisible(true); } customImporterTable.revalidate(); customImporterTable.repaint(10); frame.setUpImportMenus(); } }); addFromJarButton.setToolTipText(Globals.lang("Add a (compiled) custom ImportFormat class from a Zip-archive.\nThe Zip-archive need not be on the classpath of JabRef.")); showDescButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = customImporterTable.getSelectedRow(); if (row != -1) { CustomImportList.Importer importer = ((ImportTableModel)customImporterTable.getModel()).getImporter(row); try { ImportFormat importFormat = importer.getInstance(); JOptionPane.showMessageDialog(frame, importFormat.getDescription()); } catch (Exception exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1", importer.getName() + ":\n", exc.getMessage())); } } else { JOptionPane.showMessageDialog(frame, Globals.lang("Please select an importer")); } } }); removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = customImporterTable.getSelectedRow(); if (row != -1) { customImporterTable.removeRowSelectionInterval(row,row); prefs.customImports.remove(((ImportTableModel)customImporterTable.getModel()).getImporter(row)); Globals.importFormatReader.resetImportFormats(); customImporterTable.revalidate(); customImporterTable.repaint(); frame.setUpImportMenus(); } else { JOptionPane.showMessageDialog(frame, Globals.lang("Please select an importer.")); } } }); AbstractAction closeAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dispose(); } }; closeButton.addActionListener(closeAction); helpButton.addActionListener(new HelpAction(frame.helpDiag, GUIGlobals.importCustomizationHelp, "Help")); ImportTableModel tableModel = new ImportTableModel(); customImporterTable = new JTable(tableModel); TableColumnModel cm = customImporterTable.getColumnModel(); cm.getColumn(0).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_0_WIDTH); cm.getColumn(1).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_1_WIDTH); cm.getColumn(2).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_2_WIDTH); cm.getColumn(3).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_3_WIDTH); JScrollPane sp = new JScrollPane(customImporterTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); customImporterTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); customImporterTable.setPreferredScrollableViewportSize(getSize()); if (customImporterTable.getRowCount() > 0) { customImporterTable.setRowSelectionInterval(0, 0); } // Key bindings: ActionMap am = mainPanel.getActionMap(); InputMap im = mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(frame.prefs().getKey("Close dialog"), "close"); am.put("close", closeAction); mainPanel.setLayout(new BorderLayout()); mainPanel.add(sp, BorderLayout.CENTER); optionsPanel.add(addFromFolderButton); optionsPanel.add(addFromJarButton); optionsPanel.add(showDescButton); optionsPanel.add(removeButton); optionsPanel.add(closeButton); optionsPanel.add(Box.createHorizontalStrut(5)); optionsPanel.add(helpButton); getContentPane().add(mainPanel, BorderLayout.CENTER); getContentPane().add(optionsPanel, BorderLayout.SOUTH); this.setSize(getSize()); pack(); Util.placeDialog(this, frame); new FocusRequester(customImporterTable); }
public ImportCustomizationDialog(JabRefFrame frame_) throws HeadlessException { super(frame_, Globals.lang("Manage custom imports"), false); this.importCustomizationDialog = this; frame = frame_; addFromFolderButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CustomImportList.Importer importer = prefs.customImports.new Importer(); importer.setBasePath( Globals.getNewDir(frame, prefs, new File(prefs.get("workingDirectory")), "", Globals.lang("Select Classpath of New Importer"), JFileChooser.CUSTOM_DIALOG, false) ); String chosenFileStr = Globals.getNewFile(frame, prefs, importer.getBasePath(), ".class", Globals.lang("Select new ImportFormat Subclass"), JFileChooser.CUSTOM_DIALOG, false); if (chosenFileStr != null) { try { importer.setClassName( pathToClass(importer.getBasePath(), new File(chosenFileStr)) ); importer.setName( importer.getInstance().getFormatName() ); importer.setCliId( importer.getInstance().getCLIId() ); } catch (Exception exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1", chosenFileStr + ":\n", exc.getMessage())); } catch (NoClassDefFoundError exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1. Have you chosen the correct package path?", chosenFileStr + ":\n", exc.getMessage())); } addOrReplaceImporter(importer); customImporterTable.revalidate(); customImporterTable.repaint(); frame.setUpImportMenus(); } } }); addFromFolderButton.setToolTipText(Globals.lang("Add a (compiled) custom ImportFormat class from a class path. \nThe path need not be on the classpath of JabRef.")); addFromJarButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String basePath = Globals.getNewFile(frame, prefs, new File(prefs.get("workingDirectory")), ".zip,.jar", Globals.lang("Select a Zip-archive"), JFileChooser.CUSTOM_DIALOG, false); ZipFile zipFile = null; if (basePath != null) { try { zipFile = new ZipFile(new File(basePath), ZipFile.OPEN_READ); } catch (IOException exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not open %0 %1", basePath + ":\n", exc.getMessage()) + "\n" + Globals.lang("Have you chosen the correct package path?")); return; } catch (NoClassDefFoundError exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1", basePath + ":\n", exc.getMessage()) + "\n" + Globals.lang("Have you chosen the correct package path?")); } } if (zipFile != null) { ZipFileChooser zipFileChooser = new ZipFileChooser(importCustomizationDialog, zipFile); zipFileChooser.setVisible(true); } customImporterTable.revalidate(); customImporterTable.repaint(10); frame.setUpImportMenus(); } }); addFromJarButton.setToolTipText(Globals.lang("Add a (compiled) custom ImportFormat class from a Zip-archive.\nThe Zip-archive need not be on the classpath of JabRef.")); showDescButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = customImporterTable.getSelectedRow(); if (row != -1) { CustomImportList.Importer importer = ((ImportTableModel)customImporterTable.getModel()).getImporter(row); try { ImportFormat importFormat = importer.getInstance(); JOptionPane.showMessageDialog(frame, importFormat.getDescription()); } catch (Exception exc) { exc.printStackTrace(); JOptionPane.showMessageDialog(frame, Globals.lang("Could not instantiate %0 %1", importer.getName() + ":\n", exc.getMessage())); } } else { JOptionPane.showMessageDialog(frame, Globals.lang("Please select an importer")); } } }); removeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = customImporterTable.getSelectedRow(); if (row != -1) { customImporterTable.removeRowSelectionInterval(row,row); prefs.customImports.remove(((ImportTableModel)customImporterTable.getModel()).getImporter(row)); Globals.importFormatReader.resetImportFormats(); customImporterTable.revalidate(); customImporterTable.repaint(); frame.setUpImportMenus(); } else { JOptionPane.showMessageDialog(frame, Globals.lang("Please select an importer.")); } } }); AbstractAction closeAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { dispose(); } }; closeButton.addActionListener(closeAction); helpButton.addActionListener(new HelpAction(frame.helpDiag, GUIGlobals.importCustomizationHelp, "Help")); ImportTableModel tableModel = new ImportTableModel(); customImporterTable = new JTable(tableModel); TableColumnModel cm = customImporterTable.getColumnModel(); cm.getColumn(0).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_0_WIDTH); cm.getColumn(1).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_1_WIDTH); cm.getColumn(2).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_2_WIDTH); cm.getColumn(3).setPreferredWidth(GUIGlobals.IMPORT_DIALOG_COL_3_WIDTH); JScrollPane sp = new JScrollPane(customImporterTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); customImporterTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); customImporterTable.setPreferredScrollableViewportSize(getSize()); if (customImporterTable.getRowCount() > 0) { customImporterTable.setRowSelectionInterval(0, 0); } // Key bindings: ActionMap am = mainPanel.getActionMap(); InputMap im = mainPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); im.put(frame.prefs().getKey("Close dialog"), "close"); am.put("close", closeAction); mainPanel.setLayout(new BorderLayout()); mainPanel.add(sp, BorderLayout.CENTER); optionsPanel.add(addFromFolderButton); optionsPanel.add(addFromJarButton); optionsPanel.add(showDescButton); optionsPanel.add(removeButton); optionsPanel.add(closeButton); optionsPanel.add(Box.createHorizontalStrut(5)); optionsPanel.add(helpButton); getContentPane().add(mainPanel, BorderLayout.CENTER); getContentPane().add(optionsPanel, BorderLayout.SOUTH); this.setSize(getSize()); pack(); Util.placeDialog(this, frame); new FocusRequester(customImporterTable); }
diff --git a/src/com/github/pmcompany/pustomario/core/ConcreteGame.java b/src/com/github/pmcompany/pustomario/core/ConcreteGame.java index 0c0fa2f..28e9790 100644 --- a/src/com/github/pmcompany/pustomario/core/ConcreteGame.java +++ b/src/com/github/pmcompany/pustomario/core/ConcreteGame.java @@ -1,649 +1,655 @@ package com.github.pmcompany.pustomario.core; import com.github.pmcompany.pustomario.io.View; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*; import static com.github.pmcompany.pustomario.core.VectorDirection.*; /** * @author dector ([email protected]) */ public class ConcreteGame implements EventHandler, DataProvider, EventServer { private static final int TRACE_RAY_COEF = 1; private static final int HIT_DECREMENT_HP_VALUE = 10; private Map map; private java.util.Map<String, Player> players; private EventHandler generatedEventsEventHandler; private String playerName; private Player currentPlayer; private List<EventHandler> handlers; private long updateTime; private Player hitedPlayer; private List<Point> spawnPoints; private Rating rate; public ConcreteGame(String playerName) { this.playerName = playerName; players = new LinkedHashMap<String, Player>(); handlers = new LinkedList<EventHandler>(); } public void initGame() { spawnPoints = new LinkedList<Point>(); loadMap(); initPlayers(); updateTime = System.currentTimeMillis(); } private void initPlayers() { rate = new Rating(); if (players.isEmpty()) { Player p = new Player(0, 0); p.setName(playerName); players.put(playerName, p); } for (Player p : players.values()) { spawn(p); rate.addPlayer(p); } } private void spawn(Player p) { System.out.println("Respawning player " + p.getName()); Random rnd = new Random(); Point spawnPoint = spawnPoints.get(rnd.nextInt(spawnPoints.size())); p.setHp(Player.START_HP); p.setX((spawnPoint.getX()-1) * View.TILE_WIDTH + 1); p.setY((spawnPoint.getY()-1) * View.TILE_HEIGHT + 1); } private void loadMap() { try { BufferedReader reader; reader = new BufferedReader(new FileReader("level.pml")); String[] levelParams = reader.readLine().split(" "); int levelWidth = Integer.parseInt(levelParams[0]); int levelHeight = Integer.parseInt(levelParams[1]); map = new Map(levelWidth, levelHeight); int tile; for (int j = levelHeight; j > 0; j--) { String levelLine = reader.readLine(); for (int i = 1; i <= levelWidth; i++) { tile = levelLine.charAt(i-1); if (tile == '#') { map.setAt(i, j, levelLine.charAt(i-1)); } else if (tile == '@') { spawnPoints.add(new Point(i, j)); // if (playerName != null) { // currentPlayer = new Player((i-1) * View.TILE_WIDTH + 1, // (j-1) * View.TILE_HEIGHT + 1); // } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (currentPlayer == null) { currentPlayer = new Player(1, 1); } currentPlayer.setName(playerName); players.put(currentPlayer.getName(), currentPlayer); } public void handleEvent(Event e) { Player p; if (e.getStringValue().equals(getPlayerName())) { p = currentPlayer; } else { p = players.get(e.getSender()); } if (p != null) { System.out.printf("Handling event from %s %n", p.getName()); } switch (e.getType()) { // case ACCELERATE_X_PLAYER: { // p.accelerateX(e.getFloatValue() * Physics.RUN_ACCELERATION_COEFFICIENT); // } break; // case ACCELERATE_Y_PLAYER: { // p.accelerateY(e.getFloatValue()); // } break; case RUN_RIGHT: { - p.accelerateX(Physics.RUN_SPEED); + if (p != null) { + p.accelerateX(Physics.RUN_SPEED); + } } break; case RUN_LEFT: { - p.accelerateX(-Physics.RUN_SPEED); + if (p != null) { + p.accelerateX(-Physics.RUN_SPEED); + } } break; case JUMP: { - if (p.isCanJump()) { - p.accelerateY(Physics.JUMP_SPEED); - p.setCanJump(false); + if (p != null) { + if (p.isCanJump()) { + p.accelerateY(Physics.JUMP_SPEED); + p.setCanJump(false); + } } } break; case SHOOT: { String[] pos = e.getStringValue().split(" "); int sx = Integer.parseInt(pos[0]); int sy = Integer.parseInt(pos[1]); countShoot(currentPlayer.getPosition(), new Point(sx, sy)); if (hitedPlayer != null) { Event event = new GameEvent(EventType.INCREMENT_HP, e.getSender(), hitedPlayer.getName() + " -" + HIT_DECREMENT_HP_VALUE); for (EventHandler h : handlers) { h.handleEvent(event); } hitedPlayer = null; handleEvent(event); } } break; case INCREMENT_HP: { String[] values = e.getStringValue().split(" "); int leftHP = players.get(values[0]).changeHP(Integer.parseInt(values[1])); if (leftHP <= 0) { GameEvent event = new GameEvent(EventType.KILLED, e.getSender(), values[0]); for (EventHandler h : handlers) { h.handleEvent(event); } handleEvent(event); } } break; case KILLED: { System.out.printf("%s: %s killed %s%n", playerName, e.getSender(), e.getStringValue()); rate.incScore(players.get(e.getSender()), 1); rate.incScore(players.get(e.getStringValue()), -1); GameEvent event = new GameEvent(EventType.REBORN, e.getSender(), e.getStringValue()); for (EventHandler h : handlers) { h.handleEvent(event); } handleEvent(event); } break; case REBORN: { spawn(players.get(e.getStringValue())); } break; case JOIN_NEW_PLAYER: { String[] playerInfo = e.getStringValue().split(" "); int x = Integer.parseInt(playerInfo[0]); int y = Integer.parseInt(playerInfo[1]); Player newPlayer = new Player(x, y); newPlayer.setName(e.getSender()); players.put(newPlayer.getName(), newPlayer); rate.addPlayer(newPlayer); } break; case MOVE_PLAYER: { if (p != currentPlayer && p != null) { String[] pos = e.getStringValue().split(" "); int x = Integer.parseInt(pos[0]); int y = Integer.parseInt(pos[1]); p.setX(x); p.setY(y); } } break; // case SET_PLAYER_X: { // currentPlayer.setX(e.getIntValue()); // } break; // case SET_PLAYER_Y: { // currentPlayer.setY(e.getIntValue()); // } break; } } public int getTileAt(int x, int y) { return map.getAt(x, y); } public Point countTileByAbs(int absX, int absY) { return new Point((absX-1) / View.TILE_WIDTH + 1, (absY-1) / View.TILE_HEIGHT + 1); } public Point countAbsByTile(Point p) { return countAbsByTile(p.getX(), p.getY()); } public Point countAbsByTile(int tX, int tY) { return new Point((tX - 1) * View.TILE_WIDTH + 1, (tY - 1) * View.TILE_HEIGHT + 1); } public boolean isTileBlocked(int x, int y) { return map.isBlocked(x, y); } public int getPlayerX() { return currentPlayer.getX(); } public int getPlayerY() { return currentPlayer.getY(); } public float getPlayerSpeedX() { return currentPlayer.getSpeedX(); } public float getPlayerSpeedY() { return currentPlayer.getSpeedY(); } public int getMapWidth() { return map.getWidth(); } public int getMapHeight() { return map.getHeight(); } public boolean isPlayerWatchingRight() { return currentPlayer.isWatchingRight(); } public void preUpdate() { long currTime = System.currentTimeMillis(); long diff = currTime - updateTime; // Count dynamic objects position, // using physical laws and time value for (Player p : players.values()) { movePlayer(p); if (p == currentPlayer && p.moved()) { // System.out.printf("%b X %d->%d Y %d->%d%n", p.moved(), p.getPrevX(), p.getX(), // p.getPrevY(), p.getY()); for (EventHandler h : handlers) { h.handleEvent(new GameEvent(EventType.MOVE_PLAYER, currentPlayer.getName(), String.format("%d %d", currentPlayer.getX(), currentPlayer.getY()))); } } } updateTime = currTime; } public void postUpdate() { // currentPlayer.setSpeedX(0); // currentPlayer.setSpeedY(0); } private void movePlayer(Player currentPlayer) { currentPlayer.accelerateY(Physics.GRAVITY_ACCELERATION); currentPlayer.setSpeedX(currentPlayer.getSpeedX() * Physics.GROUND_ONE_ON_FRICTION); int px = currentPlayer.getX(); int py = currentPlayer.getY(); float speedX = currentPlayer.getSpeedX(); float speedY = currentPlayer.getSpeedY(); // Move currentPlayer if (currentPlayer == this.currentPlayer) { currentPlayer.setPrevX(px); currentPlayer.setPrevY(py); } Point newCrossedTile = null; List<Point> crossedTiles; boolean crosses = false; if (speedX != 0) { currentPlayer.setX(px + (int) speedX); crossedTiles = getPlayerCrossedTiles(currentPlayer); for (int i = 0; i < crossedTiles.size() && (! crosses); i++) { newCrossedTile = crossedTiles.get(i); if (isTileBlocked(newCrossedTile.getX(), newCrossedTile.getY())) { crosses = true; } } if (crosses) { currentPlayer.setX(px); currentPlayer.setSpeedX(0); } } crosses = false; if (speedY != 0) { currentPlayer.setY(py + (int) speedY); crossedTiles = getPlayerCrossedTiles(currentPlayer); for (int i = 0; i < crossedTiles.size() && (! crosses); i++) { newCrossedTile = crossedTiles.get(i); if (isTileBlocked(newCrossedTile.getX(), newCrossedTile.getY())) { crosses = true; } } if (crosses) { currentPlayer.setY(py); if (speedY < 0) { currentPlayer.setCanJump(true); } currentPlayer.setSpeedY(0); } } } public List<Point> getPlayerCrossedTiles(Player currentPlayer) { List<Point> tilesList = new LinkedList<Point>(); int px = currentPlayer.getX(); int py = currentPlayer.getY(); int lx = 0; int ly = 0; int nx; int ny; int dx; int dy; Point p; for (int i = 0; i < 4; i++) { nx = px + lx * (View.TILE_WIDTH - 1); ny = py + ly * (View.TILE_HEIGHT - 1); dx = nx % View.TILE_WIDTH; dy = ny % View.TILE_HEIGHT; nx -= ((dx != 0)?dx:View.TILE_WIDTH) - 1; ny -= ((dy != 0)?dy:View.TILE_HEIGHT) - 1; p = countTileByAbs(nx, ny); if (! tilesList.contains(p)) { tilesList.add(p); } if (i == 1) { lx = 1; } else if (i == 0) { ly = 1; } else if (i == 2) { ly = 0; } } return tilesList; } /* * 1 * ^ * 8 < . > 2 * V * 4 */ public List<Point> getPlayerNeighbourTiles(Player currentPlayer, int direction) { List<Point> points = new LinkedList<Point>(); List<Point> crossedTiles = getPlayerCrossedTiles(currentPlayer); int lx; int ly; Point nP; Point crossedP; for (int i = 0; i < crossedTiles.size(); i++) { crossedP = crossedTiles.get(i); int k = 0; int directionMask; for (int j = 0; j < 4; j++) { directionMask = 0; if (direction != 0) { if ((direction & UP) != 0) { ly = 1; directionMask |= UP; } else if ((direction & DOWN) != 0) { ly = -1; directionMask |= DOWN; } else { ly = 0; } if ((direction & RIGHT) != 0) { lx = 1; directionMask |= RIGHT; } else if ((direction & LEFT) != 0) { lx = -1; directionMask |= LEFT; } else { lx = 0; } nP = new Point(crossedP.getX() + lx, crossedP.getY() + ly); if (! crossedTiles.contains(nP) && ! points.contains(nP)) { points.add(nP); } } k++; } } return points; } // private int[][] getPlayerTiles() { // int[][] pTiles = new int[4][2]; // // int px = currentPlayer.getX(); // int py = currentPlayer.getY(); // int rx = View.TILE_XRADIUS; // int ry = View.TILE_YRADIUS; // // pTiles[0][0] = px - rx; // pTiles[0][1] = py + ry; // pTiles[1][0] = px + rx; // pTiles[1][1] = py + ry; // pTiles[2][0] = px + rx; // pTiles[2][1] = py - ry; // pTiles[3][0] = px - rx; // pTiles[3][1] = py - ry; // // return pTiles; // } public int getPlayerX(String name) { return players.get(name).getX(); } public int getPlayerY(String name) { return players.get(name).getY(); } public float getPlayerSpeedX(String name) { return players.get(name).getSpeedX(); } public float getPlayerSpeedY(String name) { return players.get(name).getSpeedY(); } public boolean isPlayerWatchingRight(String name) { return players.get(name).isWatchingRight(); } public String getPlayerName() { return currentPlayer.getName(); } public void setPlayerName(String newName) { currentPlayer.setName(newName); } public void addPlayer(String name, int x, int y) { Player p = new Player(x, y); p.setName(name); players.put(name, p); } public Iterator<Player> getPlayersIterator() { return players.values().iterator(); } public int getPlayersNum() { return players.size(); } public Player getPlayer() { return currentPlayer; } public void addEventHandler(EventHandler handler) { handlers.add(handler); } public void removeEventHandler(EventHandler handler) { handlers.remove(handler); } public Player getPlayerByName(String name) { return players.get(name); } public void removeMainPlayer() { players.remove(currentPlayer.getName()); } public Point countShoot(Point start, Point aim) { return countShoot(start, aim, true); } public Point countShoot(Point start, Point aim, boolean fillShooted) { boolean done = false; double cx = start.getX(); double cy = start.getY(); int sx = aim.getX(); int sy = aim.getY(); System.out.printf("Counting shoot from %.0f:%.0f to %d:%d%n", cx, cy, sx, sy); double c = Math.sqrt(Math.pow(sx - cx, 2) + Math.pow(sy - cy, 2)); double cosf = (sx - cx) / c; double sinf = (sy - cy) / c; Point currTile = countTileByAbs((int)cx, (int)cy); Point prevTile; while (! done) { cx += TRACE_RAY_COEF * cosf; cy += TRACE_RAY_COEF * sinf; if (0 < cx && cx < getMapWidth() * View.TILE_WIDTH && 0 < cy && cy < getMapHeight() * View.TILE_HEIGHT) { prevTile = currTile; currTile = countTileByAbs((int)cx, (int)cy); for (Player p : players.values()) { if (p != currentPlayer && p.getX() <= cx && cx <= p.getX() + View.TILE_WIDTH/2 && p.getY() <= cy && cy <= p.getY() + View.TILE_HEIGHT/2) { done = true; if (fillShooted) { hitedPlayer = p; } } } if (! currTile.equals(prevTile)) { if (getTileAt(currTile.getX(), currTile.getY()) == '#') { done = true; } } } else { done = true; } } return new Point((int)cx, (int)cy); } public Point getPlayerPosition() { return currentPlayer.getPosition(); } public EventHandler getGeneratedEventsEventHandler() { return generatedEventsEventHandler; } public void setGeneratedEventsEventHandler(EventHandler generatedEventsEventHandler) { this.generatedEventsEventHandler = generatedEventsEventHandler; } public String getWinnerName() { Player p = rate.getWinner(); if (p != null) { return p.getName(); } else { return "N/a"; } } public int getWinnerScore() { return rate.getScore(rate.getWinner()); } public int getScore(Player p) { return rate.getScore(p); } }
false
true
public void handleEvent(Event e) { Player p; if (e.getStringValue().equals(getPlayerName())) { p = currentPlayer; } else { p = players.get(e.getSender()); } if (p != null) { System.out.printf("Handling event from %s %n", p.getName()); } switch (e.getType()) { // case ACCELERATE_X_PLAYER: { // p.accelerateX(e.getFloatValue() * Physics.RUN_ACCELERATION_COEFFICIENT); // } break; // case ACCELERATE_Y_PLAYER: { // p.accelerateY(e.getFloatValue()); // } break; case RUN_RIGHT: { p.accelerateX(Physics.RUN_SPEED); } break; case RUN_LEFT: { p.accelerateX(-Physics.RUN_SPEED); } break; case JUMP: { if (p.isCanJump()) { p.accelerateY(Physics.JUMP_SPEED); p.setCanJump(false); } } break; case SHOOT: { String[] pos = e.getStringValue().split(" "); int sx = Integer.parseInt(pos[0]); int sy = Integer.parseInt(pos[1]); countShoot(currentPlayer.getPosition(), new Point(sx, sy)); if (hitedPlayer != null) { Event event = new GameEvent(EventType.INCREMENT_HP, e.getSender(), hitedPlayer.getName() + " -" + HIT_DECREMENT_HP_VALUE); for (EventHandler h : handlers) { h.handleEvent(event); } hitedPlayer = null; handleEvent(event); } } break; case INCREMENT_HP: { String[] values = e.getStringValue().split(" "); int leftHP = players.get(values[0]).changeHP(Integer.parseInt(values[1])); if (leftHP <= 0) { GameEvent event = new GameEvent(EventType.KILLED, e.getSender(), values[0]); for (EventHandler h : handlers) { h.handleEvent(event); } handleEvent(event); } } break; case KILLED: { System.out.printf("%s: %s killed %s%n", playerName, e.getSender(), e.getStringValue()); rate.incScore(players.get(e.getSender()), 1); rate.incScore(players.get(e.getStringValue()), -1); GameEvent event = new GameEvent(EventType.REBORN, e.getSender(), e.getStringValue()); for (EventHandler h : handlers) { h.handleEvent(event); } handleEvent(event); } break; case REBORN: { spawn(players.get(e.getStringValue())); } break; case JOIN_NEW_PLAYER: { String[] playerInfo = e.getStringValue().split(" "); int x = Integer.parseInt(playerInfo[0]); int y = Integer.parseInt(playerInfo[1]); Player newPlayer = new Player(x, y); newPlayer.setName(e.getSender()); players.put(newPlayer.getName(), newPlayer); rate.addPlayer(newPlayer); } break; case MOVE_PLAYER: { if (p != currentPlayer && p != null) { String[] pos = e.getStringValue().split(" "); int x = Integer.parseInt(pos[0]); int y = Integer.parseInt(pos[1]); p.setX(x); p.setY(y); } } break; // case SET_PLAYER_X: { // currentPlayer.setX(e.getIntValue()); // } break; // case SET_PLAYER_Y: { // currentPlayer.setY(e.getIntValue()); // } break; } }
public void handleEvent(Event e) { Player p; if (e.getStringValue().equals(getPlayerName())) { p = currentPlayer; } else { p = players.get(e.getSender()); } if (p != null) { System.out.printf("Handling event from %s %n", p.getName()); } switch (e.getType()) { // case ACCELERATE_X_PLAYER: { // p.accelerateX(e.getFloatValue() * Physics.RUN_ACCELERATION_COEFFICIENT); // } break; // case ACCELERATE_Y_PLAYER: { // p.accelerateY(e.getFloatValue()); // } break; case RUN_RIGHT: { if (p != null) { p.accelerateX(Physics.RUN_SPEED); } } break; case RUN_LEFT: { if (p != null) { p.accelerateX(-Physics.RUN_SPEED); } } break; case JUMP: { if (p != null) { if (p.isCanJump()) { p.accelerateY(Physics.JUMP_SPEED); p.setCanJump(false); } } } break; case SHOOT: { String[] pos = e.getStringValue().split(" "); int sx = Integer.parseInt(pos[0]); int sy = Integer.parseInt(pos[1]); countShoot(currentPlayer.getPosition(), new Point(sx, sy)); if (hitedPlayer != null) { Event event = new GameEvent(EventType.INCREMENT_HP, e.getSender(), hitedPlayer.getName() + " -" + HIT_DECREMENT_HP_VALUE); for (EventHandler h : handlers) { h.handleEvent(event); } hitedPlayer = null; handleEvent(event); } } break; case INCREMENT_HP: { String[] values = e.getStringValue().split(" "); int leftHP = players.get(values[0]).changeHP(Integer.parseInt(values[1])); if (leftHP <= 0) { GameEvent event = new GameEvent(EventType.KILLED, e.getSender(), values[0]); for (EventHandler h : handlers) { h.handleEvent(event); } handleEvent(event); } } break; case KILLED: { System.out.printf("%s: %s killed %s%n", playerName, e.getSender(), e.getStringValue()); rate.incScore(players.get(e.getSender()), 1); rate.incScore(players.get(e.getStringValue()), -1); GameEvent event = new GameEvent(EventType.REBORN, e.getSender(), e.getStringValue()); for (EventHandler h : handlers) { h.handleEvent(event); } handleEvent(event); } break; case REBORN: { spawn(players.get(e.getStringValue())); } break; case JOIN_NEW_PLAYER: { String[] playerInfo = e.getStringValue().split(" "); int x = Integer.parseInt(playerInfo[0]); int y = Integer.parseInt(playerInfo[1]); Player newPlayer = new Player(x, y); newPlayer.setName(e.getSender()); players.put(newPlayer.getName(), newPlayer); rate.addPlayer(newPlayer); } break; case MOVE_PLAYER: { if (p != currentPlayer && p != null) { String[] pos = e.getStringValue().split(" "); int x = Integer.parseInt(pos[0]); int y = Integer.parseInt(pos[1]); p.setX(x); p.setY(y); } } break; // case SET_PLAYER_X: { // currentPlayer.setX(e.getIntValue()); // } break; // case SET_PLAYER_Y: { // currentPlayer.setY(e.getIntValue()); // } break; } }
diff --git a/src/main/java/syndeticlogic/catena/store/PageFactory.java b/src/main/java/syndeticlogic/catena/store/PageFactory.java index 96b96ac..46c7538 100644 --- a/src/main/java/syndeticlogic/catena/store/PageFactory.java +++ b/src/main/java/syndeticlogic/catena/store/PageFactory.java @@ -1,157 +1,154 @@ package syndeticlogic.catena.store; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.io.File; import java.io.FileInputStream; import java.nio.ByteBuffer; import syndeticlogic.memento.Cache; import syndeticlogic.memento.PinnableListener; import syndeticlogic.memento.PinnableLruStrategy; import syndeticlogic.memento.PolicyCache; import syndeticlogic.memento.PolicyStrategy; import syndeticlogic.catena.utility.ObservationManager; import syndeticlogic.catena.store.PageManager; public class PageFactory { public static enum BufferPoolMemoryType { Native, Java }; public static enum PageDescriptorType { Synchronized, Unsynchronized }; public static enum CachingPolicy { Uncached, Fifo, Lru, Lfu, PinnableLru }; private static volatile PageFactory singleton; public synchronized static void configure(PageFactory factory) { if (singleton == null) { singleton = factory; } } public static PageFactory get() { if (singleton == null) { throw new RuntimeException("PageFactory has not been injected"); } return singleton; } private final BufferPoolMemoryType memoryType; private final CachingPolicy cachePolicy; private final PageDescriptorType pageDescType; private final int retryLimit; public PageFactory(BufferPoolMemoryType bpt, CachingPolicy cst, PageDescriptorType pdt, int retryLimit) { this.memoryType = bpt; this.cachePolicy = cst; this.pageDescType = pdt; this.retryLimit = retryLimit; assert memoryType != null && cachePolicy != null && pageDescType != null && retryLimit > 0; } public Page createPageDescriptor() { Page pagedes = null; switch (pageDescType) { case Unsynchronized: pagedes = new Page(); break; case Synchronized: assert false; break; default: assert false; } return pagedes; } public PageManager createPageManager(List<String> files, int pageSize, int numPages) { ConcurrentLinkedQueue<ByteBuffer> freelist = new ConcurrentLinkedQueue<ByteBuffer>(); HashMap<String, List<Page>> pageSequences = new HashMap<String, List<Page>>(); for (int i = 0; i < numPages; i++) { switch (memoryType) { case Native: freelist.add(ByteBuffer.allocateDirect(pageSize)); break; case Java: freelist.add(ByteBuffer.allocate(pageSize)); break; default: assert false; } } try { if (files != null) { assert false; for (String file : files) { FileInputStream fileIn = new FileInputStream(new File(file)); long size = fileIn.getChannel().size(); assert (size / pageSize + 1) > 0 && (size / pageSize + 1) < Integer.MAX_VALUE; int pages = (int) (size / pageSize + 1); - List<Page> pageSequence = new ArrayList<Page>( - pages); - long offset = 0; + List<Page> pageSequence = new ArrayList<Page>(pages); for (int i = 0; i < pages; i++) { pageSequence.add(createPageDescriptor()); - offset += pageSize; } pageSequences.put(file, pageSequence); } } } catch (Exception e) { throw new RuntimeException(e); } ObservationManager observer = new ObservationManager(null); PageManager pageManager = new PageManager(this, observer, pageSequences, freelist, pageSize, retryLimit); if(this.cachePolicy != CachingPolicy.Uncached) { long cacheTimeoutMillis = 999999999999L; PolicyStrategy policyStrategy = createPolicyStrategy(numPages, cacheTimeoutMillis); assert policyStrategy instanceof PinnableListener; Cache policyCache = createCache(policyStrategy, "page-cache"); PageCache pageCache = new PageCache(pageManager, policyCache, (PinnableListener)policyStrategy); observer.register(pageCache); policyStrategy.setEvictionListener(pageCache); } return pageManager; } public Cache createCache(PolicyStrategy ps, String string) { return new PolicyCache(ps, "page-cache"); } public PolicyStrategy createPolicyStrategy(int size, long timeoutMillis) { PolicyStrategy ps = null; switch (cachePolicy) { case Fifo: case Lru: case Lfu: assert false; break; case PinnableLru: ps = new PinnableLruStrategy(null, size, timeoutMillis); } return ps; } }
false
true
public PageManager createPageManager(List<String> files, int pageSize, int numPages) { ConcurrentLinkedQueue<ByteBuffer> freelist = new ConcurrentLinkedQueue<ByteBuffer>(); HashMap<String, List<Page>> pageSequences = new HashMap<String, List<Page>>(); for (int i = 0; i < numPages; i++) { switch (memoryType) { case Native: freelist.add(ByteBuffer.allocateDirect(pageSize)); break; case Java: freelist.add(ByteBuffer.allocate(pageSize)); break; default: assert false; } } try { if (files != null) { assert false; for (String file : files) { FileInputStream fileIn = new FileInputStream(new File(file)); long size = fileIn.getChannel().size(); assert (size / pageSize + 1) > 0 && (size / pageSize + 1) < Integer.MAX_VALUE; int pages = (int) (size / pageSize + 1); List<Page> pageSequence = new ArrayList<Page>( pages); long offset = 0; for (int i = 0; i < pages; i++) { pageSequence.add(createPageDescriptor()); offset += pageSize; } pageSequences.put(file, pageSequence); } } } catch (Exception e) { throw new RuntimeException(e); } ObservationManager observer = new ObservationManager(null); PageManager pageManager = new PageManager(this, observer, pageSequences, freelist, pageSize, retryLimit); if(this.cachePolicy != CachingPolicy.Uncached) { long cacheTimeoutMillis = 999999999999L; PolicyStrategy policyStrategy = createPolicyStrategy(numPages, cacheTimeoutMillis); assert policyStrategy instanceof PinnableListener; Cache policyCache = createCache(policyStrategy, "page-cache"); PageCache pageCache = new PageCache(pageManager, policyCache, (PinnableListener)policyStrategy); observer.register(pageCache); policyStrategy.setEvictionListener(pageCache); } return pageManager; }
public PageManager createPageManager(List<String> files, int pageSize, int numPages) { ConcurrentLinkedQueue<ByteBuffer> freelist = new ConcurrentLinkedQueue<ByteBuffer>(); HashMap<String, List<Page>> pageSequences = new HashMap<String, List<Page>>(); for (int i = 0; i < numPages; i++) { switch (memoryType) { case Native: freelist.add(ByteBuffer.allocateDirect(pageSize)); break; case Java: freelist.add(ByteBuffer.allocate(pageSize)); break; default: assert false; } } try { if (files != null) { assert false; for (String file : files) { FileInputStream fileIn = new FileInputStream(new File(file)); long size = fileIn.getChannel().size(); assert (size / pageSize + 1) > 0 && (size / pageSize + 1) < Integer.MAX_VALUE; int pages = (int) (size / pageSize + 1); List<Page> pageSequence = new ArrayList<Page>(pages); for (int i = 0; i < pages; i++) { pageSequence.add(createPageDescriptor()); } pageSequences.put(file, pageSequence); } } } catch (Exception e) { throw new RuntimeException(e); } ObservationManager observer = new ObservationManager(null); PageManager pageManager = new PageManager(this, observer, pageSequences, freelist, pageSize, retryLimit); if(this.cachePolicy != CachingPolicy.Uncached) { long cacheTimeoutMillis = 999999999999L; PolicyStrategy policyStrategy = createPolicyStrategy(numPages, cacheTimeoutMillis); assert policyStrategy instanceof PinnableListener; Cache policyCache = createCache(policyStrategy, "page-cache"); PageCache pageCache = new PageCache(pageManager, policyCache, (PinnableListener)policyStrategy); observer.register(pageCache); policyStrategy.setEvictionListener(pageCache); } return pageManager; }
diff --git a/src/net/milkbowl/vault/chat/plugins/Chat_iChat.java b/src/net/milkbowl/vault/chat/plugins/Chat_iChat.java index cd01a2f..ea917c4 100644 --- a/src/net/milkbowl/vault/chat/plugins/Chat_iChat.java +++ b/src/net/milkbowl/vault/chat/plugins/Chat_iChat.java @@ -1,253 +1,253 @@ package net.milkbowl.vault.chat.plugins; import java.util.logging.Logger; import org.bukkit.entity.Player; import org.bukkit.event.Event.Priority; import org.bukkit.event.Event.Type; import org.bukkit.event.server.PluginDisableEvent; import org.bukkit.event.server.PluginEnableEvent; import org.bukkit.event.server.ServerListener; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import net.TheDgtl.iChat.iChatAPI; import net.TheDgtl.iChat.iChat; import net.milkbowl.vault.chat.Chat; import net.milkbowl.vault.permission.Permission; public class Chat_iChat extends Chat { private static final Logger log = Logger.getLogger("Minecraft"); private final String name = "iChat"; private Plugin plugin = null; private PluginManager pluginManager = null; private iChatAPI iChat = null; private PermissionServerListener permissionServerListener = null; public Chat_iChat(Plugin plugin, Permission perms) { super(perms); this.plugin = plugin; pluginManager = this.plugin.getServer().getPluginManager(); permissionServerListener = new PermissionServerListener(this); this.pluginManager.registerEvent(Type.PLUGIN_ENABLE, permissionServerListener, Priority.Monitor, plugin); this.pluginManager.registerEvent(Type.PLUGIN_DISABLE, permissionServerListener, Priority.Monitor, plugin); // Load Plugin in case it was loaded before if (iChat == null) { - Plugin chat = plugin.getServer().getPluginManager().getPlugin("mChat"); + Plugin chat = plugin.getServer().getPluginManager().getPlugin("iChat"); if (chat != null) { iChat = ((iChat) plugin).API; - log.info(String.format("[%s][Chat] %s hooked.", plugin.getDescription().getName(), "mChat")); + log.info(String.format("[%s][Chat] %s hooked.", plugin.getDescription().getName(), "iChat")); } } } private class PermissionServerListener extends ServerListener { Chat_iChat chat = null; public PermissionServerListener(Chat_iChat chat) { this.chat = chat; } public void onPluginEnable(PluginEnableEvent event) { if (this.chat.iChat == null) { Plugin chat = plugin.getServer().getPluginManager().getPlugin("iChat"); if (chat != null) { this.chat.iChat = ((iChat) plugin).API; log.info(String.format("[%s][Chat] %s hooked.", plugin.getDescription().getName(), "iChat")); } } } public void onPluginDisable(PluginDisableEvent event) { if (this.chat.iChat != null) { if (event.getPlugin().getDescription().getName().equals("iChat")) { this.chat.iChat = null; log.info(String.format("[%s][Chat] %s un-hooked.", plugin.getDescription().getName(), "iChat")); } } } } @Override public String getName() { return name; } @Override public boolean isEnabled() { return iChat != null; } @Override public String getPlayerPrefix(String world, String player) { Player p = plugin.getServer().getPlayer(player); if (p == null) throw new UnsupportedOperationException("iChat does not support offline player info nodes!"); if (!p.getWorld().getName().equals(world)) return null; return iChat.getPrefix(p); } @Override public void setPlayerPrefix(String world, String player, String prefix) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public String getPlayerSuffix(String world, String player) { Player p = plugin.getServer().getPlayer(player); if (p == null) throw new UnsupportedOperationException("iChat does not support offline player info nodes!"); if (!p.getWorld().getName().equals(world)) return null; return iChat.getSuffix(p); } @Override public void setPlayerSuffix(String world, String player, String suffix) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public String getGroupPrefix(String world, String group) { throw new UnsupportedOperationException("iChat does not support group info nodes!"); } @Override public void setGroupPrefix(String world, String group, String prefix) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public String getGroupSuffix(String world, String group) { throw new UnsupportedOperationException("iChat does not support group info nodes!"); } @Override public void setGroupSuffix(String world, String group, String suffix) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public int getPlayerInfoInteger(String world, String player, String node, int defaultValue) { String val = getPlayerInfoString(world, player, node, null); if (val == null) return defaultValue; Integer i = defaultValue; try { i = Integer.valueOf(val); return i; } catch (NumberFormatException e) { return defaultValue; } } @Override public void setPlayerInfoInteger(String world, String player, String node, int value) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public int getGroupInfoInteger(String world, String group, String node, int defaultValue) { throw new UnsupportedOperationException("iChat does not support group info nodes!"); } @Override public void setGroupInfoInteger(String world, String group, String node, int value) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public double getPlayerInfoDouble(String world, String player, String node, double defaultValue) { String val = getPlayerInfoString(world, player, node, null); if (val == null) return defaultValue; double d = defaultValue; try { d = Double.valueOf(val); return d; } catch (NumberFormatException e) { return defaultValue; } } @Override public void setPlayerInfoDouble(String world, String player, String node, double value) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public double getGroupInfoDouble(String world, String group, String node, double defaultValue) { throw new UnsupportedOperationException("iChat does not support group info nodes!"); } @Override public void setGroupInfoDouble(String world, String group, String node, double value) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public boolean getPlayerInfoBoolean(String world, String player, String node, boolean defaultValue) { String val = getPlayerInfoString(world, player, node, null); if (val == null) return defaultValue; return Boolean.valueOf(val); } @Override public void setPlayerInfoBoolean(String world, String player, String node, boolean value) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public boolean getGroupInfoBoolean(String world, String group, String node, boolean defaultValue) { // TODO Auto-generated method stub return false; } @Override public void setGroupInfoBoolean(String world, String group, String node, boolean value) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public String getPlayerInfoString(String world, String player, String node, String defaultValue) { Player p = plugin.getServer().getPlayer(player); if (p == null) throw new UnsupportedOperationException("iChat does not support offline player info nodes!"); if (!p.getWorld().getName().equals(world)) return null; String val = iChat.getInfo(p, node); return val != null ? val : defaultValue; } @Override public void setPlayerInfoString(String world, String player, String node, String value) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } @Override public String getGroupInfoString(String world, String group, String node, String defaultValue) { throw new UnsupportedOperationException("iChat does not support group info nodes!"); } @Override public void setGroupInfoString(String world, String group, String node, String value) { throw new UnsupportedOperationException("iChat does not support mutable info nodes!"); } }
false
true
public Chat_iChat(Plugin plugin, Permission perms) { super(perms); this.plugin = plugin; pluginManager = this.plugin.getServer().getPluginManager(); permissionServerListener = new PermissionServerListener(this); this.pluginManager.registerEvent(Type.PLUGIN_ENABLE, permissionServerListener, Priority.Monitor, plugin); this.pluginManager.registerEvent(Type.PLUGIN_DISABLE, permissionServerListener, Priority.Monitor, plugin); // Load Plugin in case it was loaded before if (iChat == null) { Plugin chat = plugin.getServer().getPluginManager().getPlugin("mChat"); if (chat != null) { iChat = ((iChat) plugin).API; log.info(String.format("[%s][Chat] %s hooked.", plugin.getDescription().getName(), "mChat")); } } }
public Chat_iChat(Plugin plugin, Permission perms) { super(perms); this.plugin = plugin; pluginManager = this.plugin.getServer().getPluginManager(); permissionServerListener = new PermissionServerListener(this); this.pluginManager.registerEvent(Type.PLUGIN_ENABLE, permissionServerListener, Priority.Monitor, plugin); this.pluginManager.registerEvent(Type.PLUGIN_DISABLE, permissionServerListener, Priority.Monitor, plugin); // Load Plugin in case it was loaded before if (iChat == null) { Plugin chat = plugin.getServer().getPluginManager().getPlugin("iChat"); if (chat != null) { iChat = ((iChat) plugin).API; log.info(String.format("[%s][Chat] %s hooked.", plugin.getDescription().getName(), "iChat")); } } }
diff --git a/everest-ipojo/src/main/java/org/apache/felix/ipojo/everest/ipojo/ServiceDependencyResource.java b/everest-ipojo/src/main/java/org/apache/felix/ipojo/everest/ipojo/ServiceDependencyResource.java index 14a1c88..a157413 100644 --- a/everest-ipojo/src/main/java/org/apache/felix/ipojo/everest/ipojo/ServiceDependencyResource.java +++ b/everest-ipojo/src/main/java/org/apache/felix/ipojo/everest/ipojo/ServiceDependencyResource.java @@ -1,211 +1,213 @@ package org.apache.felix.ipojo.everest.ipojo; import org.apache.felix.ipojo.everest.core.Everest; import org.apache.felix.ipojo.everest.impl.DefaultReadOnlyResource; import org.apache.felix.ipojo.everest.impl.DefaultRelation; import org.apache.felix.ipojo.everest.impl.ImmutableResourceMetadata; import org.apache.felix.ipojo.everest.services.*; import org.apache.felix.ipojo.handlers.dependency.Dependency; import org.apache.felix.ipojo.handlers.dependency.DependencyDescription; import org.apache.felix.ipojo.util.DependencyModel; import org.apache.felix.ipojo.util.DependencyModelListener; import org.osgi.framework.Constants; import org.osgi.framework.ServiceReference; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import static org.apache.felix.ipojo.everest.ipojo.IpojoRootResource.PATH_TO_OSGI_SERVICES; import static org.apache.felix.ipojo.util.DependencyModel.*; /** * '/ipojo/instance/$name/dependency/$id' resource. */ public class ServiceDependencyResource extends DefaultReadOnlyResource implements DependencyModelListener { private WeakReference<DependencyDescription> m_description; public ServiceDependencyResource(InstanceResource instance, DependencyDescription description) { super(instance.getDependencies().getPath().addElements(description.getId()), new ImmutableResourceMetadata.Builder() .set("id", description.getId()) .set("specification", description.getSpecification()) // May become mutable is future iPOJO releases? .set("isNullable", description.supportsNullable()) .set("isProxy", description.isProxy()) .set("defaultImplementation", description.getDefaultImplementation()) // All other attributes are considered dynamic .build()); m_description = new WeakReference<DependencyDescription>(description); description.addListener(this); } @Override public ResourceMetadata getMetadata() { ResourceMetadata m = super.getMetadata(); DependencyDescription d = m_description.get(); if (d == null) { return m; } else { return new ImmutableResourceMetadata.Builder() .set("state", stateToString(d.getState())) .set("filter", d.getFilter()) .set("policy", policyToString(d.getPolicy())) .set("comparator", d.getComparator()) .set("isAggregate", d.isMultiple()) .set("isOptional", d.isOptional()) .set("isFrozen", d.isFrozen()) .build(); } } @Override public List<Relation> getRelations() { List<Relation> r = super.getRelations(); DependencyDescription d = m_description.get(); if (d == null) { return r; } else { r = new ArrayList<Relation>(r); @SuppressWarnings("unchecked") List<ServiceReference> matching = d.getServiceReferences(); if (matching != null) { for(ServiceReference<?> s : matching) { String id = String.valueOf(s.getProperty(Constants.SERVICE_ID)); r.add(new DefaultRelation( PATH_TO_OSGI_SERVICES.addElements(id), Action.READ, String.format("matchingService[%s]", id), String.format("Matching service with id '%s'", id))); } } @SuppressWarnings("unchecked") List<ServiceReference> used = d.getUsedServices(); - for(ServiceReference<?> s : used) { - String id = String.valueOf(s.getProperty(Constants.SERVICE_ID)); - r.add(new DefaultRelation( - PATH_TO_OSGI_SERVICES.addElements(id), - Action.READ, - String.format("usedService[%s]", id), - String.format("Used service with id '%s'", id))); + if (used != null) { + for(ServiceReference<?> s : used) { + String id = String.valueOf(s.getProperty(Constants.SERVICE_ID)); + r.add(new DefaultRelation( + PATH_TO_OSGI_SERVICES.addElements(id), + Action.READ, + String.format("usedService[%s]", id), + String.format("Used service with id '%s'", id))); + } } return Collections.unmodifiableList(r); } } @Override public boolean isObservable() { return true; } @Override public <A> A adaptTo(Class<A> clazz) { if (clazz == DependencyModel.class) { return clazz.cast(getDependency(m_description.get())); } else if (clazz == DependencyDescription.class) { return clazz.cast(m_description.get()); } else { return super.adaptTo(clazz); } } public void validate(DependencyModel dependency) { // Fire UPDATED event Everest.postResource(ResourceEvent.UPDATED, this); } public void invalidate(DependencyModel dependency) { // Fire UPDATED event Everest.postResource(ResourceEvent.UPDATED, this); } private static String policyToString(int policy) { switch (policy) { case DYNAMIC_BINDING_POLICY: return "DYNAMIC_BINDING"; case STATIC_BINDING_POLICY: return "STATIC_BINDING"; case DYNAMIC_PRIORITY_BINDING_POLICY: return "DYNAMIC_PRIORITY_BINDING"; default: return "CUSTOMIZED"; // Optimistic! } } private static String stateToString(int state) { switch (state) { case BROKEN: return "BROKEN"; case UNRESOLVED: return "UNRESOLVED"; case RESOLVED: return "RESOLVED"; default: return "unknown"; } } // WARN: This is a hack! private static Dependency getDependency(DependencyDescription description) { if (description == null) { return null; } Field shunt = null; try { shunt = DependencyDescription.class.getDeclaredField("m_dependency"); shunt.setAccessible(true); return (Dependency) shunt.get(description); } catch (Exception e) { throw new IllegalStateException("cannot get service dependency", e); } finally { if (shunt != null) { shunt.setAccessible(false); } } } public void matchingServiceArrived(DependencyModel dependency, ServiceReference<?> service) { // Fire UPDATED event Everest.postResource(ResourceEvent.UPDATED, this); } public void matchingServiceModified(DependencyModel dependency, ServiceReference<?> service) { // Fire UPDATED event Everest.postResource(ResourceEvent.UPDATED, this); } public void matchingServiceDeparted(DependencyModel dependency, ServiceReference<?> service) { // Fire UPDATED event Everest.postResource(ResourceEvent.UPDATED, this); } public void serviceBound(DependencyModel dependency, ServiceReference<?> service, Object object) { // Fire UPDATED event Everest.postResource(ResourceEvent.UPDATED, this); } public void serviceUnbound(DependencyModel dependency, ServiceReference<?> service, Object object) { // Fire UPDATED event Everest.postResource(ResourceEvent.UPDATED, this); } public void reconfigured(DependencyModel dependency) { // Fire UPDATED event Everest.postResource(ResourceEvent.UPDATED, this); } public void cleanup() { // Remove the listener DependencyDescription d = m_description.get(); if (d != null) { try { d.removeListener(this); } catch (NoSuchElementException e) { // Swallow } } } }
true
true
public List<Relation> getRelations() { List<Relation> r = super.getRelations(); DependencyDescription d = m_description.get(); if (d == null) { return r; } else { r = new ArrayList<Relation>(r); @SuppressWarnings("unchecked") List<ServiceReference> matching = d.getServiceReferences(); if (matching != null) { for(ServiceReference<?> s : matching) { String id = String.valueOf(s.getProperty(Constants.SERVICE_ID)); r.add(new DefaultRelation( PATH_TO_OSGI_SERVICES.addElements(id), Action.READ, String.format("matchingService[%s]", id), String.format("Matching service with id '%s'", id))); } } @SuppressWarnings("unchecked") List<ServiceReference> used = d.getUsedServices(); for(ServiceReference<?> s : used) { String id = String.valueOf(s.getProperty(Constants.SERVICE_ID)); r.add(new DefaultRelation( PATH_TO_OSGI_SERVICES.addElements(id), Action.READ, String.format("usedService[%s]", id), String.format("Used service with id '%s'", id))); } return Collections.unmodifiableList(r); } }
public List<Relation> getRelations() { List<Relation> r = super.getRelations(); DependencyDescription d = m_description.get(); if (d == null) { return r; } else { r = new ArrayList<Relation>(r); @SuppressWarnings("unchecked") List<ServiceReference> matching = d.getServiceReferences(); if (matching != null) { for(ServiceReference<?> s : matching) { String id = String.valueOf(s.getProperty(Constants.SERVICE_ID)); r.add(new DefaultRelation( PATH_TO_OSGI_SERVICES.addElements(id), Action.READ, String.format("matchingService[%s]", id), String.format("Matching service with id '%s'", id))); } } @SuppressWarnings("unchecked") List<ServiceReference> used = d.getUsedServices(); if (used != null) { for(ServiceReference<?> s : used) { String id = String.valueOf(s.getProperty(Constants.SERVICE_ID)); r.add(new DefaultRelation( PATH_TO_OSGI_SERVICES.addElements(id), Action.READ, String.format("usedService[%s]", id), String.format("Used service with id '%s'", id))); } } return Collections.unmodifiableList(r); } }
diff --git a/modules/rampart-policy/src/main/java/org/apache/ws/secpolicy/model/SecureConversationToken.java b/modules/rampart-policy/src/main/java/org/apache/ws/secpolicy/model/SecureConversationToken.java index c0d58f503..54f1b24c7 100644 --- a/modules/rampart-policy/src/main/java/org/apache/ws/secpolicy/model/SecureConversationToken.java +++ b/modules/rampart-policy/src/main/java/org/apache/ws/secpolicy/model/SecureConversationToken.java @@ -1,186 +1,185 @@ /* * Copyright 2004,2005 The Apache Software 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.apache.ws.secpolicy.model; import org.apache.axiom.om.OMElement; import org.apache.neethi.Policy; import org.apache.ws.secpolicy.SP11Constants; import org.apache.ws.secpolicy.SP12Constants; import org.apache.ws.secpolicy.SPConstants; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; /** * Model class of SecureConversationToken assertion */ public class SecureConversationToken extends SecurityContextToken { private Policy bootstrapPolicy; private OMElement issuerEpr; public SecureConversationToken(int version) { super(version); } /** * @return Returns the bootstrapPolicy. */ public Policy getBootstrapPolicy() { return bootstrapPolicy; } /** * @param bootstrapPolicy * The bootstrapPolicy to set. */ public void setBootstrapPolicy(Policy bootstrapPolicy) { this.bootstrapPolicy = bootstrapPolicy; } /* * (non-Javadoc) * * @see org.apache.neethi.Assertion#getName() */ public QName getName() { if ( version == SPConstants.SP_V12) { return SP12Constants.SECURE_CONVERSATION_TOKEN; } else { return SP11Constants.SECURE_CONVERSATION_TOKEN; } } public void serialize(XMLStreamWriter writer) throws XMLStreamException { String localname = getName().getLocalPart(); String namespaceURI = getName().getNamespaceURI(); String prefix; String writerPrefix = writer.getPrefix(namespaceURI); if (writerPrefix == null) { prefix = getName().getPrefix(); writer.setPrefix(prefix, namespaceURI); } else { prefix = writerPrefix; } // <sp:SecureConversationToken> writer.writeStartElement(prefix, localname, namespaceURI); if (writerPrefix == null) { // xmlns:sp=".." writer.writeNamespace(prefix, namespaceURI); } String inclusion; if (version == SPConstants.SP_V12) { inclusion = SP12Constants.getAttributeValueFromInclusion(getInclusion()); } else { inclusion = SP11Constants.getAttributeValueFromInclusion(getInclusion()); } if (inclusion != null) { - writer.writeAttribute(prefix, namespaceURI, SPConstants.ATTR_INCLUDE_TOKEN, - namespaceURI + inclusion); + writer.writeAttribute(prefix, namespaceURI, SPConstants.ATTR_INCLUDE_TOKEN, inclusion); } if (issuerEpr != null) { // <sp:Issuer> writer.writeStartElement(prefix, SPConstants.ISSUER , namespaceURI); issuerEpr.serialize(writer); writer.writeEndElement(); } if (isDerivedKeys() || isRequireExternalUriRef() || isSc10SecurityContextToken() || (bootstrapPolicy != null)) { String wspNamespaceURI = SPConstants.POLICY.getNamespaceURI(); String wspPrefix; String wspWriterPrefix = writer.getPrefix(wspNamespaceURI); if (wspWriterPrefix == null) { wspPrefix = SPConstants.POLICY.getPrefix(); writer.setPrefix(wspPrefix, wspNamespaceURI); } else { wspPrefix = wspWriterPrefix; } // <wsp:Policy> writer.writeStartElement(wspPrefix, SPConstants.POLICY.getLocalPart(), wspNamespaceURI); if (wspWriterPrefix == null) { // xmlns:wsp=".." writer.writeNamespace(wspPrefix, wspNamespaceURI); } if (isDerivedKeys()) { // <sp:RequireDerivedKeys /> writer.writeEmptyElement(prefix, SPConstants.REQUIRE_DERIVED_KEYS, namespaceURI); } if (isRequireExternalUriRef()) { // <sp:RequireExternalUriReference /> writer.writeEmptyElement(prefix, SPConstants.REQUIRE_EXTERNAL_URI_REFERNCE, namespaceURI); } if (isSc10SecurityContextToken()) { // <sp:SC10SecurityContextToken /> writer.writeEmptyElement(prefix, SPConstants.SC10_SECURITY_CONTEXT_TOKEN, namespaceURI); } if (bootstrapPolicy != null) { // <sp:BootstrapPolicy ..> writer.writeStartElement(prefix, SPConstants.BOOTSTRAP_POLICY, namespaceURI); bootstrapPolicy.serialize(writer); writer.writeEndElement(); } // </wsp:Policy> writer.writeEndElement(); } // </sp:SecureConversationToken> writer.writeEndElement(); } /** * @return Returns the issuerEpr. */ public OMElement getIssuerEpr() { return issuerEpr; } /** * @param issuerEpr * The issuerEpr to set. */ public void setIssuerEpr(OMElement issuerEpr) { this.issuerEpr = issuerEpr; } }
true
true
public void serialize(XMLStreamWriter writer) throws XMLStreamException { String localname = getName().getLocalPart(); String namespaceURI = getName().getNamespaceURI(); String prefix; String writerPrefix = writer.getPrefix(namespaceURI); if (writerPrefix == null) { prefix = getName().getPrefix(); writer.setPrefix(prefix, namespaceURI); } else { prefix = writerPrefix; } // <sp:SecureConversationToken> writer.writeStartElement(prefix, localname, namespaceURI); if (writerPrefix == null) { // xmlns:sp=".." writer.writeNamespace(prefix, namespaceURI); } String inclusion; if (version == SPConstants.SP_V12) { inclusion = SP12Constants.getAttributeValueFromInclusion(getInclusion()); } else { inclusion = SP11Constants.getAttributeValueFromInclusion(getInclusion()); } if (inclusion != null) { writer.writeAttribute(prefix, namespaceURI, SPConstants.ATTR_INCLUDE_TOKEN, namespaceURI + inclusion); } if (issuerEpr != null) { // <sp:Issuer> writer.writeStartElement(prefix, SPConstants.ISSUER , namespaceURI); issuerEpr.serialize(writer); writer.writeEndElement(); } if (isDerivedKeys() || isRequireExternalUriRef() || isSc10SecurityContextToken() || (bootstrapPolicy != null)) { String wspNamespaceURI = SPConstants.POLICY.getNamespaceURI(); String wspPrefix; String wspWriterPrefix = writer.getPrefix(wspNamespaceURI); if (wspWriterPrefix == null) { wspPrefix = SPConstants.POLICY.getPrefix(); writer.setPrefix(wspPrefix, wspNamespaceURI); } else { wspPrefix = wspWriterPrefix; } // <wsp:Policy> writer.writeStartElement(wspPrefix, SPConstants.POLICY.getLocalPart(), wspNamespaceURI); if (wspWriterPrefix == null) { // xmlns:wsp=".." writer.writeNamespace(wspPrefix, wspNamespaceURI); } if (isDerivedKeys()) { // <sp:RequireDerivedKeys /> writer.writeEmptyElement(prefix, SPConstants.REQUIRE_DERIVED_KEYS, namespaceURI); } if (isRequireExternalUriRef()) { // <sp:RequireExternalUriReference /> writer.writeEmptyElement(prefix, SPConstants.REQUIRE_EXTERNAL_URI_REFERNCE, namespaceURI); } if (isSc10SecurityContextToken()) { // <sp:SC10SecurityContextToken /> writer.writeEmptyElement(prefix, SPConstants.SC10_SECURITY_CONTEXT_TOKEN, namespaceURI); } if (bootstrapPolicy != null) { // <sp:BootstrapPolicy ..> writer.writeStartElement(prefix, SPConstants.BOOTSTRAP_POLICY, namespaceURI); bootstrapPolicy.serialize(writer); writer.writeEndElement(); } // </wsp:Policy> writer.writeEndElement(); } // </sp:SecureConversationToken> writer.writeEndElement(); }
public void serialize(XMLStreamWriter writer) throws XMLStreamException { String localname = getName().getLocalPart(); String namespaceURI = getName().getNamespaceURI(); String prefix; String writerPrefix = writer.getPrefix(namespaceURI); if (writerPrefix == null) { prefix = getName().getPrefix(); writer.setPrefix(prefix, namespaceURI); } else { prefix = writerPrefix; } // <sp:SecureConversationToken> writer.writeStartElement(prefix, localname, namespaceURI); if (writerPrefix == null) { // xmlns:sp=".." writer.writeNamespace(prefix, namespaceURI); } String inclusion; if (version == SPConstants.SP_V12) { inclusion = SP12Constants.getAttributeValueFromInclusion(getInclusion()); } else { inclusion = SP11Constants.getAttributeValueFromInclusion(getInclusion()); } if (inclusion != null) { writer.writeAttribute(prefix, namespaceURI, SPConstants.ATTR_INCLUDE_TOKEN, inclusion); } if (issuerEpr != null) { // <sp:Issuer> writer.writeStartElement(prefix, SPConstants.ISSUER , namespaceURI); issuerEpr.serialize(writer); writer.writeEndElement(); } if (isDerivedKeys() || isRequireExternalUriRef() || isSc10SecurityContextToken() || (bootstrapPolicy != null)) { String wspNamespaceURI = SPConstants.POLICY.getNamespaceURI(); String wspPrefix; String wspWriterPrefix = writer.getPrefix(wspNamespaceURI); if (wspWriterPrefix == null) { wspPrefix = SPConstants.POLICY.getPrefix(); writer.setPrefix(wspPrefix, wspNamespaceURI); } else { wspPrefix = wspWriterPrefix; } // <wsp:Policy> writer.writeStartElement(wspPrefix, SPConstants.POLICY.getLocalPart(), wspNamespaceURI); if (wspWriterPrefix == null) { // xmlns:wsp=".." writer.writeNamespace(wspPrefix, wspNamespaceURI); } if (isDerivedKeys()) { // <sp:RequireDerivedKeys /> writer.writeEmptyElement(prefix, SPConstants.REQUIRE_DERIVED_KEYS, namespaceURI); } if (isRequireExternalUriRef()) { // <sp:RequireExternalUriReference /> writer.writeEmptyElement(prefix, SPConstants.REQUIRE_EXTERNAL_URI_REFERNCE, namespaceURI); } if (isSc10SecurityContextToken()) { // <sp:SC10SecurityContextToken /> writer.writeEmptyElement(prefix, SPConstants.SC10_SECURITY_CONTEXT_TOKEN, namespaceURI); } if (bootstrapPolicy != null) { // <sp:BootstrapPolicy ..> writer.writeStartElement(prefix, SPConstants.BOOTSTRAP_POLICY, namespaceURI); bootstrapPolicy.serialize(writer); writer.writeEndElement(); } // </wsp:Policy> writer.writeEndElement(); } // </sp:SecureConversationToken> writer.writeEndElement(); }
diff --git a/modules/resin/src/com/caucho/admin/action/PdfReportAction.java b/modules/resin/src/com/caucho/admin/action/PdfReportAction.java index bb666d220..b000a25dc 100644 --- a/modules/resin/src/com/caucho/admin/action/PdfReportAction.java +++ b/modules/resin/src/com/caucho/admin/action/PdfReportAction.java @@ -1,377 +1,378 @@ /* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * @author Scott Ferguson */ package com.caucho.admin.action; import java.io.IOException; import java.util.logging.Logger; import javax.mail.internet.InternetAddress; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.caucho.config.ConfigException; import com.caucho.hemp.services.MailService; import com.caucho.quercus.QuercusContext; import com.caucho.quercus.env.Env; import com.caucho.quercus.env.Value; import com.caucho.quercus.page.QuercusPage; import com.caucho.server.http.StubServletRequest; import com.caucho.server.http.StubServletResponse; import com.caucho.server.resin.Resin; import com.caucho.util.Alarm; import com.caucho.util.IoUtil; import com.caucho.util.L10N; import com.caucho.util.QDate; import com.caucho.vfs.Path; import com.caucho.vfs.TempStream; import com.caucho.vfs.Vfs; import com.caucho.vfs.WriteStream; public class PdfReportAction implements AdminAction { private static final L10N L = new L10N(PdfReportAction.class); private static final long HOUR = 3600 * 1000L; private static final long DAY = 24 * 3600 * 1000L; private String _serverId; private String _logDirectory; private String _path; private long _period; private String _report; private String _title; private MailService _mailService = new MailService(); private String _mailTo; private String _mailFrom; private boolean _isSnapshot; private long _profileTime; private long _profileTick; private boolean _isWatchdog; private QuercusContext _quercus; private Path _phpPath; private Path _logPath; public String getPath() { return _path; } public void setPath(String path) { _path = path; } public String getReport() { return _report; } public void setReport(String report) { _report = report; } public String getTitle() { return _title; } public void setTitle(String title) { _title = title; } public long getPeriod() { return _period; } public void setPeriod(long period) { _period = period; } public boolean isSnapshot() { return _isSnapshot; } public void setSnapshot(boolean isSnapshot) { _isSnapshot = isSnapshot; } public void setWatchdog(boolean isWatchdog) { _isWatchdog = isWatchdog; } public boolean isWatchdog() { return _isWatchdog; } public long getProfileTime() { return _profileTime; } public void setProfileTime(long profileTime) { _profileTime = profileTime; } public long getProfileTick() { return _profileTick; } public void setProfileTick(long profileTick) { _profileTick = profileTick; } public String getLogDirectory() { return _logDirectory; } public void setLogDirectory(String logDirectory) { _logDirectory = logDirectory; } public void setMailTo(String mailTo) { if (! "".equals(mailTo)) _mailTo = mailTo; } public void setMailFrom(String mailFrom) { if (! "".equals(mailFrom)) _mailFrom = mailFrom; } private String calculateReport() { if (_report != null) return _report; else if (isWatchdog()) return "Watchdog"; else return "Snapshot"; } private String calculateTitle() { if (_title != null) return _title; else return calculateReport(); } private long calculatePeriod() { if (_period != 0) return _period; else if (isWatchdog()) return 2 * HOUR; else return DAY; } public void init() { Resin resin = Resin.getCurrent(); if (resin != null) { _serverId = resin.getServerId(); if (_logDirectory == null) _logPath = resin.getLogDirectory(); } else { _serverId = "unknown"; if (_logDirectory == null) _logPath = Vfs.getPwd(); } // If Resin is running then path is optional and should default // to ${resin.home}/doc/admin/pdf-gen.php // // If Resin is not running, then path is required if (_path != null) { _phpPath = Vfs.lookup(_path); } else if (resin != null) { if (_path == null) { Path path = resin.getRootDirectory().lookup("doc/admin/pdf-gen.php"); if (path.canRead()) { _path = path.getNativePath(); } } if (_path == null) { Path path = resin.getResinHome().lookup("doc/admin/pdf-gen.php"); if (path.canRead()) { _path = path.getNativePath(); } } - _phpPath = Vfs.lookup(_path); + if (_path != null) + _phpPath = Vfs.lookup(_path); } if (_phpPath == null) { throw new ConfigException(L.l("{0} requires a path to a PDF generating .php file", getClass().getSimpleName())); } if (_logPath == null) _logPath = Vfs.lookup(_logDirectory); _quercus = new QuercusContext(); _quercus.setPwd(_phpPath.getParent()); _quercus.init(); _quercus.start(); if (_mailTo != null) { try { _mailService.addTo(new InternetAddress(_mailTo)); _mailService.init(); } catch (Exception e) { throw ConfigException.create(e); } } if (_mailFrom != null) { try { _mailService.addFrom(new InternetAddress(_mailFrom)); _mailService.init(); } catch (Exception e) { throw ConfigException.create(e); } } } public String execute() throws Exception { Env env = null; try { QuercusPage page = _quercus.parse(_phpPath); TempStream ts = new TempStream(); ts.openWrite(); WriteStream ws = new WriteStream(ts); HttpServletRequest request = new StubServletRequest(); HttpServletResponse response = new StubServletResponse(); env = _quercus.createEnv(page, ws, request, response); //env.setGlobalValue("health_service", env.wrapJava(healthService)); env.setGlobalValue("g_report", env.wrapJava(calculateReport())); env.setGlobalValue("g_title", env.wrapJava(calculateTitle())); env.setGlobalValue("period", env.wrapJava(calculatePeriod() / 1000)); env.setGlobalValue("g_is_snapshot", env.wrapJava(isSnapshot())); env.setGlobalValue("g_is_watchdog", env.wrapJava(isWatchdog())); if (getProfileTime() > 0) { env.setGlobalValue("profile_time", env.wrapJava(getProfileTime() / 1000)); } if (getProfileTick() > 0) { env.setGlobalValue("profile_tick", env.wrapJava(getProfileTick())); } env.start(); Value result = env.executeTop(); ws.close(); if (! result.toString().equals("ok")) { throw new Exception(L.l("generation failed: {0}", result.toString())); } if (_mailTo != null && ! "".equals(_mailTo)) { mailPdf(ts); return(L.l("{0} mailed to {1}", calculateTitle(), _mailTo)); } Path path = writePdfToFile(ts); return(L.l("generated {0}", path)); } finally { if (env != null) env.close(); } } private void mailPdf(TempStream ts) throws IOException { String date = QDate.formatLocal(Alarm.getCurrentTime(), "%Y%m%dT%H%M"); String fileName = String.format("%s-%s-%s.pdf", _serverId, calculateTitle(), date); String userDate = QDate.formatLocal(Alarm.getCurrentTime(), "%Y-%m-%d %H:%M"); String subject = "[Resin] PDF Report: " + calculateTitle() + "@" + _serverId + " " + userDate; StringBuilder text = new StringBuilder(); text.append("Resin generated PDF Report"); text.append("\n"); text.append("\nReport: ").append(calculateReport()); text.append("\nGenerated: ").append(userDate); text.append("\nServer: ").append(_serverId); _mailService.sendWithAttachment(subject, text.toString(), "application/pdf", fileName, ts.openInputStream()); } private Path writePdfToFile(TempStream ts) throws IOException { String date = QDate.formatLocal(Alarm.getCurrentTime(), "%Y%m%dT%H%M"); Path path = _logPath.lookup(String.format("%s-%s-%s.pdf", _serverId, calculateTitle(), date)); path.getParent().mkdirs(); WriteStream os = path.openWrite(); try { ts.writeToStream(os); } finally { IoUtil.close(os); } return path; } }
true
true
public void init() { Resin resin = Resin.getCurrent(); if (resin != null) { _serverId = resin.getServerId(); if (_logDirectory == null) _logPath = resin.getLogDirectory(); } else { _serverId = "unknown"; if (_logDirectory == null) _logPath = Vfs.getPwd(); } // If Resin is running then path is optional and should default // to ${resin.home}/doc/admin/pdf-gen.php // // If Resin is not running, then path is required if (_path != null) { _phpPath = Vfs.lookup(_path); } else if (resin != null) { if (_path == null) { Path path = resin.getRootDirectory().lookup("doc/admin/pdf-gen.php"); if (path.canRead()) { _path = path.getNativePath(); } } if (_path == null) { Path path = resin.getResinHome().lookup("doc/admin/pdf-gen.php"); if (path.canRead()) { _path = path.getNativePath(); } } _phpPath = Vfs.lookup(_path); } if (_phpPath == null) { throw new ConfigException(L.l("{0} requires a path to a PDF generating .php file", getClass().getSimpleName())); } if (_logPath == null) _logPath = Vfs.lookup(_logDirectory); _quercus = new QuercusContext(); _quercus.setPwd(_phpPath.getParent()); _quercus.init(); _quercus.start(); if (_mailTo != null) { try { _mailService.addTo(new InternetAddress(_mailTo)); _mailService.init(); } catch (Exception e) { throw ConfigException.create(e); } } if (_mailFrom != null) { try { _mailService.addFrom(new InternetAddress(_mailFrom)); _mailService.init(); } catch (Exception e) { throw ConfigException.create(e); } } }
public void init() { Resin resin = Resin.getCurrent(); if (resin != null) { _serverId = resin.getServerId(); if (_logDirectory == null) _logPath = resin.getLogDirectory(); } else { _serverId = "unknown"; if (_logDirectory == null) _logPath = Vfs.getPwd(); } // If Resin is running then path is optional and should default // to ${resin.home}/doc/admin/pdf-gen.php // // If Resin is not running, then path is required if (_path != null) { _phpPath = Vfs.lookup(_path); } else if (resin != null) { if (_path == null) { Path path = resin.getRootDirectory().lookup("doc/admin/pdf-gen.php"); if (path.canRead()) { _path = path.getNativePath(); } } if (_path == null) { Path path = resin.getResinHome().lookup("doc/admin/pdf-gen.php"); if (path.canRead()) { _path = path.getNativePath(); } } if (_path != null) _phpPath = Vfs.lookup(_path); } if (_phpPath == null) { throw new ConfigException(L.l("{0} requires a path to a PDF generating .php file", getClass().getSimpleName())); } if (_logPath == null) _logPath = Vfs.lookup(_logDirectory); _quercus = new QuercusContext(); _quercus.setPwd(_phpPath.getParent()); _quercus.init(); _quercus.start(); if (_mailTo != null) { try { _mailService.addTo(new InternetAddress(_mailTo)); _mailService.init(); } catch (Exception e) { throw ConfigException.create(e); } } if (_mailFrom != null) { try { _mailService.addFrom(new InternetAddress(_mailFrom)); _mailService.init(); } catch (Exception e) { throw ConfigException.create(e); } } }
diff --git a/src/com/activehabits/android/mark.java b/src/com/activehabits/android/mark.java index 01826d7..d661433 100644 --- a/src/com/activehabits/android/mark.java +++ b/src/com/activehabits/android/mark.java @@ -1,658 +1,658 @@ package com.activehabits.android; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Set; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.content.res.Resources; import android.database.Cursor; import android.graphics.PorterDuff; import android.graphics.Typeface; import android.location.Location; import android.location.LocationManager; import android.os.Bundle; import android.os.Environment; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Display; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class mark extends Activity implements OnClickListener { private static final String TAG = "ActiveHabits.mark"; // for Log.i(TAG, ...); private static FileWriter writer; private static int paddingValue = 7; // * 10 pixels for calculating button sizes private static int splashed = 0; private View contextMenuItem; // button long pressed for context menu private View textEntryView; // TextEntry to update with default value of contextMenuItem /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // TODO: find onCreate / onResume bug // TODO: default rename field if "Default Action" - set to null } @Override public void onConfigurationChanged(Configuration newConfig) { // TODO: handle keyboard opening and closing events - currently crashes sometimes super.onConfigurationChanged(newConfig); } @Override public void onResume() { super.onResume(); // load default preferences SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); setContentView(R.layout.main); // prepare to add more buttons from myMgrPrefs if they exist Map<String, ?> bar = myMgrPrefs.getAll(); //Log.i(TAG, "mark myMgrPrefs: " + bar.toString()); int len = sizeWithoutPl(myMgrPrefs); // roughly each button height = screen size / 1+len // subtract for padding - use self.paddingValue Display container = ((WindowManager)this.getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); //Log.i(TAG, "mark vars1: " + container.toString() ); //Log.i(TAG, "mark vars2: " + container.getHeight());//(int) container.getHeight() ); Integer buttonHeight; if (len == 0) { buttonHeight = (Integer) ((container.getHeight() - (10*(mark.paddingValue+1) )) / (1)); } else { buttonHeight = (Integer) ((container.getHeight() - (10*(len+mark.paddingValue) )) / (len)); } // set up action0 button Button logEventButton = (Button) findViewById(R.id.log_event_button); logEventButton.setText(myMgrPrefs.getString("action0", getString(R.string.markaction))); logEventButton.setTag("action0"); logEventButton.setMinLines(3); logEventButton.setPadding(10, 10, 10, 10); logEventButton.setTextSize((float)24.0); logEventButton.setTypeface(null, Typeface.BOLD); logEventButton.setOnClickListener((OnClickListener) this); logEventButton.setHeight(buttonHeight); logEventButton.setTextColor(0xFFFFFFFF); // text color logEventButton.getBackground().setColorFilter(0x33FFFFFF, PorterDuff.Mode.MULTIPLY); // background color // use 0xFFFFFFFF for default behavior registerForContextMenu(logEventButton); final CharSequence setTo = logEventButton.getText(); final CharSequence defaultSetTo = getString(R.string.markaction); //Log.i(TAG, "mark splash? " + setTo + ", " + defaultSetTo); if (setTo.equals(defaultSetTo) & (mark.splashed == 0)) { // strange syntax to make it compare mark.splashed = 1; // assume if first action is not changed from default // this is first run or help is needed so show splash Intent mySplashIntent = new Intent(this,splash.class); startActivityForResult(mySplashIntent,1); } // add more buttons if they exist String newAction; for (int i = 1; i < len ; ++i) { // i=1, don't run for action0 newAction = "action" + i; if ( bar.containsKey(newAction) ) { // & ! (findView(newAction)) ) { // add new button to activity //Log.i(TAG, "mark need to add: " + newAction + ", " + (String) bar.get(newAction) + ", " +buttonHeight); createNewButton(newAction, myMgrPrefs.getString(newAction, getString(R.string.markaction)), buttonHeight); } } //Log.i(TAG, "mark myMgrPrefs: " + myMgrPrefs.getAll().toString()); /* show history at the bottom */ try { View history = new TextView(this); ((TextView) history).setText(myMgrPrefs.getString("lastactionpl", "")); ((ViewGroup) logEventButton.getParent()).addView(history); } catch(Exception e) { e.printStackTrace(); } boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } // begin work if (mExternalStorageAvailable & mExternalStorageWriteable ){ // getExternalStorageDirectory() // check if file exists //read in last event from log try { File root = Environment.getExternalStorageDirectory(); Resources res = getResources(); String sFileName = res.getString(R.string.log_event_filename); //String sFileName = "activehabits.txt"; File gpxfile = new File(root,sFileName); if (gpxfile.exists()) writer = new FileWriter(gpxfile, true); // appends else writer = new FileWriter(gpxfile, false); // doesn't exist so overwrite a new file // I hope this fixes the first click new user crash bug } catch(IOException e) { e.printStackTrace(); } // needs testing // create log && notify user new file was created } // else { // external storage is either not available or not writeable - trouble // notify user of no writeable storage and no log && exit } private void createNewButton(String newAction, String newActionString, Integer newButtonHeight) { // add new button to activity Button newButton = new Button(this); newButton.setMinLines(3); newButton.setPadding(10, 10, 10, 10); newButton.setTextSize((float)24.0); newButton.setTypeface(null, Typeface.BOLD); newButton.setTag(newAction); newButton.setText(newActionString); newButton.setClickable(true); newButton.setLongClickable(true); newButton.setFocusableInTouchMode(false); newButton.setFocusable(true); newButton.setOnClickListener((OnClickListener) this); newButton.setHeight(newButtonHeight); newButton.setTextColor(0xFFFFFFFF); // text color newButton.getBackground().setColorFilter(0x33FFFFFF, PorterDuff.Mode.MULTIPLY); // background color registerForContextMenu(newButton); View logEventButton = findViewById(R.id.log_event_button); ((ViewGroup) logEventButton.getParent()).addView(newButton); //Log.i(TAG, "mark added: " + newAction + ", " + newActionString); } @Override public void onPause() { try { writer.flush(); writer.close(); } catch(IOException e) { e.printStackTrace(); } super.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // bottom menu MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.habit_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // bottom menu super.onPrepareOptionsMenu(menu); menu.removeItem(R.id.mark); // we are in mark so disable mark item menu.removeItem(R.id.addaction); // streamlining? // is it possible to make menu 1 x 3 instead of 2x2? return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.chart: Intent myChartIntent = new Intent(this,chart.class); startActivity(myChartIntent); finish(); return true; // case R.id.social: // return true; case R.id.addaction: addNewAction(); return true; case R.id.about: Intent myAboutIntent = new Intent(this,about.class); startActivity(myAboutIntent); return true; // case R.id.quit: { // finish(); // return true; // } default: return super.onOptionsItemSelected(item); } } public void onClick(View v) { Calendar rightnow = Calendar.getInstance(); Date x = rightnow.getTime(); // x.getTime() should be identical rightnow.getTimeInMillis() Integer b = x.getMinutes() * 100 / 60; LocationManager locator = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location loc = null; try { loc = locator.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (loc == null) { // Fall back to coarse location. loc = locator.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // criteria, enabledOnly - getLastKnownLocation error check? } } catch (IllegalArgumentException e) { e.printStackTrace(); } String locString; if (loc == null) locString = ""; else locString = loc.toString(); - String buttonText = (String) ((Button) v).getText(); + String buttonText = ((Button) v).getText().toString(); //Log.i(TAG, "buttonText: " + buttonText); //Log.i(TAG, "R.string.markaction: " + getString(R.string.markaction)); //if (buttonText == ((CharSequence) getString(R.string.markaction))) { if (buttonText.matches(getString(R.string.markaction))) { // TODO: \o/ dialog - rename before pressing a button, marking an action //Log.i(TAG, "buttonText MATCHED"); return; } //Log.i(TAG, "recorded bad data?"); long presentTime = (rightnow.getTimeInMillis() / 1000); try { if (b < 10) { Log.i(TAG, "mark write: " + buttonText + "\t" + presentTime + "\t" + x.getHours() + ".0" + b + "\t" + x.toLocaleString() + "\t" + locString); writer.append( buttonText + "\t" + presentTime + "\t" + x.getHours() + ".0" + b + "\t" + x.toLocaleString() + "\t" + locString + "\n"); } else { Log.i(TAG, "mark write: " + buttonText + "\t" + presentTime + "\t" + x.getHours() + "." + b + "\t" + x.toLocaleString() + "\t" + locString); writer.append( buttonText + "\t" + presentTime + "\t" + x.getHours() + "." + b + "\t" + x.toLocaleString() + "\t" + locString + "\n"); } } catch (IOException e) { e.printStackTrace(); } // if a playlist is set, play it SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); String playAction = (String)v.getTag(); String pl = myMgrPrefs.getString( playAction + "pl", null); if ( ! ( pl == null) ) { Log.i(TAG, "play list " + pl); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setComponent(new ComponentName("com.android.music","com.android.music.PlaylistBrowserActivity")); intent.setType(MediaStore.Audio.Playlists.CONTENT_TYPE); intent.setFlags(0x10000000); // need to understand these 3 lines //intent.putExtra(playlist, false); intent.putExtra("playlist", pl ); startActivity(intent); // test mp3 http://download29.jamendo.com/download/track/469312/mp32/24deaf7def/Hope.mp3 } /* store clicked item as history */ // lastactionpl is the key // "[button's name], [human readable date string]" is the value, ready for display Editor e = myMgrPrefs.edit(); e.putString("lastactionpl", "last action: " + buttonText + " @ " + x.toLocaleString() ); e.commit(); finish(); } private void addNewAction() { SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); // add to shared preferences int len = sizeWithoutPl(myMgrPrefs); // -1 for 0 based, + 1 for new value = size String newAction = "action" + len; //Log.i(TAG, "mark adding: " + newAction + ", " + getString(R.string.markaction)); Editor e = myMgrPrefs.edit(); e.putString(newAction, getString(R.string.markaction)); e.putString(newAction + "pl", null); e.commit(); //Log.i(TAG, "mark myMgrPrefs: " + myMgrPrefs.getAll().toString()); // calculate new buttonHeight Display container = ((WindowManager)this.getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); final Integer buttonHeight; // we are adding a button, len will be OK. buttonHeight = (Integer) ((container.getHeight() - (10*(mark.paddingValue) )) / (len)); // resize existing buttons to buttonHeight ViewGroup context = (ViewGroup) findViewById(R.id.log_event_button).getParent(); Integer i; for (i = 0; i < len; ++i) { //Log.i(TAG, "mark resizing " + i + ", " + context.getChildAt(i) + " to " + buttonHeight); ((Button) context.getChildAt(i)).setHeight(buttonHeight); } // add button to activity createNewButton(newAction, getString(R.string.markaction), buttonHeight); // redraw Intent myPrefIntent = new Intent(this,mark.class); startActivity(myPrefIntent); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); contextMenuItem = v; // stores button context menu called from // does not need to move to onPrepareContextMenu /* create and attach submenu */ // TODO: submenu in correct ordering //MenuItem bar = (MenuItem) findViewById(R.id.removeaction); //int foo = bar.getOrder(); //Log.i(TAG, "foo: " + foo); SubMenu sub = menu.addSubMenu ( 1, 3, 0, R.string.playlistchange ); sub.clear(); sub.add( 0, R.id.playlistclear, 0, R.string.playlistclear ); // I sure hope the list of playlists doesn't change on me but this function is my only choice /* populate submenu */ String playlistid = null; String newListName = null; Cursor cursor = getContentResolver().query( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { do { playlistid = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists._ID)); newListName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.NAME)); //listPlay.add(newListName); //listIds.add(playlistid); Intent intent = new Intent(); intent.putExtra("playlist", Long.parseLong(playlistid)); // this is a fantastic intent trick from com/android/music/MusicUtils.java and MediaPlaybackActivity.java sub.add(2, R.id.playlistselected, Integer.parseInt(playlistid), newListName).setIntent(intent); } while (cursor.moveToNext()); cursor.close(); } } } // Doesn't Exist!!! WTF!? // @Override // public void onPrepareContextMenu(ContextMenu menu) { // super.onPrepareOptionsMenu(menu); // } @Override public boolean onContextItemSelected(MenuItem item) { // need these vars for playlistclear and playlistselected SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); Editor e = myMgrPrefs.edit(); String theAction = (String) ((Button)contextMenuItem).getTag(); // Handle item selection switch (item.getItemId()) { case R.id.renameaction: showDialog(R.layout.rename); return true; case R.id.removeaction: showDialog(R.layout.remove); return true; case R.id.addaction: addNewAction(); return true; case R.id.moveup: moveAction(theAction, "up"); return true; case R.id.movedown: moveAction(theAction, "down"); return true; //case R.id.playlist: // done automatically case R.id.playlistclear: /* set pl to null */ Log.i(TAG, "playlistclear from " + myMgrPrefs.getString(theAction + "pl", null) + " to null"); e.putString(theAction + "pl", null); e.commit(); return true; case R.id.playlistselected: // this is a fantastic intent trick from com/android/music/MusicUtils.java and MediaPlaybackActivity.java long sel = item.getIntent().getLongExtra("playlist", 0); Log.i(TAG, "sel " + sel ); /* set pl setting to sel */ Log.i(TAG, "playlistclear from " + myMgrPrefs.getString(theAction + "pl", null) + " to sel " + sel); e.putString(theAction + "pl", Long.toString(sel) ); e.commit(); return true; default: return super.onContextItemSelected(item); } } @Override protected Dialog onCreateDialog(int id) { //Dialog dialog; switch(id) { case R.layout.rename: //renameDialogInt: // from Context Item LayoutInflater factory = LayoutInflater.from(mark.this); textEntryView = factory.inflate(R.layout.rename, null); /* return the constructed AlertDialog */ // TODO: can enter be intercepted during dialog text entry? return new AlertDialog.Builder(mark.this) .setTitle(R.string.renametitle) // add text of action .setView(textEntryView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK */ EditText b = (EditText) textEntryView.findViewById(R.id.renametext); final CharSequence ca; ca = (CharSequence) b.getText(); // TODO: if result not null & ! equal to old result /* change preference */ CharSequence newAction = (CharSequence) ((Button)contextMenuItem).getTag(); //final CharSequence x = ((Button)contextMenuItem).getText(); //Log.i(TAG, "change " + newAction + " from " + x + " to " + ca ); SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); //Log.i(TAG, "mark myMgrPrefs before: " + myMgrPrefs.getAll().toString() ); Editor e = myMgrPrefs.edit(); e.putString( newAction.toString(), ca.toString()); e.commit(); //Log.i(TAG, "mark myMgrPrefs after: " + myMgrPrefs.getAll().toString()); /* change button */ ((Button)contextMenuItem).setText(ca); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do nothing */ } }) //.setIcon(R.drawable.alert_dialog_icon) .create(); case R.layout.remove: LayoutInflater removeFactory = LayoutInflater.from(mark.this); View confirmView = removeFactory.inflate(R.layout.remove, null); // confirm remove dialog return new AlertDialog.Builder(mark.this) .setTitle(R.string.removetitle) .setView(confirmView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK */ /* change preferences by moving all down to fill the gap */ CharSequence oldAction = (CharSequence) ((Button)contextMenuItem).getTag(); SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); int len = sizeWithoutPl(myMgrPrefs); // assume string of exactly "actionX", X<10 int begin = Integer.parseInt(oldAction.subSequence(6, 7).toString()); //Log.i(TAG, "remove " + oldAction + ", move from " + begin + " to len " + len); //Log.i(TAG, "mark myMgrPrefs before: " + myMgrPrefs.getAll().toString() ); Editor e = myMgrPrefs.edit(); for (int i = begin; i < len ; ++i) { String newAction = "action" + i; String movedAction = "action" + (i+1); e.putString( newAction, myMgrPrefs.getString(movedAction, "error") ); // error if defaults } e.remove("action"+(len-1)); e.remove("action"+(len-1)+"pl"); e.commit(); //Log.i(TAG, "mark myMgrPrefs after: " + myMgrPrefs.getAll().toString()); // redraw Intent myRemovePrefIntent = new Intent(getBaseContext(), mark.class); startActivity(myRemovePrefIntent); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do nothing */ } }) //.setIcon(R.drawable.alert_dialog_icon) .create(); default: return null; } } @Override protected void onPrepareDialog(int id, Dialog d) { //super.onPrepareDialog(id, d); switch(id) { case R.layout.rename: //renameDialogInt: // from Context Item // prepare default text of dialog box with button name // if it is not the default button name View y = d.findViewById(R.id.renametext); if ( ! ((Button)contextMenuItem).getText().toString().equals(getString(R.string.markaction)) ) { ((TextView) y).setText(((Button)contextMenuItem).getText()); // TODO: set cursor to end, highlight as well? // Log.i(TAG, "CHANGED"); //} else { // Log.i(TAG, "UNCHANGED"); } } } private int sizeWithoutPl(SharedPreferences myMgrPrefs) { int total = myMgrPrefs.getAll().size(); Set<String> baz = myMgrPrefs.getAll().keySet(); Iterator<String> bar = baz.iterator(); int totalPl = 0; int i; String s; for (i = 0; i < total; ++i) { s = bar.next(); if ( ! (s == null) ) { //Log.i(TAG, "s " + s); if ( s.matches(".*pl") ) { //Log.i(TAG, "s matched"); totalPl = totalPl+1; } } } //Log.i(TAG, "sizeWithoutPl" + " total " + total + ", totalPl " + totalPl); if ((total - totalPl) == 0) { return 1; } else { return ( total - totalPl ); } } private int moveAction(CharSequence theAction, CharSequence direction) { SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); int len = sizeWithoutPl(myMgrPrefs); // assume string of exactly "actionX", X<10 int begin = Integer.parseInt(theAction.subSequence(6, 7).toString()); if ( ( (begin == len) && (direction == "up") ) || ( (begin == 1) && (direction == "down") ) ) { // impossible, TODO: dialog to notify of illegal action return 1; } //Log.i(TAG, "remove " + oldAction + ", move from " + begin + " to len " + len); //Log.i(TAG, "mark myMgrPrefs before: " + myMgrPrefs.getAll().toString() ); String tempAction = null; // String tempPlaylist = null; // TODO: move playlists too Editor e = myMgrPrefs.edit(); if (direction == "up") { // list is top to bottom tempAction = myMgrPrefs.getString("action" + (begin-1), "error"); e.putString("action" + (begin-1), myMgrPrefs.getString("action" + (begin), "error")); e.putString("action" + (begin), tempAction); } else { // ASSUME direction == "down" // increment tempAction = myMgrPrefs.getString("action" + (begin+1), "error"); e.putString("action" + (begin+1), myMgrPrefs.getString("action" + (begin), "error")); e.putString("action" + (begin), tempAction); } //e.remove("action"+(len-1)+"pl"); e.commit(); //Log.i(TAG, "mark myMgrPrefs after: " + myMgrPrefs.getAll().toString()); // redraw Intent myRemovePrefIntent = new Intent(getBaseContext(), mark.class); startActivity(myRemovePrefIntent); return 1; } };
true
true
public void onResume() { super.onResume(); // load default preferences SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); setContentView(R.layout.main); // prepare to add more buttons from myMgrPrefs if they exist Map<String, ?> bar = myMgrPrefs.getAll(); //Log.i(TAG, "mark myMgrPrefs: " + bar.toString()); int len = sizeWithoutPl(myMgrPrefs); // roughly each button height = screen size / 1+len // subtract for padding - use self.paddingValue Display container = ((WindowManager)this.getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); //Log.i(TAG, "mark vars1: " + container.toString() ); //Log.i(TAG, "mark vars2: " + container.getHeight());//(int) container.getHeight() ); Integer buttonHeight; if (len == 0) { buttonHeight = (Integer) ((container.getHeight() - (10*(mark.paddingValue+1) )) / (1)); } else { buttonHeight = (Integer) ((container.getHeight() - (10*(len+mark.paddingValue) )) / (len)); } // set up action0 button Button logEventButton = (Button) findViewById(R.id.log_event_button); logEventButton.setText(myMgrPrefs.getString("action0", getString(R.string.markaction))); logEventButton.setTag("action0"); logEventButton.setMinLines(3); logEventButton.setPadding(10, 10, 10, 10); logEventButton.setTextSize((float)24.0); logEventButton.setTypeface(null, Typeface.BOLD); logEventButton.setOnClickListener((OnClickListener) this); logEventButton.setHeight(buttonHeight); logEventButton.setTextColor(0xFFFFFFFF); // text color logEventButton.getBackground().setColorFilter(0x33FFFFFF, PorterDuff.Mode.MULTIPLY); // background color // use 0xFFFFFFFF for default behavior registerForContextMenu(logEventButton); final CharSequence setTo = logEventButton.getText(); final CharSequence defaultSetTo = getString(R.string.markaction); //Log.i(TAG, "mark splash? " + setTo + ", " + defaultSetTo); if (setTo.equals(defaultSetTo) & (mark.splashed == 0)) { // strange syntax to make it compare mark.splashed = 1; // assume if first action is not changed from default // this is first run or help is needed so show splash Intent mySplashIntent = new Intent(this,splash.class); startActivityForResult(mySplashIntent,1); } // add more buttons if they exist String newAction; for (int i = 1; i < len ; ++i) { // i=1, don't run for action0 newAction = "action" + i; if ( bar.containsKey(newAction) ) { // & ! (findView(newAction)) ) { // add new button to activity //Log.i(TAG, "mark need to add: " + newAction + ", " + (String) bar.get(newAction) + ", " +buttonHeight); createNewButton(newAction, myMgrPrefs.getString(newAction, getString(R.string.markaction)), buttonHeight); } } //Log.i(TAG, "mark myMgrPrefs: " + myMgrPrefs.getAll().toString()); /* show history at the bottom */ try { View history = new TextView(this); ((TextView) history).setText(myMgrPrefs.getString("lastactionpl", "")); ((ViewGroup) logEventButton.getParent()).addView(history); } catch(Exception e) { e.printStackTrace(); } boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } // begin work if (mExternalStorageAvailable & mExternalStorageWriteable ){ // getExternalStorageDirectory() // check if file exists //read in last event from log try { File root = Environment.getExternalStorageDirectory(); Resources res = getResources(); String sFileName = res.getString(R.string.log_event_filename); //String sFileName = "activehabits.txt"; File gpxfile = new File(root,sFileName); if (gpxfile.exists()) writer = new FileWriter(gpxfile, true); // appends else writer = new FileWriter(gpxfile, false); // doesn't exist so overwrite a new file // I hope this fixes the first click new user crash bug } catch(IOException e) { e.printStackTrace(); } // needs testing // create log && notify user new file was created } // else { // external storage is either not available or not writeable - trouble // notify user of no writeable storage and no log && exit } private void createNewButton(String newAction, String newActionString, Integer newButtonHeight) { // add new button to activity Button newButton = new Button(this); newButton.setMinLines(3); newButton.setPadding(10, 10, 10, 10); newButton.setTextSize((float)24.0); newButton.setTypeface(null, Typeface.BOLD); newButton.setTag(newAction); newButton.setText(newActionString); newButton.setClickable(true); newButton.setLongClickable(true); newButton.setFocusableInTouchMode(false); newButton.setFocusable(true); newButton.setOnClickListener((OnClickListener) this); newButton.setHeight(newButtonHeight); newButton.setTextColor(0xFFFFFFFF); // text color newButton.getBackground().setColorFilter(0x33FFFFFF, PorterDuff.Mode.MULTIPLY); // background color registerForContextMenu(newButton); View logEventButton = findViewById(R.id.log_event_button); ((ViewGroup) logEventButton.getParent()).addView(newButton); //Log.i(TAG, "mark added: " + newAction + ", " + newActionString); } @Override public void onPause() { try { writer.flush(); writer.close(); } catch(IOException e) { e.printStackTrace(); } super.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // bottom menu MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.habit_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // bottom menu super.onPrepareOptionsMenu(menu); menu.removeItem(R.id.mark); // we are in mark so disable mark item menu.removeItem(R.id.addaction); // streamlining? // is it possible to make menu 1 x 3 instead of 2x2? return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.chart: Intent myChartIntent = new Intent(this,chart.class); startActivity(myChartIntent); finish(); return true; // case R.id.social: // return true; case R.id.addaction: addNewAction(); return true; case R.id.about: Intent myAboutIntent = new Intent(this,about.class); startActivity(myAboutIntent); return true; // case R.id.quit: { // finish(); // return true; // } default: return super.onOptionsItemSelected(item); } } public void onClick(View v) { Calendar rightnow = Calendar.getInstance(); Date x = rightnow.getTime(); // x.getTime() should be identical rightnow.getTimeInMillis() Integer b = x.getMinutes() * 100 / 60; LocationManager locator = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location loc = null; try { loc = locator.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (loc == null) { // Fall back to coarse location. loc = locator.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // criteria, enabledOnly - getLastKnownLocation error check? } } catch (IllegalArgumentException e) { e.printStackTrace(); } String locString; if (loc == null) locString = ""; else locString = loc.toString(); String buttonText = (String) ((Button) v).getText(); //Log.i(TAG, "buttonText: " + buttonText); //Log.i(TAG, "R.string.markaction: " + getString(R.string.markaction)); //if (buttonText == ((CharSequence) getString(R.string.markaction))) { if (buttonText.matches(getString(R.string.markaction))) { // TODO: \o/ dialog - rename before pressing a button, marking an action //Log.i(TAG, "buttonText MATCHED"); return; } //Log.i(TAG, "recorded bad data?"); long presentTime = (rightnow.getTimeInMillis() / 1000); try { if (b < 10) { Log.i(TAG, "mark write: " + buttonText + "\t" + presentTime + "\t" + x.getHours() + ".0" + b + "\t" + x.toLocaleString() + "\t" + locString); writer.append( buttonText + "\t" + presentTime + "\t" + x.getHours() + ".0" + b + "\t" + x.toLocaleString() + "\t" + locString + "\n"); } else { Log.i(TAG, "mark write: " + buttonText + "\t" + presentTime + "\t" + x.getHours() + "." + b + "\t" + x.toLocaleString() + "\t" + locString); writer.append( buttonText + "\t" + presentTime + "\t" + x.getHours() + "." + b + "\t" + x.toLocaleString() + "\t" + locString + "\n"); } } catch (IOException e) { e.printStackTrace(); } // if a playlist is set, play it SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); String playAction = (String)v.getTag(); String pl = myMgrPrefs.getString( playAction + "pl", null); if ( ! ( pl == null) ) { Log.i(TAG, "play list " + pl); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setComponent(new ComponentName("com.android.music","com.android.music.PlaylistBrowserActivity")); intent.setType(MediaStore.Audio.Playlists.CONTENT_TYPE); intent.setFlags(0x10000000); // need to understand these 3 lines //intent.putExtra(playlist, false); intent.putExtra("playlist", pl ); startActivity(intent); // test mp3 http://download29.jamendo.com/download/track/469312/mp32/24deaf7def/Hope.mp3 } /* store clicked item as history */ // lastactionpl is the key // "[button's name], [human readable date string]" is the value, ready for display Editor e = myMgrPrefs.edit(); e.putString("lastactionpl", "last action: " + buttonText + " @ " + x.toLocaleString() ); e.commit(); finish(); } private void addNewAction() { SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); // add to shared preferences int len = sizeWithoutPl(myMgrPrefs); // -1 for 0 based, + 1 for new value = size String newAction = "action" + len; //Log.i(TAG, "mark adding: " + newAction + ", " + getString(R.string.markaction)); Editor e = myMgrPrefs.edit(); e.putString(newAction, getString(R.string.markaction)); e.putString(newAction + "pl", null); e.commit(); //Log.i(TAG, "mark myMgrPrefs: " + myMgrPrefs.getAll().toString()); // calculate new buttonHeight Display container = ((WindowManager)this.getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); final Integer buttonHeight; // we are adding a button, len will be OK. buttonHeight = (Integer) ((container.getHeight() - (10*(mark.paddingValue) )) / (len)); // resize existing buttons to buttonHeight ViewGroup context = (ViewGroup) findViewById(R.id.log_event_button).getParent(); Integer i; for (i = 0; i < len; ++i) { //Log.i(TAG, "mark resizing " + i + ", " + context.getChildAt(i) + " to " + buttonHeight); ((Button) context.getChildAt(i)).setHeight(buttonHeight); } // add button to activity createNewButton(newAction, getString(R.string.markaction), buttonHeight); // redraw Intent myPrefIntent = new Intent(this,mark.class); startActivity(myPrefIntent); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); contextMenuItem = v; // stores button context menu called from // does not need to move to onPrepareContextMenu /* create and attach submenu */ // TODO: submenu in correct ordering //MenuItem bar = (MenuItem) findViewById(R.id.removeaction); //int foo = bar.getOrder(); //Log.i(TAG, "foo: " + foo); SubMenu sub = menu.addSubMenu ( 1, 3, 0, R.string.playlistchange ); sub.clear(); sub.add( 0, R.id.playlistclear, 0, R.string.playlistclear ); // I sure hope the list of playlists doesn't change on me but this function is my only choice /* populate submenu */ String playlistid = null; String newListName = null; Cursor cursor = getContentResolver().query( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { do { playlistid = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists._ID)); newListName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.NAME)); //listPlay.add(newListName); //listIds.add(playlistid); Intent intent = new Intent(); intent.putExtra("playlist", Long.parseLong(playlistid)); // this is a fantastic intent trick from com/android/music/MusicUtils.java and MediaPlaybackActivity.java sub.add(2, R.id.playlistselected, Integer.parseInt(playlistid), newListName).setIntent(intent); } while (cursor.moveToNext()); cursor.close(); } } } // Doesn't Exist!!! WTF!? // @Override // public void onPrepareContextMenu(ContextMenu menu) { // super.onPrepareOptionsMenu(menu); // } @Override public boolean onContextItemSelected(MenuItem item) { // need these vars for playlistclear and playlistselected SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); Editor e = myMgrPrefs.edit(); String theAction = (String) ((Button)contextMenuItem).getTag(); // Handle item selection switch (item.getItemId()) { case R.id.renameaction: showDialog(R.layout.rename); return true; case R.id.removeaction: showDialog(R.layout.remove); return true; case R.id.addaction: addNewAction(); return true; case R.id.moveup: moveAction(theAction, "up"); return true; case R.id.movedown: moveAction(theAction, "down"); return true; //case R.id.playlist: // done automatically case R.id.playlistclear: /* set pl to null */ Log.i(TAG, "playlistclear from " + myMgrPrefs.getString(theAction + "pl", null) + " to null"); e.putString(theAction + "pl", null); e.commit(); return true; case R.id.playlistselected: // this is a fantastic intent trick from com/android/music/MusicUtils.java and MediaPlaybackActivity.java long sel = item.getIntent().getLongExtra("playlist", 0); Log.i(TAG, "sel " + sel ); /* set pl setting to sel */ Log.i(TAG, "playlistclear from " + myMgrPrefs.getString(theAction + "pl", null) + " to sel " + sel); e.putString(theAction + "pl", Long.toString(sel) ); e.commit(); return true; default: return super.onContextItemSelected(item); } } @Override protected Dialog onCreateDialog(int id) { //Dialog dialog; switch(id) { case R.layout.rename: //renameDialogInt: // from Context Item LayoutInflater factory = LayoutInflater.from(mark.this); textEntryView = factory.inflate(R.layout.rename, null); /* return the constructed AlertDialog */ // TODO: can enter be intercepted during dialog text entry? return new AlertDialog.Builder(mark.this) .setTitle(R.string.renametitle) // add text of action .setView(textEntryView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK */ EditText b = (EditText) textEntryView.findViewById(R.id.renametext); final CharSequence ca; ca = (CharSequence) b.getText(); // TODO: if result not null & ! equal to old result /* change preference */ CharSequence newAction = (CharSequence) ((Button)contextMenuItem).getTag(); //final CharSequence x = ((Button)contextMenuItem).getText(); //Log.i(TAG, "change " + newAction + " from " + x + " to " + ca ); SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); //Log.i(TAG, "mark myMgrPrefs before: " + myMgrPrefs.getAll().toString() ); Editor e = myMgrPrefs.edit(); e.putString( newAction.toString(), ca.toString()); e.commit(); //Log.i(TAG, "mark myMgrPrefs after: " + myMgrPrefs.getAll().toString()); /* change button */ ((Button)contextMenuItem).setText(ca); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do nothing */ } }) //.setIcon(R.drawable.alert_dialog_icon) .create(); case R.layout.remove: LayoutInflater removeFactory = LayoutInflater.from(mark.this); View confirmView = removeFactory.inflate(R.layout.remove, null); // confirm remove dialog return new AlertDialog.Builder(mark.this) .setTitle(R.string.removetitle) .setView(confirmView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK */ /* change preferences by moving all down to fill the gap */ CharSequence oldAction = (CharSequence) ((Button)contextMenuItem).getTag(); SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); int len = sizeWithoutPl(myMgrPrefs); // assume string of exactly "actionX", X<10 int begin = Integer.parseInt(oldAction.subSequence(6, 7).toString()); //Log.i(TAG, "remove " + oldAction + ", move from " + begin + " to len " + len); //Log.i(TAG, "mark myMgrPrefs before: " + myMgrPrefs.getAll().toString() ); Editor e = myMgrPrefs.edit(); for (int i = begin; i < len ; ++i) { String newAction = "action" + i; String movedAction = "action" + (i+1); e.putString( newAction, myMgrPrefs.getString(movedAction, "error") ); // error if defaults } e.remove("action"+(len-1)); e.remove("action"+(len-1)+"pl"); e.commit(); //Log.i(TAG, "mark myMgrPrefs after: " + myMgrPrefs.getAll().toString()); // redraw Intent myRemovePrefIntent = new Intent(getBaseContext(), mark.class); startActivity(myRemovePrefIntent); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do nothing */ } }) //.setIcon(R.drawable.alert_dialog_icon) .create(); default: return null; } } @Override protected void onPrepareDialog(int id, Dialog d) { //super.onPrepareDialog(id, d); switch(id) { case R.layout.rename: //renameDialogInt: // from Context Item // prepare default text of dialog box with button name // if it is not the default button name View y = d.findViewById(R.id.renametext); if ( ! ((Button)contextMenuItem).getText().toString().equals(getString(R.string.markaction)) ) { ((TextView) y).setText(((Button)contextMenuItem).getText()); // TODO: set cursor to end, highlight as well? // Log.i(TAG, "CHANGED"); //} else { // Log.i(TAG, "UNCHANGED"); } } } private int sizeWithoutPl(SharedPreferences myMgrPrefs) { int total = myMgrPrefs.getAll().size(); Set<String> baz = myMgrPrefs.getAll().keySet(); Iterator<String> bar = baz.iterator(); int totalPl = 0; int i; String s; for (i = 0; i < total; ++i) { s = bar.next(); if ( ! (s == null) ) { //Log.i(TAG, "s " + s); if ( s.matches(".*pl") ) { //Log.i(TAG, "s matched"); totalPl = totalPl+1; } } } //Log.i(TAG, "sizeWithoutPl" + " total " + total + ", totalPl " + totalPl); if ((total - totalPl) == 0) { return 1; } else { return ( total - totalPl ); } } private int moveAction(CharSequence theAction, CharSequence direction) { SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); int len = sizeWithoutPl(myMgrPrefs); // assume string of exactly "actionX", X<10 int begin = Integer.parseInt(theAction.subSequence(6, 7).toString()); if ( ( (begin == len) && (direction == "up") ) || ( (begin == 1) && (direction == "down") ) ) { // impossible, TODO: dialog to notify of illegal action return 1; } //Log.i(TAG, "remove " + oldAction + ", move from " + begin + " to len " + len); //Log.i(TAG, "mark myMgrPrefs before: " + myMgrPrefs.getAll().toString() ); String tempAction = null; // String tempPlaylist = null; // TODO: move playlists too Editor e = myMgrPrefs.edit(); if (direction == "up") { // list is top to bottom tempAction = myMgrPrefs.getString("action" + (begin-1), "error"); e.putString("action" + (begin-1), myMgrPrefs.getString("action" + (begin), "error")); e.putString("action" + (begin), tempAction); } else { // ASSUME direction == "down" // increment tempAction = myMgrPrefs.getString("action" + (begin+1), "error"); e.putString("action" + (begin+1), myMgrPrefs.getString("action" + (begin), "error")); e.putString("action" + (begin), tempAction); } //e.remove("action"+(len-1)+"pl"); e.commit(); //Log.i(TAG, "mark myMgrPrefs after: " + myMgrPrefs.getAll().toString()); // redraw Intent myRemovePrefIntent = new Intent(getBaseContext(), mark.class); startActivity(myRemovePrefIntent); return 1; } };
public void onResume() { super.onResume(); // load default preferences SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); setContentView(R.layout.main); // prepare to add more buttons from myMgrPrefs if they exist Map<String, ?> bar = myMgrPrefs.getAll(); //Log.i(TAG, "mark myMgrPrefs: " + bar.toString()); int len = sizeWithoutPl(myMgrPrefs); // roughly each button height = screen size / 1+len // subtract for padding - use self.paddingValue Display container = ((WindowManager)this.getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); //Log.i(TAG, "mark vars1: " + container.toString() ); //Log.i(TAG, "mark vars2: " + container.getHeight());//(int) container.getHeight() ); Integer buttonHeight; if (len == 0) { buttonHeight = (Integer) ((container.getHeight() - (10*(mark.paddingValue+1) )) / (1)); } else { buttonHeight = (Integer) ((container.getHeight() - (10*(len+mark.paddingValue) )) / (len)); } // set up action0 button Button logEventButton = (Button) findViewById(R.id.log_event_button); logEventButton.setText(myMgrPrefs.getString("action0", getString(R.string.markaction))); logEventButton.setTag("action0"); logEventButton.setMinLines(3); logEventButton.setPadding(10, 10, 10, 10); logEventButton.setTextSize((float)24.0); logEventButton.setTypeface(null, Typeface.BOLD); logEventButton.setOnClickListener((OnClickListener) this); logEventButton.setHeight(buttonHeight); logEventButton.setTextColor(0xFFFFFFFF); // text color logEventButton.getBackground().setColorFilter(0x33FFFFFF, PorterDuff.Mode.MULTIPLY); // background color // use 0xFFFFFFFF for default behavior registerForContextMenu(logEventButton); final CharSequence setTo = logEventButton.getText(); final CharSequence defaultSetTo = getString(R.string.markaction); //Log.i(TAG, "mark splash? " + setTo + ", " + defaultSetTo); if (setTo.equals(defaultSetTo) & (mark.splashed == 0)) { // strange syntax to make it compare mark.splashed = 1; // assume if first action is not changed from default // this is first run or help is needed so show splash Intent mySplashIntent = new Intent(this,splash.class); startActivityForResult(mySplashIntent,1); } // add more buttons if they exist String newAction; for (int i = 1; i < len ; ++i) { // i=1, don't run for action0 newAction = "action" + i; if ( bar.containsKey(newAction) ) { // & ! (findView(newAction)) ) { // add new button to activity //Log.i(TAG, "mark need to add: " + newAction + ", " + (String) bar.get(newAction) + ", " +buttonHeight); createNewButton(newAction, myMgrPrefs.getString(newAction, getString(R.string.markaction)), buttonHeight); } } //Log.i(TAG, "mark myMgrPrefs: " + myMgrPrefs.getAll().toString()); /* show history at the bottom */ try { View history = new TextView(this); ((TextView) history).setText(myMgrPrefs.getString("lastactionpl", "")); ((ViewGroup) logEventButton.getParent()).addView(history); } catch(Exception e) { e.printStackTrace(); } boolean mExternalStorageAvailable = false; boolean mExternalStorageWriteable = false; String state = Environment.getExternalStorageState(); if (Environment.MEDIA_MOUNTED.equals(state)) { // We can read and write the media mExternalStorageAvailable = mExternalStorageWriteable = true; } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { // We can only read the media mExternalStorageAvailable = true; mExternalStorageWriteable = false; } else { // Something else is wrong. It may be one of many other states, but all we need // to know is we can neither read nor write mExternalStorageAvailable = mExternalStorageWriteable = false; } // begin work if (mExternalStorageAvailable & mExternalStorageWriteable ){ // getExternalStorageDirectory() // check if file exists //read in last event from log try { File root = Environment.getExternalStorageDirectory(); Resources res = getResources(); String sFileName = res.getString(R.string.log_event_filename); //String sFileName = "activehabits.txt"; File gpxfile = new File(root,sFileName); if (gpxfile.exists()) writer = new FileWriter(gpxfile, true); // appends else writer = new FileWriter(gpxfile, false); // doesn't exist so overwrite a new file // I hope this fixes the first click new user crash bug } catch(IOException e) { e.printStackTrace(); } // needs testing // create log && notify user new file was created } // else { // external storage is either not available or not writeable - trouble // notify user of no writeable storage and no log && exit } private void createNewButton(String newAction, String newActionString, Integer newButtonHeight) { // add new button to activity Button newButton = new Button(this); newButton.setMinLines(3); newButton.setPadding(10, 10, 10, 10); newButton.setTextSize((float)24.0); newButton.setTypeface(null, Typeface.BOLD); newButton.setTag(newAction); newButton.setText(newActionString); newButton.setClickable(true); newButton.setLongClickable(true); newButton.setFocusableInTouchMode(false); newButton.setFocusable(true); newButton.setOnClickListener((OnClickListener) this); newButton.setHeight(newButtonHeight); newButton.setTextColor(0xFFFFFFFF); // text color newButton.getBackground().setColorFilter(0x33FFFFFF, PorterDuff.Mode.MULTIPLY); // background color registerForContextMenu(newButton); View logEventButton = findViewById(R.id.log_event_button); ((ViewGroup) logEventButton.getParent()).addView(newButton); //Log.i(TAG, "mark added: " + newAction + ", " + newActionString); } @Override public void onPause() { try { writer.flush(); writer.close(); } catch(IOException e) { e.printStackTrace(); } super.onPause(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // bottom menu MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.habit_menu, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // bottom menu super.onPrepareOptionsMenu(menu); menu.removeItem(R.id.mark); // we are in mark so disable mark item menu.removeItem(R.id.addaction); // streamlining? // is it possible to make menu 1 x 3 instead of 2x2? return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.chart: Intent myChartIntent = new Intent(this,chart.class); startActivity(myChartIntent); finish(); return true; // case R.id.social: // return true; case R.id.addaction: addNewAction(); return true; case R.id.about: Intent myAboutIntent = new Intent(this,about.class); startActivity(myAboutIntent); return true; // case R.id.quit: { // finish(); // return true; // } default: return super.onOptionsItemSelected(item); } } public void onClick(View v) { Calendar rightnow = Calendar.getInstance(); Date x = rightnow.getTime(); // x.getTime() should be identical rightnow.getTimeInMillis() Integer b = x.getMinutes() * 100 / 60; LocationManager locator = (LocationManager)getSystemService(Context.LOCATION_SERVICE); Location loc = null; try { loc = locator.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (loc == null) { // Fall back to coarse location. loc = locator.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // criteria, enabledOnly - getLastKnownLocation error check? } } catch (IllegalArgumentException e) { e.printStackTrace(); } String locString; if (loc == null) locString = ""; else locString = loc.toString(); String buttonText = ((Button) v).getText().toString(); //Log.i(TAG, "buttonText: " + buttonText); //Log.i(TAG, "R.string.markaction: " + getString(R.string.markaction)); //if (buttonText == ((CharSequence) getString(R.string.markaction))) { if (buttonText.matches(getString(R.string.markaction))) { // TODO: \o/ dialog - rename before pressing a button, marking an action //Log.i(TAG, "buttonText MATCHED"); return; } //Log.i(TAG, "recorded bad data?"); long presentTime = (rightnow.getTimeInMillis() / 1000); try { if (b < 10) { Log.i(TAG, "mark write: " + buttonText + "\t" + presentTime + "\t" + x.getHours() + ".0" + b + "\t" + x.toLocaleString() + "\t" + locString); writer.append( buttonText + "\t" + presentTime + "\t" + x.getHours() + ".0" + b + "\t" + x.toLocaleString() + "\t" + locString + "\n"); } else { Log.i(TAG, "mark write: " + buttonText + "\t" + presentTime + "\t" + x.getHours() + "." + b + "\t" + x.toLocaleString() + "\t" + locString); writer.append( buttonText + "\t" + presentTime + "\t" + x.getHours() + "." + b + "\t" + x.toLocaleString() + "\t" + locString + "\n"); } } catch (IOException e) { e.printStackTrace(); } // if a playlist is set, play it SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); String playAction = (String)v.getTag(); String pl = myMgrPrefs.getString( playAction + "pl", null); if ( ! ( pl == null) ) { Log.i(TAG, "play list " + pl); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setComponent(new ComponentName("com.android.music","com.android.music.PlaylistBrowserActivity")); intent.setType(MediaStore.Audio.Playlists.CONTENT_TYPE); intent.setFlags(0x10000000); // need to understand these 3 lines //intent.putExtra(playlist, false); intent.putExtra("playlist", pl ); startActivity(intent); // test mp3 http://download29.jamendo.com/download/track/469312/mp32/24deaf7def/Hope.mp3 } /* store clicked item as history */ // lastactionpl is the key // "[button's name], [human readable date string]" is the value, ready for display Editor e = myMgrPrefs.edit(); e.putString("lastactionpl", "last action: " + buttonText + " @ " + x.toLocaleString() ); e.commit(); finish(); } private void addNewAction() { SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); // add to shared preferences int len = sizeWithoutPl(myMgrPrefs); // -1 for 0 based, + 1 for new value = size String newAction = "action" + len; //Log.i(TAG, "mark adding: " + newAction + ", " + getString(R.string.markaction)); Editor e = myMgrPrefs.edit(); e.putString(newAction, getString(R.string.markaction)); e.putString(newAction + "pl", null); e.commit(); //Log.i(TAG, "mark myMgrPrefs: " + myMgrPrefs.getAll().toString()); // calculate new buttonHeight Display container = ((WindowManager)this.getSystemService(WINDOW_SERVICE)).getDefaultDisplay(); final Integer buttonHeight; // we are adding a button, len will be OK. buttonHeight = (Integer) ((container.getHeight() - (10*(mark.paddingValue) )) / (len)); // resize existing buttons to buttonHeight ViewGroup context = (ViewGroup) findViewById(R.id.log_event_button).getParent(); Integer i; for (i = 0; i < len; ++i) { //Log.i(TAG, "mark resizing " + i + ", " + context.getChildAt(i) + " to " + buttonHeight); ((Button) context.getChildAt(i)).setHeight(buttonHeight); } // add button to activity createNewButton(newAction, getString(R.string.markaction), buttonHeight); // redraw Intent myPrefIntent = new Intent(this,mark.class); startActivity(myPrefIntent); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); contextMenuItem = v; // stores button context menu called from // does not need to move to onPrepareContextMenu /* create and attach submenu */ // TODO: submenu in correct ordering //MenuItem bar = (MenuItem) findViewById(R.id.removeaction); //int foo = bar.getOrder(); //Log.i(TAG, "foo: " + foo); SubMenu sub = menu.addSubMenu ( 1, 3, 0, R.string.playlistchange ); sub.clear(); sub.add( 0, R.id.playlistclear, 0, R.string.playlistclear ); // I sure hope the list of playlists doesn't change on me but this function is my only choice /* populate submenu */ String playlistid = null; String newListName = null; Cursor cursor = getContentResolver().query( MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, null, null, null, null); if (cursor != null) { if (cursor.moveToFirst()) { do { playlistid = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists._ID)); newListName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Playlists.NAME)); //listPlay.add(newListName); //listIds.add(playlistid); Intent intent = new Intent(); intent.putExtra("playlist", Long.parseLong(playlistid)); // this is a fantastic intent trick from com/android/music/MusicUtils.java and MediaPlaybackActivity.java sub.add(2, R.id.playlistselected, Integer.parseInt(playlistid), newListName).setIntent(intent); } while (cursor.moveToNext()); cursor.close(); } } } // Doesn't Exist!!! WTF!? // @Override // public void onPrepareContextMenu(ContextMenu menu) { // super.onPrepareOptionsMenu(menu); // } @Override public boolean onContextItemSelected(MenuItem item) { // need these vars for playlistclear and playlistselected SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(this); Editor e = myMgrPrefs.edit(); String theAction = (String) ((Button)contextMenuItem).getTag(); // Handle item selection switch (item.getItemId()) { case R.id.renameaction: showDialog(R.layout.rename); return true; case R.id.removeaction: showDialog(R.layout.remove); return true; case R.id.addaction: addNewAction(); return true; case R.id.moveup: moveAction(theAction, "up"); return true; case R.id.movedown: moveAction(theAction, "down"); return true; //case R.id.playlist: // done automatically case R.id.playlistclear: /* set pl to null */ Log.i(TAG, "playlistclear from " + myMgrPrefs.getString(theAction + "pl", null) + " to null"); e.putString(theAction + "pl", null); e.commit(); return true; case R.id.playlistselected: // this is a fantastic intent trick from com/android/music/MusicUtils.java and MediaPlaybackActivity.java long sel = item.getIntent().getLongExtra("playlist", 0); Log.i(TAG, "sel " + sel ); /* set pl setting to sel */ Log.i(TAG, "playlistclear from " + myMgrPrefs.getString(theAction + "pl", null) + " to sel " + sel); e.putString(theAction + "pl", Long.toString(sel) ); e.commit(); return true; default: return super.onContextItemSelected(item); } } @Override protected Dialog onCreateDialog(int id) { //Dialog dialog; switch(id) { case R.layout.rename: //renameDialogInt: // from Context Item LayoutInflater factory = LayoutInflater.from(mark.this); textEntryView = factory.inflate(R.layout.rename, null); /* return the constructed AlertDialog */ // TODO: can enter be intercepted during dialog text entry? return new AlertDialog.Builder(mark.this) .setTitle(R.string.renametitle) // add text of action .setView(textEntryView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK */ EditText b = (EditText) textEntryView.findViewById(R.id.renametext); final CharSequence ca; ca = (CharSequence) b.getText(); // TODO: if result not null & ! equal to old result /* change preference */ CharSequence newAction = (CharSequence) ((Button)contextMenuItem).getTag(); //final CharSequence x = ((Button)contextMenuItem).getText(); //Log.i(TAG, "change " + newAction + " from " + x + " to " + ca ); SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); //Log.i(TAG, "mark myMgrPrefs before: " + myMgrPrefs.getAll().toString() ); Editor e = myMgrPrefs.edit(); e.putString( newAction.toString(), ca.toString()); e.commit(); //Log.i(TAG, "mark myMgrPrefs after: " + myMgrPrefs.getAll().toString()); /* change button */ ((Button)contextMenuItem).setText(ca); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do nothing */ } }) //.setIcon(R.drawable.alert_dialog_icon) .create(); case R.layout.remove: LayoutInflater removeFactory = LayoutInflater.from(mark.this); View confirmView = removeFactory.inflate(R.layout.remove, null); // confirm remove dialog return new AlertDialog.Builder(mark.this) .setTitle(R.string.removetitle) .setView(confirmView) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked OK */ /* change preferences by moving all down to fill the gap */ CharSequence oldAction = (CharSequence) ((Button)contextMenuItem).getTag(); SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); int len = sizeWithoutPl(myMgrPrefs); // assume string of exactly "actionX", X<10 int begin = Integer.parseInt(oldAction.subSequence(6, 7).toString()); //Log.i(TAG, "remove " + oldAction + ", move from " + begin + " to len " + len); //Log.i(TAG, "mark myMgrPrefs before: " + myMgrPrefs.getAll().toString() ); Editor e = myMgrPrefs.edit(); for (int i = begin; i < len ; ++i) { String newAction = "action" + i; String movedAction = "action" + (i+1); e.putString( newAction, myMgrPrefs.getString(movedAction, "error") ); // error if defaults } e.remove("action"+(len-1)); e.remove("action"+(len-1)+"pl"); e.commit(); //Log.i(TAG, "mark myMgrPrefs after: " + myMgrPrefs.getAll().toString()); // redraw Intent myRemovePrefIntent = new Intent(getBaseContext(), mark.class); startActivity(myRemovePrefIntent); } }) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { /* User clicked cancel so do nothing */ } }) //.setIcon(R.drawable.alert_dialog_icon) .create(); default: return null; } } @Override protected void onPrepareDialog(int id, Dialog d) { //super.onPrepareDialog(id, d); switch(id) { case R.layout.rename: //renameDialogInt: // from Context Item // prepare default text of dialog box with button name // if it is not the default button name View y = d.findViewById(R.id.renametext); if ( ! ((Button)contextMenuItem).getText().toString().equals(getString(R.string.markaction)) ) { ((TextView) y).setText(((Button)contextMenuItem).getText()); // TODO: set cursor to end, highlight as well? // Log.i(TAG, "CHANGED"); //} else { // Log.i(TAG, "UNCHANGED"); } } } private int sizeWithoutPl(SharedPreferences myMgrPrefs) { int total = myMgrPrefs.getAll().size(); Set<String> baz = myMgrPrefs.getAll().keySet(); Iterator<String> bar = baz.iterator(); int totalPl = 0; int i; String s; for (i = 0; i < total; ++i) { s = bar.next(); if ( ! (s == null) ) { //Log.i(TAG, "s " + s); if ( s.matches(".*pl") ) { //Log.i(TAG, "s matched"); totalPl = totalPl+1; } } } //Log.i(TAG, "sizeWithoutPl" + " total " + total + ", totalPl " + totalPl); if ((total - totalPl) == 0) { return 1; } else { return ( total - totalPl ); } } private int moveAction(CharSequence theAction, CharSequence direction) { SharedPreferences myMgrPrefs = PreferenceManager .getDefaultSharedPreferences(getBaseContext()); int len = sizeWithoutPl(myMgrPrefs); // assume string of exactly "actionX", X<10 int begin = Integer.parseInt(theAction.subSequence(6, 7).toString()); if ( ( (begin == len) && (direction == "up") ) || ( (begin == 1) && (direction == "down") ) ) { // impossible, TODO: dialog to notify of illegal action return 1; } //Log.i(TAG, "remove " + oldAction + ", move from " + begin + " to len " + len); //Log.i(TAG, "mark myMgrPrefs before: " + myMgrPrefs.getAll().toString() ); String tempAction = null; // String tempPlaylist = null; // TODO: move playlists too Editor e = myMgrPrefs.edit(); if (direction == "up") { // list is top to bottom tempAction = myMgrPrefs.getString("action" + (begin-1), "error"); e.putString("action" + (begin-1), myMgrPrefs.getString("action" + (begin), "error")); e.putString("action" + (begin), tempAction); } else { // ASSUME direction == "down" // increment tempAction = myMgrPrefs.getString("action" + (begin+1), "error"); e.putString("action" + (begin+1), myMgrPrefs.getString("action" + (begin), "error")); e.putString("action" + (begin), tempAction); } //e.remove("action"+(len-1)+"pl"); e.commit(); //Log.i(TAG, "mark myMgrPrefs after: " + myMgrPrefs.getAll().toString()); // redraw Intent myRemovePrefIntent = new Intent(getBaseContext(), mark.class); startActivity(myRemovePrefIntent); return 1; } };
diff --git a/src/frontend/org/voltdb/RestoreAgent.java b/src/frontend/org/voltdb/RestoreAgent.java index fea62edc8..1c28b07dc 100644 --- a/src/frontend/org/voltdb/RestoreAgent.java +++ b/src/frontend/org/voltdb/RestoreAgent.java @@ -1,1166 +1,1165 @@ /* This file is part of VoltDB. * Copyright (C) 2008-2011 VoltDB Inc. * * VoltDB 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. * * VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.lang.reflect.Constructor; import java.nio.ByteBuffer; 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.Map.Entry; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.FutureTask; import org.apache.zookeeper_voltpatches.CreateMode; import org.apache.zookeeper_voltpatches.KeeperException; import org.apache.zookeeper_voltpatches.KeeperException.Code; import org.apache.zookeeper_voltpatches.ZooDefs.Ids; import org.apache.zookeeper_voltpatches.ZooKeeper; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.voltdb.SystemProcedureCatalog.Config; import org.voltdb.VoltDB.START_ACTION; import org.voltdb.catalog.CommandLog; import org.voltdb.catalog.Partition; import org.voltdb.catalog.Procedure; import org.voltdb.client.ClientResponse; import org.voltdb.dtxn.TransactionInitiator; import org.voltdb.logging.VoltLogger; import org.voltdb.messaging.FastSerializable; import org.voltdb.network.Connection; import org.voltdb.network.NIOReadStream; import org.voltdb.network.WriteStream; import org.voltdb.sysprocs.saverestore.SnapshotUtil; import org.voltdb.sysprocs.saverestore.SnapshotUtil.Snapshot; import org.voltdb.sysprocs.saverestore.SnapshotUtil.TableFiles; import org.voltdb.utils.DBBPool.BBContainer; import org.voltdb.utils.DeferredSerialization; import org.voltdb.utils.EstTime; import org.voltdb.utils.MiscUtils; import org.voltdb.utils.Pair; /** * An agent responsible for the whole restore process when the cluster starts * up. It performs the following tasks in order, * * - Try to restore the last snapshot * - Try to replay all command logs * - Take a snapshot if command logs were replayed to truncate them * * Once all of these tasks have finished successfully, it will call RealVoltDB * to resume normal operation. */ public class RestoreAgent implements CommandLogReinitiator.Callback, SnapshotCompletionInterest { // Implement this callback to get notified when restore finishes. public interface Callback { /** * Callback function executed when restore finishes. * * @param txnId * The txnId of the truncation snapshot at the end of the * restore, or Long.MIN if there is none. * @param initCommandLog * Whether or not to initialize the command log module */ public void onRestoreCompletion(long txnId, boolean initCommandLog); } private final static VoltLogger LOG = new VoltLogger("HOST"); // ZK stuff private final static String RESTORE = "/restore"; private final static String RESTORE_BARRIER = "/restore_barrier"; private final static String SNAPSHOT_ID = "/restore/snapshot_id"; private final String zkBarrierNode; private final Integer m_hostId; private final CatalogContext m_context; private final TransactionInitiator m_initiator; private final SnapshotCompletionMonitor m_snapshotMonitor; private final Callback m_callback; private final START_ACTION m_action; // The txnId of the truncation snapshot generated at the end. private long m_truncationSnapshot = Long.MIN_VALUE; private final ZooKeeper m_zk; private final int[] m_allPartitions; // Different states the restore process can be in private enum State { RESTORE, REPLAY, TRUNCATE }; // State of the restore agent private volatile State m_state = State.RESTORE; private final RestoreAdapter m_restoreAdapter = new RestoreAdapter(); // Whether or not we have a snapshot to restore private boolean m_hasRestored = false; private CommandLogReinitiator m_replayAgent = new CommandLogReinitiator() { private Callback m_callback; @Override public void setCallback(Callback callback) { m_callback = callback; } @Override public void replay() { new Thread(new Runnable() { @Override public void run() { if (m_callback != null) { m_callback.onReplayCompletion(); } } }).start(); } @Override public void join() throws InterruptedException {} @Override public boolean hasReplayed() { return false; } @Override public Long getMinLastSeenTxn() { return null; } @Override public boolean started() { return true; } @Override public void setSnapshotTxnId(long txnId) {} @Override public void returnAllSegments() {} }; private Thread m_restoreHeartbeatThread; private Runnable m_restorePlanner = new Runnable() { @Override public void run() { createZKDirectory(RESTORE); createZKDirectory(RESTORE_BARRIER); enterRestore(); // Transaction ID of the restore sysproc final long txnId = 1l; TreeMap<Long, Snapshot> snapshots = getSnapshots(); Set<SnapshotInfo> snapshotInfos = new HashSet<SnapshotInfo>(); final Long minLastSeenTxn = m_replayAgent.getMinLastSeenTxn(); for (Entry<Long, Snapshot> e : snapshots.entrySet()) { /* * If the txn of the snapshot is before the earliest txn * among the last seen txns across all initiators when the * log starts, there is a gap in between the snapshot was * taken and the beginning of the log. So the snapshot is * not viable for replay. */ if (minLastSeenTxn != null && e.getKey() < minLastSeenTxn) { continue; } Snapshot s = e.getValue(); File digest = s.m_digests.get(0); int partitionCount = -1; boolean skip = false; for (TableFiles tf : s.m_tableFiles.values()) { if (tf.m_isReplicated) { continue; } if (skip) { break; } for (boolean completed : tf.m_completed) { if (!completed) { skip = true; break; } } // Everyone has to agree on the total partition count for (int count : tf.m_totalPartitionCounts) { if (partitionCount == -1) { partitionCount = count; } else if (count != partitionCount) { skip = true; break; } } } Long catalog_crc = null; try { JSONObject digest_detail = SnapshotUtil.CRCCheck(digest); catalog_crc = digest_detail.getLong("catalogCRC"); } catch (IOException ioe) { LOG.info("Unable to read digest file: " + digest.getAbsolutePath() + " due to: " + ioe.getMessage()); skip = true; } catch (JSONException je) { LOG.info("Unable to extract catalog CRC from digest: " + digest.getAbsolutePath() + " due to: " + je.getMessage()); skip = true; } if (skip) { continue; } SnapshotInfo info = new SnapshotInfo(e.getKey(), digest.getParent(), parseDigestFilename(digest.getName()), partitionCount, catalog_crc); for (Entry<String, TableFiles> te : s.m_tableFiles.entrySet()) { TableFiles tableFile = te.getValue(); HashSet<Integer> ids = new HashSet<Integer>(); for (Set<Integer> idSet : tableFile.m_validPartitionIds) { ids.addAll(idSet); } if (!tableFile.m_isReplicated) { info.partitions.put(te.getKey(), ids); } } snapshotInfos.add(info); } LOG.debug("Gathered " + snapshotInfos.size() + " snapshot information"); sendLocalRestoreInformation(minLastSeenTxn, snapshotInfos); // Negotiate with other hosts about which snapshot to restore String restorePath = null; String restoreNonce = null; long lastSnapshotTxnId = 0; Entry<Long, Set<SnapshotInfo>> lastSnapshot = getRestorePlan(); if (lastSnapshot != null) { LOG.debug("Snapshot to restore: " + lastSnapshot.getKey()); lastSnapshotTxnId = lastSnapshot.getKey(); Iterator<SnapshotInfo> i = lastSnapshot.getValue().iterator(); while (i.hasNext()) { SnapshotInfo next = i.next(); restorePath = next.path; restoreNonce = next.nonce; break; } assert(restorePath != null && restoreNonce != null); } /* * If this has the lowest host ID, initiate the snapshot restore */ if (isLowestHost()) { sendSnapshotTxnId(lastSnapshotTxnId); if (restorePath != null && restoreNonce != null) { LOG.debug("Initiating snapshot " + restoreNonce + " in " + restorePath); initSnapshotWork(txnId, Pair.of("@SnapshotRestore", new Object[] {restorePath, restoreNonce})); } } /* * A thread to keep on sending fake heartbeats until the restore is * complete, or otherwise the RPQ is gonna be clogged. */ m_restoreHeartbeatThread = new Thread(new Runnable() { @Override public void run() { - while (m_state == State.RESTORE || - (m_state == State.REPLAY && !m_replayAgent.started())) { + while (m_state == State.RESTORE) { m_initiator.sendHeartbeat(txnId + 1); try { Thread.sleep(500); } catch (InterruptedException e) {} } } }); m_restoreHeartbeatThread.start(); if (!isLowestHost() || restorePath == null || restoreNonce == null) { /* * Hosts that are not initiating the restore should change * state immediately */ changeState(); } } }; /** * A dummy connection to provide to the DTXN. It routes ClientResponses back * to the restore agent. */ private class RestoreAdapter implements Connection, WriteStream { @Override public boolean hadBackPressure() { throw new UnsupportedOperationException(); } @Override public boolean enqueue(BBContainer c) { throw new UnsupportedOperationException(); } @Override public boolean enqueue(FastSerializable f) { handleResponse((ClientResponse) f); return true; } @Override public boolean enqueue(FastSerializable f, int expectedSize) { return enqueue(f); } @Override public boolean enqueue(DeferredSerialization ds) { throw new UnsupportedOperationException(); } @Override public boolean enqueue(ByteBuffer b) { throw new UnsupportedOperationException(); } @Override public int calculatePendingWriteDelta(long now) { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public int getOutstandingMessageCount() { throw new UnsupportedOperationException(); } @Override public WriteStream writeStream() { return this; } @Override public NIOReadStream readStream() { throw new UnsupportedOperationException(); } @Override public void disableReadSelection() { throw new UnsupportedOperationException(); } @Override public void enableReadSelection() { throw new UnsupportedOperationException(); } @Override public String getHostname() { return ""; } @Override public long connectionId() { return -1; } @Override public void scheduleRunnable(Runnable r) { } @Override public void unregister() { } } /** * Information about the local files of a specific snapshot that will be * used to generate a restore plan */ static class SnapshotInfo { public final long txnId; public final String path; public final String nonce; public final int partitionCount; public final long catalogCrc; // All the partitions for partitioned tables in the local snapshot file public final Map<String, Set<Integer>> partitions = new TreeMap<String, Set<Integer>>(); public SnapshotInfo(long txnId, String path, String nonce, int partitions, long catalogCrc) { this.txnId = txnId; this.path = path; this.nonce = nonce; this.partitionCount = partitions; this.catalogCrc = catalogCrc; } public int size() { // I can't make this add up --izzy // txnId + pathLen + nonceLen + partCount + catalogCrc + path + nonce int size = 8 + 4 + 4 + 8 + 8 + 4 + path.length() + nonce.length(); for (Entry<String, Set<Integer>> e : partitions.entrySet()) { size += 4 + 4 + e.getKey().length() + 4 * e.getValue().size(); } return size; } } /** * Creates a ZooKeeper directory if it doesn't exist. Crashes VoltDB if the * creation fails for any reason other then the path already existing. * * @param path */ private void createZKDirectory(String path) { try { try { m_zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException e) { if (e.code() != Code.NODEEXISTS) { throw e; } } } catch (Exception e) { LOG.fatal("Failed to create Zookeeper node: " + e.getMessage()); VoltDB.crashVoltDB(); } } public RestoreAgent(CatalogContext context, TransactionInitiator initiator, ZooKeeper zk, SnapshotCompletionMonitor snapshotMonitor, Callback callback, int hostId, START_ACTION action) throws IOException { m_hostId = hostId; m_context = context; m_initiator = initiator; m_snapshotMonitor = snapshotMonitor; m_callback = callback; m_action = action; m_zk = zk; zkBarrierNode = RESTORE_BARRIER + "/" + m_hostId; m_allPartitions = new int[m_context.numberOfPartitions]; int i = 0; for (Partition p : m_context.cluster.getPartitions()) { m_allPartitions[i++] = Integer.parseInt(p.getTypeName()); } initialize(); } private void initialize() { // Load command log reinitiator try { Class<?> replayClass = MiscUtils.loadProClass("org.voltdb.CommandLogReinitiatorImpl", "Command log replay", false); if (replayClass != null) { Constructor<?> constructor = replayClass.getConstructor(int.class, START_ACTION.class, TransactionInitiator.class, CatalogContext.class, ZooKeeper.class); m_replayAgent = (CommandLogReinitiator) constructor.newInstance(m_hostId, m_action, m_initiator, m_context, m_zk); } } catch (Exception e) { LOG.fatal("Unable to instantiate command log reinitiator", e); VoltDB.crashVoltDB(); } m_replayAgent.setCallback(this); } /** * Enters the restore process. Creates ZooKeeper barrier node for this host. */ private void enterRestore() { try { m_zk.create(zkBarrierNode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } catch (Exception e) { LOG.fatal("Failed to create Zookeeper node: " + e.getMessage()); VoltDB.crashVoltDB(); } } /** * Exists the restore process. Waits for all other hosts to complete first. * This method blocks. */ private void exitRestore() { try { m_zk.delete(zkBarrierNode, -1); } catch (Exception ignore) {} LOG.debug("Waiting for all hosts to complete restore"); List<String> children = null; while (true) { try { children = m_zk.getChildren(RESTORE_BARRIER, false); } catch (KeeperException e2) { LOG.fatal(e2.getMessage()); VoltDB.crashVoltDB(); } catch (InterruptedException e2) { continue; } if (children.size() > 0) { try { Thread.sleep(500); } catch (InterruptedException e) {} } else { break; } } } /** * Start the restore process. It will first try to restore from the last * snapshot, then replay the logs, followed by a snapshot to truncate the * logs. This method won't block. */ public void restore() { new Thread(m_restorePlanner, "restore-planner").start(); } /** * Send the txnId of the snapshot that was picked to restore from to the * other hosts. If there was no snapshot to restore from, send 0. * * @param txnId */ private void sendSnapshotTxnId(long txnId) { ByteBuffer buf = ByteBuffer.allocate(8); buf.putLong(txnId); LOG.debug("Sending snapshot ID " + txnId + " for restore to other nodes"); try { m_zk.create(SNAPSHOT_ID, buf.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } catch (Exception e) { LOG.fatal("Failed to create Zookeeper node: " + e.getMessage()); VoltDB.crashVoltDB(); } } /** * Wait for the specified host to send the txnId of the snapshot the cluster * is restoring from. */ private void waitForSnapshotTxnId() { long txnId = 0; while (true) { LOG.debug("Waiting for the initiator to send the snapshot txnid"); try { if (m_zk.exists(SNAPSHOT_ID, false) == null) { Thread.sleep(500); continue; } else { byte[] data = m_zk.getData(SNAPSHOT_ID, false, null); txnId = ByteBuffer.wrap(data).getLong(); break; } } catch (KeeperException e2) { LOG.fatal(e2.getMessage()); VoltDB.crashVoltDB(); } catch (InterruptedException e2) { continue; } } // If the txnId is not 0, it means we restored a snapshot if (txnId != 0) { m_hasRestored = true; } m_replayAgent.setSnapshotTxnId(txnId); } /** * Send the information about the local snapshot files to the other hosts to * generate restore plan. * * @param min * The minimum txnId of the last txn across all initiators in the * local command log. * @param snapshots * The information of the local snapshot files. */ private void sendLocalRestoreInformation(Long min, Set<SnapshotInfo> snapshots) { ByteBuffer buf = serializeRestoreInformation(min, snapshots); String zkNode = RESTORE + "/" + m_hostId; try { m_zk.create(zkNode, buf.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL); } catch (Exception e) { LOG.fatal("Failed to create Zookeeper node: " + e.getMessage()); VoltDB.crashVoltDB(); } } /** * @param clStartTxnId The TXN ID at which the command log starts. * NULL means no command log exists. * Long.MIN_VALUE means the command log has no * associated snapshot. * @param snapshotFragments A map of the TXNID/SnapshotInfo reported by * the other hosts in the cluster. Will be * modified as snapshots are removed because * they are not compatible with the command log * @return Whether or not any of the snapshots matched the current * catalog's CRC check when there was a command log to replay */ static boolean currySnapshotInfo(Long clStartTxnId, long currentCatalogCrc, Map<Long, Set<SnapshotInfo>> snapshotFragments) { boolean crc_catalog_match = false; if (clStartTxnId != null && clStartTxnId == Long.MIN_VALUE) { // command log has no snapshot requirement. Just clear out the // fragment set directly snapshotFragments.clear(); // Quick hack. replace with command log catalog crc check crc_catalog_match = true; } else { // Filter all snapshots that are not viable Iterator<Long> iter = snapshotFragments.keySet().iterator(); while (iter.hasNext()) { Long txnId = iter.next(); long this_crc = snapshotFragments.get(txnId).iterator().next().catalogCrc; if (this_crc == currentCatalogCrc) { crc_catalog_match = true; } if (clStartTxnId != null && (this_crc != currentCatalogCrc || txnId < clStartTxnId)) { iter.remove(); } } } return crc_catalog_match; } /** * Pick the snapshot to restore from based on the global snapshot * information. * * @return The snapshot to restore from, null if none. */ private Entry<Long, Set<SnapshotInfo>> getRestorePlan() { /* * Only let the first host do the rest, so we don't end up having * multiple hosts trying to initiate a snapshot restore */ if (!isLowestHost()) { return null; } LOG.debug("Waiting for all hosts to send their snapshot information"); List<String> children = null; while (true) { try { children = m_zk.getChildren(RESTORE, false); } catch (KeeperException e2) { LOG.fatal(e2.getMessage()); VoltDB.crashVoltDB(); } catch (InterruptedException e2) { continue; } Set<Integer> liveHosts = m_context.siteTracker.getAllLiveHosts(); if (children.size() < liveHosts.size()) { try { Thread.sleep(500); } catch (InterruptedException e1) {} } else { break; } } if (children == null) { LOG.fatal("Unable to read agreement messages from other hosts for" + " restore plan"); VoltDB.crashVoltDB(); } TreeMap<Long, Set<SnapshotInfo>> snapshotFragments = new TreeMap<Long, Set<SnapshotInfo>>(); Long clStartTxnId = deserializeRestoreInformation(children, snapshotFragments); // If we're not recovering, skip the rest if (m_action == START_ACTION.CREATE) { return null; } boolean crc_catalog_match = false; // Eliminate any snapshot fragments that don't match our command log (if we have one) crc_catalog_match = currySnapshotInfo(clStartTxnId, m_context.catalogCRC, snapshotFragments); // If we have a command log and it requires a snapshot, then bail if // there's no good snapshot if ((clStartTxnId != null && clStartTxnId != Long.MIN_VALUE) && snapshotFragments.size() == 0) { if (!crc_catalog_match) { LOG.fatal("No snapshot present that matches the loaded catalog."); } LOG.fatal("No viable snapshots to restore"); VoltDB.crashVoltDB(); } LOG.debug("There are " + snapshotFragments.size() + " snapshots available in the cluster"); // Find the last complete snapshot and use it HashMap<Long, Map<String, Set<Integer>>> snapshotTablePartitions = new HashMap<Long, Map<String,Set<Integer>>>(); Iterator<Entry<Long, Set<SnapshotInfo>>> it = snapshotFragments.entrySet().iterator(); while (it.hasNext()) { Entry<Long, Set<SnapshotInfo>> e = it.next(); long txnId = e.getKey(); Map<String, Set<Integer>> tablePartitions = snapshotTablePartitions.get(txnId); if (tablePartitions == null) { tablePartitions = new HashMap<String, Set<Integer>>(); snapshotTablePartitions.put(txnId, tablePartitions); } int totalPartitions = -1; boolean inconsistent = false; Set<SnapshotInfo> fragments = e.getValue(); for (SnapshotInfo s : fragments) { if (totalPartitions == -1) { totalPartitions = s.partitionCount; } else if (totalPartitions != s.partitionCount) { inconsistent = true; break; } for (Entry<String, Set<Integer>> entry : s.partitions.entrySet()) { Set<Integer> partitions = tablePartitions.get(entry.getKey()); if (partitions == null) { tablePartitions.put(entry.getKey(), entry.getValue()); } else { partitions.addAll(entry.getValue()); } } if (inconsistent) { break; } } // Check if we have all the partitions for (Set<Integer> partitions : tablePartitions.values()) { if (partitions.size() != totalPartitions) { inconsistent = true; break; } } if (inconsistent) { it.remove(); } } if (clStartTxnId != null && clStartTxnId > 0 && snapshotFragments.size() == 0) { LOG.fatal("No viable snapshots to restore"); VoltDB.crashVoltDB(); } return snapshotFragments.lastEntry(); } /** * @param children * @param snapshotFragments * @return null if there is no log to replay in the whole cluster */ private Long deserializeRestoreInformation(List<String> children, Map<Long, Set<SnapshotInfo>> snapshotFragments) { byte recover = (byte) m_action.ordinal(); Long clStartTxnId = null; ByteBuffer buf; for (String node : children) { byte[] data = null; try { data = m_zk.getData(RESTORE + "/" + node, false, null); } catch (Exception e) { LOG.fatal(e.getMessage()); VoltDB.crashVoltDB(); } buf = ByteBuffer.wrap(data); // Check if there is log to replay boolean hasLog = buf.get() == 1; if (hasLog) { long minTxnId = buf.getLong(); if (clStartTxnId == null || minTxnId > clStartTxnId) { clStartTxnId = minTxnId; } } byte recoverByte = buf.get(); if (recoverByte != recover) { LOG.fatal("Database actions are not consistent, please enter " + "the same database action on the command-line."); VoltDB.crashVoltDB(); } int count = buf.getInt(); for (int i = 0; i < count; i++) { long txnId = buf.getLong(); Set<SnapshotInfo> fragments = snapshotFragments.get(txnId); if (fragments == null) { fragments = new HashSet<SnapshotInfo>(); snapshotFragments.put(txnId, fragments); } long catalogCrc = buf.getLong(); int len = buf.getInt(); byte[] nonceBytes = new byte[len]; buf.get(nonceBytes); len = buf.getInt(); byte[] pathBytes = new byte[len]; buf.get(pathBytes); int totalPartitionCount = buf.getInt(); SnapshotInfo info = new SnapshotInfo(txnId, new String(pathBytes), new String(nonceBytes), totalPartitionCount, catalogCrc); fragments.add(info); int tableCount = buf.getInt(); for (int j = 0; j < tableCount; j++) { len = buf.getInt(); byte[] tableNameBytes = new byte[len]; buf.get(tableNameBytes); int partitionCount = buf.getInt(); HashSet<Integer> partitions = new HashSet<Integer>(partitionCount); info.partitions.put(new String(tableNameBytes), partitions); for (int k = 0; k < partitionCount; k++) { partitions.add(buf.getInt()); } } } } return clStartTxnId; } /** * @param min * @param snapshots * @return */ private ByteBuffer serializeRestoreInformation(Long min, Set<SnapshotInfo> snapshots) { // hasLog + recover + snapshotCount int size = 1 + 1 + 4; if (min != null) { // we need to add the size of the min number to the total size size += 8; } for (SnapshotInfo i : snapshots) { size += i.size(); } ByteBuffer buf = ByteBuffer.allocate(size); if (min == null) { buf.put((byte) 0); } else { buf.put((byte) 1); buf.putLong(min); } // 1 means recover, 0 means to create new DB buf.put((byte) m_action.ordinal()); buf.putInt(snapshots.size()); for (SnapshotInfo snapshot : snapshots) { buf.putLong(snapshot.txnId); buf.putLong(snapshot.catalogCrc); buf.putInt(snapshot.nonce.length()); buf.put(snapshot.nonce.getBytes()); buf.putInt(snapshot.path.length()); buf.put(snapshot.path.getBytes()); buf.putInt(snapshot.partitionCount); buf.putInt(snapshot.partitions.size()); for (Entry<String, Set<Integer>> p : snapshot.partitions.entrySet()) { buf.putInt(p.getKey().length()); buf.put(p.getKey().getBytes()); buf.putInt(p.getValue().size()); for (int id : p.getValue()) { buf.putInt(id); } } } return buf; } /** * Initiate a snapshot action to truncate the logs. This should only be * called by one initiator. * * @param txnId * The transaction ID of the SPI to generate * @param invocation * The invocation used to create the SPI */ private void initSnapshotWork(Long txnId, final Pair<String, Object[]> invocation) { Config restore = SystemProcedureCatalog.listing.get(invocation.getFirst()); Procedure restoreProc = restore.asCatalogProcedure(); StoredProcedureInvocation spi = new StoredProcedureInvocation(); spi.procName = invocation.getFirst(); spi.params = new FutureTask<ParameterSet>(new Callable<ParameterSet>() { @Override public ParameterSet call() throws Exception { ParameterSet params = new ParameterSet(); params.setParameters(invocation.getSecond()); return params; } }); if (txnId == null) { m_initiator.createTransaction(-1, "CommandLog", true, spi, restoreProc.getReadonly(), restoreProc.getSinglepartition(), restoreProc.getEverysite(), m_allPartitions, m_allPartitions.length, m_restoreAdapter, 0, EstTime.currentTimeMillis()); } else { m_initiator.createTransaction(-1, "CommandLog", true, txnId, spi, restoreProc.getReadonly(), restoreProc.getSinglepartition(), restoreProc.getEverysite(), m_allPartitions, m_allPartitions.length, m_restoreAdapter, 0, EstTime.currentTimeMillis()); } } private void handleResponse(ClientResponse res) { boolean failure = false; if (res.getStatus() != ClientResponse.SUCCESS) { failure = true; } VoltTable[] results = res.getResults(); if (results == null || results.length != 1) { failure = true; } while (!failure && results[0].advanceRow()) { String resultStatus = results[0].getString("RESULT"); if (!resultStatus.equalsIgnoreCase("success")) { failure = true; } } if (failure) { LOG.fatal("Failed to restore from snapshot: " + res.getStatusString()); VoltDB.crashVoltDB(); } else { changeState(); } } /** * Change the state of the restore agent based on the current state. */ private void changeState() { if (m_state == State.RESTORE) { waitForSnapshotTxnId(); exitRestore(); m_state = State.REPLAY; /* * Add the interest here so that we can use the barriers in replay * agent to synchronize. */ m_snapshotMonitor.addInterest(this); m_replayAgent.replay(); } else if (m_state == State.REPLAY) { m_state = State.TRUNCATE; } else if (m_state == State.TRUNCATE) { m_snapshotMonitor.removeInterest(this); try { m_restoreHeartbeatThread.join(); } catch (InterruptedException e) {} if (m_callback != null) { m_callback.onRestoreCompletion(m_truncationSnapshot, true); } } } @Override public void onReplayCompletion() { if (!m_hasRestored && !m_replayAgent.hasReplayed() && m_action == START_ACTION.RECOVER) { /* * This means we didn't restore any snapshot, and there's no command * log to replay. But the user asked for recover */ LOG.fatal("Nothing to recover from"); VoltDB.crashVoltDB(); } else if (!m_replayAgent.hasReplayed()) { // Nothing was replayed, so no need to initiate truncation snapshot m_state = State.TRUNCATE; } changeState(); if (m_replayAgent.hasReplayed()) { /* * If this has the lowest host ID, initiate the snapshot that * will truncate the logs */ CommandLog commandLogElement = m_context.cluster.getLogconfig().get("log"); if (isLowestHost() && commandLogElement != null) { try { try { m_zk.create("/truncation_snapshot_path", commandLogElement.getInternalsnapshotpath().getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException e) {} m_zk.create("/request_truncation_snapshot", null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (Exception e) { LOG.fatal("Requesting a truncation snapshot via ZK should always succeed", e); VoltDB.crashVoltDB(); } } } } private boolean isLowestHost() { // If this is null, it must be running test if (m_hostId != null) { int lowestSite = m_context.siteTracker.getLowestLiveNonExecSiteId(); int lowestHost = m_context.siteTracker.getHostForSite(lowestSite); return m_hostId == lowestHost; } else { return false; } } /** * Finds all the snapshots in all the places we know of which could possibly * store snapshots, like command log snapshots, auto snapshots, etc. * * @return All snapshots */ private TreeMap<Long, Snapshot> getSnapshots() { /* * Use the individual snapshot directories instead of voltroot, because * they can be set individually */ List<String> paths = new ArrayList<String>(); CommandLog commandLogElement = m_context.cluster.getLogconfig().get("log"); if (commandLogElement != null) { paths.add(commandLogElement.getInternalsnapshotpath()); } if (m_context.cluster.getDatabases().get("database").getSnapshotschedule().get("default") != null) { paths.add(m_context.cluster.getDatabases().get("database").getSnapshotschedule().get("default").getPath()); } TreeMap<Long, Snapshot> snapshots = new TreeMap<Long, Snapshot>(); FileFilter filter = new SnapshotUtil.SnapshotFilter(); for (String path : paths) { SnapshotUtil.retrieveSnapshotFiles(new File(path), snapshots, filter, 0, true); } return snapshots; } /** * Get the nonce from the filename of the digest file. * @param filename The filename of the digest file * @return The nonce */ private static String parseDigestFilename(String filename) { if (filename == null || !filename.endsWith(".digest")) { throw new IllegalArgumentException(); } String nonce = filename.substring(0, filename.indexOf(".digest")); if (nonce.contains("-host_")) { nonce = nonce.substring(0, nonce.indexOf("-host_")); } return nonce; } /** * All nodes will be notified about the completion of the truncation * snapshot. */ @Override public CountDownLatch snapshotCompleted(long txnId, boolean truncationSnapshot) { if (!truncationSnapshot) { LOG.fatal("Failed to truncate command logs by snapshot"); VoltDB.crashVoltDB(); } else { m_truncationSnapshot = txnId; m_replayAgent.returnAllSegments(); changeState(); } return new CountDownLatch(0); } }
true
true
public void run() { createZKDirectory(RESTORE); createZKDirectory(RESTORE_BARRIER); enterRestore(); // Transaction ID of the restore sysproc final long txnId = 1l; TreeMap<Long, Snapshot> snapshots = getSnapshots(); Set<SnapshotInfo> snapshotInfos = new HashSet<SnapshotInfo>(); final Long minLastSeenTxn = m_replayAgent.getMinLastSeenTxn(); for (Entry<Long, Snapshot> e : snapshots.entrySet()) { /* * If the txn of the snapshot is before the earliest txn * among the last seen txns across all initiators when the * log starts, there is a gap in between the snapshot was * taken and the beginning of the log. So the snapshot is * not viable for replay. */ if (minLastSeenTxn != null && e.getKey() < minLastSeenTxn) { continue; } Snapshot s = e.getValue(); File digest = s.m_digests.get(0); int partitionCount = -1; boolean skip = false; for (TableFiles tf : s.m_tableFiles.values()) { if (tf.m_isReplicated) { continue; } if (skip) { break; } for (boolean completed : tf.m_completed) { if (!completed) { skip = true; break; } } // Everyone has to agree on the total partition count for (int count : tf.m_totalPartitionCounts) { if (partitionCount == -1) { partitionCount = count; } else if (count != partitionCount) { skip = true; break; } } } Long catalog_crc = null; try { JSONObject digest_detail = SnapshotUtil.CRCCheck(digest); catalog_crc = digest_detail.getLong("catalogCRC"); } catch (IOException ioe) { LOG.info("Unable to read digest file: " + digest.getAbsolutePath() + " due to: " + ioe.getMessage()); skip = true; } catch (JSONException je) { LOG.info("Unable to extract catalog CRC from digest: " + digest.getAbsolutePath() + " due to: " + je.getMessage()); skip = true; } if (skip) { continue; } SnapshotInfo info = new SnapshotInfo(e.getKey(), digest.getParent(), parseDigestFilename(digest.getName()), partitionCount, catalog_crc); for (Entry<String, TableFiles> te : s.m_tableFiles.entrySet()) { TableFiles tableFile = te.getValue(); HashSet<Integer> ids = new HashSet<Integer>(); for (Set<Integer> idSet : tableFile.m_validPartitionIds) { ids.addAll(idSet); } if (!tableFile.m_isReplicated) { info.partitions.put(te.getKey(), ids); } } snapshotInfos.add(info); } LOG.debug("Gathered " + snapshotInfos.size() + " snapshot information"); sendLocalRestoreInformation(minLastSeenTxn, snapshotInfos); // Negotiate with other hosts about which snapshot to restore String restorePath = null; String restoreNonce = null; long lastSnapshotTxnId = 0; Entry<Long, Set<SnapshotInfo>> lastSnapshot = getRestorePlan(); if (lastSnapshot != null) { LOG.debug("Snapshot to restore: " + lastSnapshot.getKey()); lastSnapshotTxnId = lastSnapshot.getKey(); Iterator<SnapshotInfo> i = lastSnapshot.getValue().iterator(); while (i.hasNext()) { SnapshotInfo next = i.next(); restorePath = next.path; restoreNonce = next.nonce; break; } assert(restorePath != null && restoreNonce != null); } /* * If this has the lowest host ID, initiate the snapshot restore */ if (isLowestHost()) { sendSnapshotTxnId(lastSnapshotTxnId); if (restorePath != null && restoreNonce != null) { LOG.debug("Initiating snapshot " + restoreNonce + " in " + restorePath); initSnapshotWork(txnId, Pair.of("@SnapshotRestore", new Object[] {restorePath, restoreNonce})); } } /* * A thread to keep on sending fake heartbeats until the restore is * complete, or otherwise the RPQ is gonna be clogged. */ m_restoreHeartbeatThread = new Thread(new Runnable() { @Override public void run() { while (m_state == State.RESTORE || (m_state == State.REPLAY && !m_replayAgent.started())) { m_initiator.sendHeartbeat(txnId + 1); try { Thread.sleep(500); } catch (InterruptedException e) {} } } }); m_restoreHeartbeatThread.start(); if (!isLowestHost() || restorePath == null || restoreNonce == null) { /* * Hosts that are not initiating the restore should change * state immediately */ changeState(); } }
public void run() { createZKDirectory(RESTORE); createZKDirectory(RESTORE_BARRIER); enterRestore(); // Transaction ID of the restore sysproc final long txnId = 1l; TreeMap<Long, Snapshot> snapshots = getSnapshots(); Set<SnapshotInfo> snapshotInfos = new HashSet<SnapshotInfo>(); final Long minLastSeenTxn = m_replayAgent.getMinLastSeenTxn(); for (Entry<Long, Snapshot> e : snapshots.entrySet()) { /* * If the txn of the snapshot is before the earliest txn * among the last seen txns across all initiators when the * log starts, there is a gap in between the snapshot was * taken and the beginning of the log. So the snapshot is * not viable for replay. */ if (minLastSeenTxn != null && e.getKey() < minLastSeenTxn) { continue; } Snapshot s = e.getValue(); File digest = s.m_digests.get(0); int partitionCount = -1; boolean skip = false; for (TableFiles tf : s.m_tableFiles.values()) { if (tf.m_isReplicated) { continue; } if (skip) { break; } for (boolean completed : tf.m_completed) { if (!completed) { skip = true; break; } } // Everyone has to agree on the total partition count for (int count : tf.m_totalPartitionCounts) { if (partitionCount == -1) { partitionCount = count; } else if (count != partitionCount) { skip = true; break; } } } Long catalog_crc = null; try { JSONObject digest_detail = SnapshotUtil.CRCCheck(digest); catalog_crc = digest_detail.getLong("catalogCRC"); } catch (IOException ioe) { LOG.info("Unable to read digest file: " + digest.getAbsolutePath() + " due to: " + ioe.getMessage()); skip = true; } catch (JSONException je) { LOG.info("Unable to extract catalog CRC from digest: " + digest.getAbsolutePath() + " due to: " + je.getMessage()); skip = true; } if (skip) { continue; } SnapshotInfo info = new SnapshotInfo(e.getKey(), digest.getParent(), parseDigestFilename(digest.getName()), partitionCount, catalog_crc); for (Entry<String, TableFiles> te : s.m_tableFiles.entrySet()) { TableFiles tableFile = te.getValue(); HashSet<Integer> ids = new HashSet<Integer>(); for (Set<Integer> idSet : tableFile.m_validPartitionIds) { ids.addAll(idSet); } if (!tableFile.m_isReplicated) { info.partitions.put(te.getKey(), ids); } } snapshotInfos.add(info); } LOG.debug("Gathered " + snapshotInfos.size() + " snapshot information"); sendLocalRestoreInformation(minLastSeenTxn, snapshotInfos); // Negotiate with other hosts about which snapshot to restore String restorePath = null; String restoreNonce = null; long lastSnapshotTxnId = 0; Entry<Long, Set<SnapshotInfo>> lastSnapshot = getRestorePlan(); if (lastSnapshot != null) { LOG.debug("Snapshot to restore: " + lastSnapshot.getKey()); lastSnapshotTxnId = lastSnapshot.getKey(); Iterator<SnapshotInfo> i = lastSnapshot.getValue().iterator(); while (i.hasNext()) { SnapshotInfo next = i.next(); restorePath = next.path; restoreNonce = next.nonce; break; } assert(restorePath != null && restoreNonce != null); } /* * If this has the lowest host ID, initiate the snapshot restore */ if (isLowestHost()) { sendSnapshotTxnId(lastSnapshotTxnId); if (restorePath != null && restoreNonce != null) { LOG.debug("Initiating snapshot " + restoreNonce + " in " + restorePath); initSnapshotWork(txnId, Pair.of("@SnapshotRestore", new Object[] {restorePath, restoreNonce})); } } /* * A thread to keep on sending fake heartbeats until the restore is * complete, or otherwise the RPQ is gonna be clogged. */ m_restoreHeartbeatThread = new Thread(new Runnable() { @Override public void run() { while (m_state == State.RESTORE) { m_initiator.sendHeartbeat(txnId + 1); try { Thread.sleep(500); } catch (InterruptedException e) {} } } }); m_restoreHeartbeatThread.start(); if (!isLowestHost() || restorePath == null || restoreNonce == null) { /* * Hosts that are not initiating the restore should change * state immediately */ changeState(); } }
diff --git a/stripes/src/net/sourceforge/stripes/tag/LinkTag.java b/stripes/src/net/sourceforge/stripes/tag/LinkTag.java index 11cb483..9d57ba5 100644 --- a/stripes/src/net/sourceforge/stripes/tag/LinkTag.java +++ b/stripes/src/net/sourceforge/stripes/tag/LinkTag.java @@ -1,118 +1,121 @@ /* Copyright 2005-2006 Tim Fennell * * 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 net.sourceforge.stripes.tag; import net.sourceforge.stripes.exception.StripesJspException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.BodyTag; import java.io.IOException; /** * Tag for generating links to pages or ActionBeans within a Stripes application. Provides * basic services such as including the context path at the start of the href URL (only * when the URL starts with a '/' and does not contain the context path already), and * including a parameter to name the source page from which the link came. Also provides the * ability to add complex parameters to the URL through the use of nested Param tags. * * @see ParamTag * @author Tim Fennell */ public class LinkTag extends LinkTagSupport implements BodyTag { /** * Does nothing. * @return EVAL_BODY_BUFFERED in all cases */ @Override public int doStartTag() throws JspException { return EVAL_BODY_BUFFERED; } /** Does nothing. */ public void doInitBody() throws JspException { /* Do Nothing. */ } /** * Does nothing. * @return SKIP_BODY in all cases */ public int doAfterBody() throws JspException { return SKIP_BODY; } /** * Prepends the context to the href attribute if necessary, and then folds all the * registered parameters into the URL. * * @return EVAL_PAGE in all cases * @throws JspException */ @Override public int doEndTag() throws JspException { try { set("href", buildUrl()); writeOpenTag(getPageContext().getOut(), "a"); String body = getBodyContentAsString(); + if (body == null) { + body = get("href"); + } if (body != null) { getPageContext().getOut().write(body.trim()); } writeCloseTag(getPageContext().getOut(), "a"); } catch (IOException ioe) { throw new StripesJspException("IOException while writing output in LinkTag.", ioe); } // Restore state and go on with the page getAttributes().remove("href"); clearParameters(); return EVAL_PAGE; } /** Pass through to {@link LinkTagSupport#setUrl(String)}. */ public void setHref(String href) { setUrl(href); } /** Pass through to {@link LinkTagSupport#getUrl()}. */ public String getHref() { return getUrl(); } /////////////////////////////////////////////////////////////////////////// // Additional HTML Attributes supported by the tag /////////////////////////////////////////////////////////////////////////// public void setCharset(String charset) { set("charset", charset); } public String getCharset() { return get("charset"); } public void setCoords(String coords) { set("coords", coords); } public String getCoords() { return get("coords"); } public void setHreflang(String hreflang) { set("hreflang", hreflang); } public String getHreflang() { return get("hreflang"); } public void setName(String name) { set("name", name); } public String getName() { return get("name"); } public void setRel(String rel) { set("rel", rel); } public String getRel() { return get("rel"); } public void setRev(String rev) { set("rev", rev); } public String getRev() { return get("rev"); } public void setShape(String shape) { set("shape", shape); } public String getShape() { return get("shape"); } public void setTarget(String target) { set("target", target); } public String getTarget() { return get("target"); } public void setType(String type) { set("type", type); } public String getType() { return get("type"); } }
true
true
public int doEndTag() throws JspException { try { set("href", buildUrl()); writeOpenTag(getPageContext().getOut(), "a"); String body = getBodyContentAsString(); if (body != null) { getPageContext().getOut().write(body.trim()); } writeCloseTag(getPageContext().getOut(), "a"); } catch (IOException ioe) { throw new StripesJspException("IOException while writing output in LinkTag.", ioe); } // Restore state and go on with the page getAttributes().remove("href"); clearParameters(); return EVAL_PAGE; }
public int doEndTag() throws JspException { try { set("href", buildUrl()); writeOpenTag(getPageContext().getOut(), "a"); String body = getBodyContentAsString(); if (body == null) { body = get("href"); } if (body != null) { getPageContext().getOut().write(body.trim()); } writeCloseTag(getPageContext().getOut(), "a"); } catch (IOException ioe) { throw new StripesJspException("IOException while writing output in LinkTag.", ioe); } // Restore state and go on with the page getAttributes().remove("href"); clearParameters(); return EVAL_PAGE; }
diff --git a/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/application/study/FileColumnTest.java b/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/application/study/FileColumnTest.java index e944baa3f..8620077fa 100644 --- a/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/application/study/FileColumnTest.java +++ b/caintegrator2-war/test/src/gov/nih/nci/caintegrator2/application/study/FileColumnTest.java @@ -1,170 +1,169 @@ /** * The software subject to this notice and license includes both human readable * source code form and machine readable, binary, object code form. The caIntegrator2 * Software was developed in conjunction with the National Cancer Institute * (NCI) by NCI employees, 5AM Solutions, Inc. (5AM), ScenPro, Inc. (ScenPro) * and Science Applications International Corporation (SAIC). To the extent * government employees are authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * * This caIntegrator2 Software License (the License) is between NCI and You. You (or * Your) shall mean a person or an entity, and all other entities that control, * are controlled by, or are under common control with the entity. Control for * purposes of this definition means (i) the direct or indirect power to cause * the direction or management of such entity, whether by contract or otherwise, * or (ii) ownership of fifty percent (50%) or more of the outstanding shares, * or (iii) beneficial ownership of such entity. * * This License is granted provided that You agree to the conditions described * below. NCI grants You a non-exclusive, worldwide, perpetual, fully-paid-up, * no-charge, irrevocable, transferable and royalty-free right and license in * its rights in the caIntegrator2 Software to (i) use, install, access, operate, * execute, copy, modify, translate, market, publicly display, publicly perform, * and prepare derivative works of the caIntegrator2 Software; (ii) distribute and * have distributed to and by third parties the caIntegrator2 Software and any * modifications and derivative works thereof; and (iii) sublicense the * foregoing rights set out in (i) and (ii) to third parties, including the * right to license such rights to further third parties. For sake of clarity, * and not by way of limitation, NCI shall have no right of accounting or right * of payment from You or Your sub-licensees for the rights granted under this * License. This License is granted at no charge to You. * * Your redistributions of the source code for the Software must retain the * above copyright notice, this list of conditions and the disclaimer and * limitation of liability of Article 6, below. Your redistributions in object * code form must reproduce the above copyright notice, this list of conditions * and the disclaimer of Article 6 in the documentation and/or other materials * provided with the distribution, if any. * * Your end-user documentation included with the redistribution, if any, must * include the following acknowledgment: This product includes software * developed by 5AM, ScenPro, SAIC and the National Cancer Institute. If You do * not include such end-user documentation, You shall include this acknowledgment * in the Software itself, wherever such third-party acknowledgments normally * appear. * * You may not use the names "The National Cancer Institute", "NCI", "ScenPro", * "SAIC" or "5AM" to endorse or promote products derived from this Software. * This License does not authorize You to use any trademarks, service marks, * trade names, logos or product names of either NCI, ScenPro, SAID or 5AM, * except as required to comply with the terms of this License. * * For sake of clarity, and not by way of limitation, You may incorporate this * Software into Your proprietary programs and into any third party proprietary * programs. However, if You incorporate the Software into third party * proprietary programs, You agree that You are solely responsible for obtaining * any permission from such third parties required to incorporate the Software * into such third party proprietary programs and for informing Your a * sub-licensees, including without limitation Your end-users, of their * obligation to secure any required permissions from such third parties before * incorporating the Software into such third party proprietary software * programs. In the event that You fail to obtain such permissions, You agree * to indemnify NCI for any claims against NCI by such third parties, except to * the extent prohibited by law, resulting from Your failure to obtain such * permissions. * * For sake of clarity, and not by way of limitation, You may add Your own * copyright statement to Your modifications and to the derivative works, and * You may provide additional or different license terms and conditions in Your * sublicenses of modifications of the Software, or any derivative works of the * Software as a whole, provided Your use, reproduction, and distribution of the * Work otherwise complies with the conditions stated in this License. * * THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, * (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, * NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO * EVENT SHALL THE NATIONAL CANCER INSTITUTE, 5AM SOLUTIONS, INC., SCENPRO, INC., * SCIENCE APPLICATIONS INTERNATIONAL CORPORATION OR THEIR * AFFILIATES 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 gov.nih.nci.caintegrator2.application.study; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import gov.nih.nci.caintegrator2.TestDataFiles; import gov.nih.nci.caintegrator2.data.CaIntegrator2DaoStub; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Test; public class FileColumnTest { @Test public void testCompareTo() { FileColumn column0 = new FileColumn(); column0.setPosition((short) 0); column0.setId(Long.valueOf(1)); column0.setName("Test"); FileColumn column1 = new FileColumn(); column1.setPosition((short) 1); column1.setId(Long.valueOf(1)); FileColumn column2 = new FileColumn(); column2.setId(Long.valueOf(1)); column2.setPosition((short) 2); List<FileColumn> columns = new ArrayList<FileColumn>(); columns.add(column1); columns.add(column0); columns.add(column2); Collections.sort(columns); assertEquals(column0, columns.get(0)); assertEquals(column1, columns.get(1)); assertEquals(column2, columns.get(2)); } @Test public void testGetDataValues() throws ValidationException { AnnotationFile annotationFile = AnnotationFile.load(TestDataFiles.VALID_FILE, new CaIntegrator2DaoStub()); List<String> dataValues = annotationFile.getColumns().get(0).getDataValues(); assertEquals("100", dataValues.get(0)); assertEquals("101", dataValues.get(1)); dataValues = annotationFile.getColumns().get(3).getDataValues(); assertEquals("N", dataValues.get(0)); assertEquals("Y", dataValues.get(1)); } @Test public void testGetUniqueDataValues() throws ValidationException { AnnotationFile annotationFile = AnnotationFile.load(TestDataFiles.VALID_FILE, new CaIntegrator2DaoStub()); Set<String> stringDataValues = annotationFile.getColumns().get(0).getUniqueDataValues(String.class); assertTrue(stringDataValues.contains("100")); assertTrue(stringDataValues.contains("101")); Set<Double> doubleDataValues = annotationFile.getColumns().get(0).getUniqueDataValues(Double.class); assertTrue(doubleDataValues.contains(100.0)); assertTrue(doubleDataValues.contains(101.0)); Set<Date> dateDataValues = new HashSet<Date>(); try { annotationFile.getColumns().get(0).getUniqueDataValues(Date.class); fail(); } catch (ValidationException e) { // noop - should catch exception. } dateDataValues = annotationFile.getColumns().get(4).getUniqueDataValues(Date.class); - assertTrue(dateDataValues.contains(new Date(1104559200000l))); - assertTrue(dateDataValues.contains(new Date(1167631200000l))); + assertEquals(2, dateDataValues.size()); try { doubleDataValues = annotationFile.getColumns().get(4).getUniqueDataValues(Double.class); fail(); } catch (ValidationException e) { // noop - should catch exception. } } }
true
true
public void testGetUniqueDataValues() throws ValidationException { AnnotationFile annotationFile = AnnotationFile.load(TestDataFiles.VALID_FILE, new CaIntegrator2DaoStub()); Set<String> stringDataValues = annotationFile.getColumns().get(0).getUniqueDataValues(String.class); assertTrue(stringDataValues.contains("100")); assertTrue(stringDataValues.contains("101")); Set<Double> doubleDataValues = annotationFile.getColumns().get(0).getUniqueDataValues(Double.class); assertTrue(doubleDataValues.contains(100.0)); assertTrue(doubleDataValues.contains(101.0)); Set<Date> dateDataValues = new HashSet<Date>(); try { annotationFile.getColumns().get(0).getUniqueDataValues(Date.class); fail(); } catch (ValidationException e) { // noop - should catch exception. } dateDataValues = annotationFile.getColumns().get(4).getUniqueDataValues(Date.class); assertTrue(dateDataValues.contains(new Date(1104559200000l))); assertTrue(dateDataValues.contains(new Date(1167631200000l))); try { doubleDataValues = annotationFile.getColumns().get(4).getUniqueDataValues(Double.class); fail(); } catch (ValidationException e) { // noop - should catch exception. } }
public void testGetUniqueDataValues() throws ValidationException { AnnotationFile annotationFile = AnnotationFile.load(TestDataFiles.VALID_FILE, new CaIntegrator2DaoStub()); Set<String> stringDataValues = annotationFile.getColumns().get(0).getUniqueDataValues(String.class); assertTrue(stringDataValues.contains("100")); assertTrue(stringDataValues.contains("101")); Set<Double> doubleDataValues = annotationFile.getColumns().get(0).getUniqueDataValues(Double.class); assertTrue(doubleDataValues.contains(100.0)); assertTrue(doubleDataValues.contains(101.0)); Set<Date> dateDataValues = new HashSet<Date>(); try { annotationFile.getColumns().get(0).getUniqueDataValues(Date.class); fail(); } catch (ValidationException e) { // noop - should catch exception. } dateDataValues = annotationFile.getColumns().get(4).getUniqueDataValues(Date.class); assertEquals(2, dateDataValues.size()); try { doubleDataValues = annotationFile.getColumns().get(4).getUniqueDataValues(Double.class); fail(); } catch (ValidationException e) { // noop - should catch exception. } }
diff --git a/src/com/tortel/deploytrack/CreateActivity.java b/src/com/tortel/deploytrack/CreateActivity.java index ba9545c..741d194 100644 --- a/src/com/tortel/deploytrack/CreateActivity.java +++ b/src/com/tortel/deploytrack/CreateActivity.java @@ -1,297 +1,299 @@ /* * Copyright (C) 2013 Scott Warner * * 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.tortel.deploytrack; import java.text.SimpleDateFormat; import java.util.Calendar; import android.annotation.SuppressLint; import android.graphics.Color; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragmentActivity; import com.actionbarsherlock.view.MenuItem; import com.fourmob.datetimepicker.date.DatePickerDialog; import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener; import com.larswerkman.colorpicker.ColorPicker; import com.larswerkman.colorpicker.ColorPicker.OnColorChangedListener; import com.tortel.deploytrack.data.*; /** * Activity for creating and editing a Deployment */ public class CreateActivity extends SherlockFragmentActivity { private static final String KEY_TIME_START = "start"; private static final String KEY_TIME_END = "end"; private static final String KEY_SET_START = "startset"; private static final String KEY_SET_END = "endset"; private static final String KEY_NAME = "name"; private static final String KEY_COLOR_COMPLETED = "completed"; private static final String KEY_COLOR_REMAINING = "remaining"; private EditText nameEdit; private Button startButton; private Button endButton; private Button saveButton; private SimpleDateFormat format; //Colors private int completedColor; private int remainingColor; //Date range private Calendar start; private Calendar end; //Flags for dates private boolean startSet; private boolean endSet; //The data to save; private Deployment deployment; @SuppressLint("SimpleDateFormat") @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_create); getSupportActionBar().setDisplayHomeAsUpEnabled(true); format = new SimpleDateFormat("MMM dd, yyyy"); nameEdit = (EditText) findViewById(R.id.name); startButton = (Button) findViewById(R.id.button_start); endButton = (Button) findViewById(R.id.button_end); saveButton = (Button) findViewById(R.id.button_save); //Color pickers ColorPicker completedPicker = (ColorPicker) findViewById(R.id.picker_completed); ColorPicker remainingPicker = (ColorPicker) findViewById(R.id.picker_remain); int id = getIntent().getIntExtra("id", -1); if(id >= 0){ //Starting in edit mode, load the old data deployment = DatabaseManager.getInstance(this).getDeployment(id); //Set the colors completedColor = deployment.getCompletedColor(); remainingColor = deployment.getRemainingColor(); //Set the dates start = Calendar.getInstance(); end = Calendar.getInstance(); start.setTimeInMillis(deployment.getStartDate().getTime()); end.setTimeInMillis(deployment.getEndDate().getTime()); startSet = true; endSet = true; //Set the buttons startButton.setText(getResources().getString(R.string.start_date)+ "\n"+format.format(start.getTime())); endButton.setText(getResources().getString(R.string.end_date)+ "\n"+format.format(end.getTime())); //Set the name nameEdit.setText(deployment.getName()); getSupportActionBar().setTitle(R.string.edit); } else { deployment = new Deployment(); disableButton(endButton); disableButton(saveButton); start = Calendar.getInstance(); end = (Calendar) start.clone(); startSet = false; endSet = false; completedColor = Color.GREEN; remainingColor = Color.RED; getSupportActionBar().setTitle(R.string.add_new); } //If restore from rotation if(savedInstanceState != null){ start.setTimeInMillis(savedInstanceState.getLong(KEY_TIME_START)); end.setTimeInMillis(savedInstanceState.getLong(KEY_TIME_END)); startSet = savedInstanceState.getBoolean(KEY_SET_START); endSet = savedInstanceState.getBoolean(KEY_SET_END); nameEdit.setText(savedInstanceState.getString(KEY_NAME)); completedColor = savedInstanceState.getInt(KEY_COLOR_COMPLETED); remainingColor = savedInstanceState.getInt(KEY_COLOR_REMAINING); //Set the date buttons, if set if(startSet){ startButton.setText(getResources().getString(R.string.start_date)+ "\n"+format.format(start.getTime())); enableButton(endButton); } if(endSet && end.after(start)){ endButton.setText(getResources().getString(R.string.end_date)+ "\n"+format.format(end.getTime())); enableButton(saveButton); } } remainingPicker.setColor(remainingColor); + remainingPicker.setOldCenterColor(remainingColor); remainingPicker.setOnColorChangedListener(new RemainingColorChangeListener()); completedPicker.setColor(completedColor); + completedPicker.setOldCenterColor(completedColor); completedPicker.setOnColorChangedListener(new CompletedColorChangeListener()); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //Save everything outState.putLong(KEY_TIME_START, start.getTimeInMillis()); outState.putLong(KEY_TIME_END, end.getTimeInMillis()); outState.putBoolean(KEY_SET_START, startSet); outState.putBoolean(KEY_SET_END, endSet); outState.putString(KEY_NAME, nameEdit.getText().toString()); outState.putInt(KEY_COLOR_COMPLETED, completedColor); outState.putInt(KEY_COLOR_REMAINING, remainingColor); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ //Finish on the icon 'up' pressed case android.R.id.home: this.finish(); return true; } return super.onOptionsItemSelected(item); } /** * Method to both disable a button, and set * the text color to gray * @param button */ private void disableButton(Button button){ button.setEnabled(false); button.setTextColor(Color.DKGRAY); } /** * Method to both enable the button and set the * text color to white * @param button */ private void enableButton(Button button){ button.setEnabled(true); button.setTextColor(Color.WHITE); } /** * Method called when the buttons are clicked * @param v */ public void onClick(View v){ FragmentManager fm = getSupportFragmentManager(); switch(v.getId()){ case R.id.button_cancel: this.finish(); return; case R.id.button_save: String name = nameEdit.getText().toString().trim(); if("".equals(name)){ Toast.makeText(this, R.string.invalid_name, Toast.LENGTH_SHORT).show(); return; } //Set the values deployment.setStartDate(start.getTime()); deployment.setEndDate(end.getTime()); deployment.setName(name); deployment.setCompletedColor(completedColor); deployment.setRemainingColor(remainingColor); //Save it DatabaseManager.getInstance(this).saveDeployment(deployment); //End finish(); return; case R.id.button_start: DatePickerDialog startPicker = new DatePickerDialog(); startPicker.initialize(new OnDateSetListener(){ public void onDateSet(DatePickerDialog dialog, int year, int month, int day){ start.set(year, month, day, 0, 0); if(!endSet || start.before(end)){ startSet = true; enableButton(endButton); startButton.setText(getResources().getString(R.string.start_date)+ "\n"+format.format(start.getTime())); } else { Toast.makeText(CreateActivity.this, R.string.invalid_start, Toast.LENGTH_SHORT).show(); disableButton(saveButton); } } }, start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH)); startPicker.show(fm, "startPicker"); return; case R.id.button_end: DatePickerDialog endPicker = new DatePickerDialog(); endPicker.initialize(new OnDateSetListener(){ public void onDateSet(DatePickerDialog dialog, int year, int month, int day){ end.set(year, month, day, 0, 0); if(end.after(start)){ endSet = true; enableButton(saveButton); endButton.setText(getResources().getString(R.string.end_date)+ "\n"+format.format(end.getTime())); } else { Toast.makeText(CreateActivity.this, R.string.invalid_end, Toast.LENGTH_SHORT).show(); disableButton(saveButton); } } }, start.get(Calendar.YEAR), start.get(Calendar.MONTH), start.get(Calendar.DAY_OF_MONTH)); endPicker.show(fm, "endPicker"); return; } } /* * Classes to listen for color changes */ private class CompletedColorChangeListener implements OnColorChangedListener{ @Override public void onColorChanged(int color) { completedColor = color; } } private class RemainingColorChangeListener implements OnColorChangedListener{ @Override public void onColorChanged(int color) { remainingColor = color; } } }
false
true
public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_create); getSupportActionBar().setDisplayHomeAsUpEnabled(true); format = new SimpleDateFormat("MMM dd, yyyy"); nameEdit = (EditText) findViewById(R.id.name); startButton = (Button) findViewById(R.id.button_start); endButton = (Button) findViewById(R.id.button_end); saveButton = (Button) findViewById(R.id.button_save); //Color pickers ColorPicker completedPicker = (ColorPicker) findViewById(R.id.picker_completed); ColorPicker remainingPicker = (ColorPicker) findViewById(R.id.picker_remain); int id = getIntent().getIntExtra("id", -1); if(id >= 0){ //Starting in edit mode, load the old data deployment = DatabaseManager.getInstance(this).getDeployment(id); //Set the colors completedColor = deployment.getCompletedColor(); remainingColor = deployment.getRemainingColor(); //Set the dates start = Calendar.getInstance(); end = Calendar.getInstance(); start.setTimeInMillis(deployment.getStartDate().getTime()); end.setTimeInMillis(deployment.getEndDate().getTime()); startSet = true; endSet = true; //Set the buttons startButton.setText(getResources().getString(R.string.start_date)+ "\n"+format.format(start.getTime())); endButton.setText(getResources().getString(R.string.end_date)+ "\n"+format.format(end.getTime())); //Set the name nameEdit.setText(deployment.getName()); getSupportActionBar().setTitle(R.string.edit); } else { deployment = new Deployment(); disableButton(endButton); disableButton(saveButton); start = Calendar.getInstance(); end = (Calendar) start.clone(); startSet = false; endSet = false; completedColor = Color.GREEN; remainingColor = Color.RED; getSupportActionBar().setTitle(R.string.add_new); } //If restore from rotation if(savedInstanceState != null){ start.setTimeInMillis(savedInstanceState.getLong(KEY_TIME_START)); end.setTimeInMillis(savedInstanceState.getLong(KEY_TIME_END)); startSet = savedInstanceState.getBoolean(KEY_SET_START); endSet = savedInstanceState.getBoolean(KEY_SET_END); nameEdit.setText(savedInstanceState.getString(KEY_NAME)); completedColor = savedInstanceState.getInt(KEY_COLOR_COMPLETED); remainingColor = savedInstanceState.getInt(KEY_COLOR_REMAINING); //Set the date buttons, if set if(startSet){ startButton.setText(getResources().getString(R.string.start_date)+ "\n"+format.format(start.getTime())); enableButton(endButton); } if(endSet && end.after(start)){ endButton.setText(getResources().getString(R.string.end_date)+ "\n"+format.format(end.getTime())); enableButton(saveButton); } } remainingPicker.setColor(remainingColor); remainingPicker.setOnColorChangedListener(new RemainingColorChangeListener()); completedPicker.setColor(completedColor); completedPicker.setOnColorChangedListener(new CompletedColorChangeListener()); }
public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_create); getSupportActionBar().setDisplayHomeAsUpEnabled(true); format = new SimpleDateFormat("MMM dd, yyyy"); nameEdit = (EditText) findViewById(R.id.name); startButton = (Button) findViewById(R.id.button_start); endButton = (Button) findViewById(R.id.button_end); saveButton = (Button) findViewById(R.id.button_save); //Color pickers ColorPicker completedPicker = (ColorPicker) findViewById(R.id.picker_completed); ColorPicker remainingPicker = (ColorPicker) findViewById(R.id.picker_remain); int id = getIntent().getIntExtra("id", -1); if(id >= 0){ //Starting in edit mode, load the old data deployment = DatabaseManager.getInstance(this).getDeployment(id); //Set the colors completedColor = deployment.getCompletedColor(); remainingColor = deployment.getRemainingColor(); //Set the dates start = Calendar.getInstance(); end = Calendar.getInstance(); start.setTimeInMillis(deployment.getStartDate().getTime()); end.setTimeInMillis(deployment.getEndDate().getTime()); startSet = true; endSet = true; //Set the buttons startButton.setText(getResources().getString(R.string.start_date)+ "\n"+format.format(start.getTime())); endButton.setText(getResources().getString(R.string.end_date)+ "\n"+format.format(end.getTime())); //Set the name nameEdit.setText(deployment.getName()); getSupportActionBar().setTitle(R.string.edit); } else { deployment = new Deployment(); disableButton(endButton); disableButton(saveButton); start = Calendar.getInstance(); end = (Calendar) start.clone(); startSet = false; endSet = false; completedColor = Color.GREEN; remainingColor = Color.RED; getSupportActionBar().setTitle(R.string.add_new); } //If restore from rotation if(savedInstanceState != null){ start.setTimeInMillis(savedInstanceState.getLong(KEY_TIME_START)); end.setTimeInMillis(savedInstanceState.getLong(KEY_TIME_END)); startSet = savedInstanceState.getBoolean(KEY_SET_START); endSet = savedInstanceState.getBoolean(KEY_SET_END); nameEdit.setText(savedInstanceState.getString(KEY_NAME)); completedColor = savedInstanceState.getInt(KEY_COLOR_COMPLETED); remainingColor = savedInstanceState.getInt(KEY_COLOR_REMAINING); //Set the date buttons, if set if(startSet){ startButton.setText(getResources().getString(R.string.start_date)+ "\n"+format.format(start.getTime())); enableButton(endButton); } if(endSet && end.after(start)){ endButton.setText(getResources().getString(R.string.end_date)+ "\n"+format.format(end.getTime())); enableButton(saveButton); } } remainingPicker.setColor(remainingColor); remainingPicker.setOldCenterColor(remainingColor); remainingPicker.setOnColorChangedListener(new RemainingColorChangeListener()); completedPicker.setColor(completedColor); completedPicker.setOldCenterColor(completedColor); completedPicker.setOnColorChangedListener(new CompletedColorChangeListener()); }
diff --git a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/DatabaseTypeIntegrationTests.java b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/DatabaseTypeIntegrationTests.java index ebdacbc7e..eca7e389f 100644 --- a/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/DatabaseTypeIntegrationTests.java +++ b/spring-batch-infrastructure/src/test/java/org/springframework/batch/support/DatabaseTypeIntegrationTests.java @@ -1,39 +1,39 @@ /* * Copyright 2006-2009 the original author or 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 org.springframework.batch.support; import static org.junit.Assert.assertEquals; import javax.sql.DataSource; import org.junit.Test; /** * @author Dave Syer * */ public class DatabaseTypeIntegrationTests { @Test public void testH2() throws Exception { - DataSource dataSource = DatabaseTypeTestUtils.getDataSource(org.h2.jdbc.JdbcConnection.class, "jdbc:h2:file:target/data/sample"); + DataSource dataSource = DatabaseTypeTestUtils.getDataSource(org.h2.Driver.class, "jdbc:h2:file:target/data/sample"); assertEquals(DatabaseType.H2, DatabaseType.fromMetaData(dataSource)); dataSource.getConnection(); } }
true
true
public void testH2() throws Exception { DataSource dataSource = DatabaseTypeTestUtils.getDataSource(org.h2.jdbc.JdbcConnection.class, "jdbc:h2:file:target/data/sample"); assertEquals(DatabaseType.H2, DatabaseType.fromMetaData(dataSource)); dataSource.getConnection(); }
public void testH2() throws Exception { DataSource dataSource = DatabaseTypeTestUtils.getDataSource(org.h2.Driver.class, "jdbc:h2:file:target/data/sample"); assertEquals(DatabaseType.H2, DatabaseType.fromMetaData(dataSource)); dataSource.getConnection(); }
diff --git a/java/src/org/broadinstitute/sting/gatk/traversals/TraversalEngine.java b/java/src/org/broadinstitute/sting/gatk/traversals/TraversalEngine.java index e3b51a344..76f147b58 100755 --- a/java/src/org/broadinstitute/sting/gatk/traversals/TraversalEngine.java +++ b/java/src/org/broadinstitute/sting/gatk/traversals/TraversalEngine.java @@ -1,418 +1,418 @@ /* * Copyright (c) 2010, 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 org.broadinstitute.sting.gatk.traversals; import org.apache.log4j.Logger; import org.broadinstitute.sting.gatk.datasources.providers.ShardDataProvider; import org.broadinstitute.sting.gatk.datasources.shards.Shard; import org.broadinstitute.sting.gatk.walkers.Walker; import org.broadinstitute.sting.gatk.ReadMetrics; import org.broadinstitute.sting.gatk.GenomeAnalysisEngine; import org.broadinstitute.sting.utils.*; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import org.broadinstitute.sting.utils.exceptions.UserException; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.*; public abstract class TraversalEngine<M,T,WalkerType extends Walker<M,T>,ProviderType extends ShardDataProvider> { // Time in milliseconds since we initialized this engine private static final int HISTORY_WINDOW_SIZE = 50; private static class ProcessingHistory { double elapsedSeconds; long unitsProcessed; long bpProcessed; GenomeLoc loc; public ProcessingHistory(double elapsedSeconds, GenomeLoc loc, long unitsProcessed, long bpProcessed) { this.elapsedSeconds = elapsedSeconds; this.loc = loc; this.unitsProcessed = unitsProcessed; this.bpProcessed = bpProcessed; } } /** * Simple utility class that makes it convenient to print unit adjusted times */ private static class MyTime { double t; // in Seconds int precision; // for format public MyTime(double t, int precision) { this.t = t; this.precision = precision; } public MyTime(double t) { this(t, 1); } /** * Instead of 10000 s, returns 2.8 hours * @return */ public String toString() { double unitTime = t; String unit = "s"; if ( t > 120 ) { unitTime = t / 60; // minutes unit = "m"; if ( unitTime > 120 ) { unitTime /= 60; // hours unit = "h"; if ( unitTime > 100 ) { unitTime /= 24; // days unit = "d"; if ( unitTime > 20 ) { unitTime /= 7; // days unit = "w"; } } } } return String.format("%6."+precision+"f %s", unitTime, unit); } } /** lock object to sure updates to history are consistent across threads */ private static final Object lock = new Object(); LinkedList<ProcessingHistory> history = new LinkedList<ProcessingHistory>(); /** We use the SimpleTimer to time our run */ private SimpleTimer timer = new SimpleTimer("Traversal"); // How long can we go without printing some progress info? private long lastProgressPrintTime = -1; // When was the last time we printed progress log? private long PROGRESS_PRINT_FREQUENCY = 10 * 1000; // in milliseconds private final double TWO_HOURS_IN_SECONDS = 2.0 * 60.0 * 60.0; private final double TWELVE_HOURS_IN_SECONDS = 12.0 * 60.0 * 60.0; // for performance log private static final boolean PERFORMANCE_LOG_ENABLED = true; private final Object performanceLogLock = new Object(); private File performanceLogFile; private PrintStream performanceLog = null; private long lastPerformanceLogPrintTime = -1; // When was the last time we printed to the performance log? private final long PERFORMANCE_LOG_PRINT_FREQUENCY = PROGRESS_PRINT_FREQUENCY; // in milliseconds /** Size, in bp, of the area we are processing. Updated once in the system in initial for performance reasons */ long targetSize = -1; GenomeLocSortedSet targetIntervals = null; /** our log, which we want to capture anything from this class */ protected static Logger logger = Logger.getLogger(TraversalEngine.class); protected GenomeAnalysisEngine engine; // ---------------------------------------------------------------------------------------------------- // // ABSTRACT METHODS // // ---------------------------------------------------------------------------------------------------- /** * Gets the named traversal type associated with the given traversal. * @return A user-friendly name for the given traversal type. */ protected abstract String getTraversalType(); /** * this method must be implemented by all traversal engines * * @param walker the walker to run with * @param dataProvider the data provider that generates data given the shard * @param sum the accumulator * * @return an object of the reduce type */ public abstract T traverse(WalkerType walker, ProviderType dataProvider, T sum); // ---------------------------------------------------------------------------------------------------- // // Common timing routines // // ---------------------------------------------------------------------------------------------------- /** * Initialize the traversal engine. After this point traversals can be run over the data * @param engine GenomeAnalysisEngine for this traversal */ public void initialize(GenomeAnalysisEngine engine) { if ( engine == null ) throw new ReviewedStingException("BUG: GenomeAnalysisEngine cannot be null!"); this.engine = engine; if ( PERFORMANCE_LOG_ENABLED && engine.getArguments() != null && engine.getArguments().performanceLog != null ) { synchronized(this.performanceLogLock) { performanceLogFile = engine.getArguments().performanceLog; createNewPerformanceLog(); } } // if we don't have any intervals defined, create intervals from the reference itself if ( this.engine.getIntervals() == null ) targetIntervals = GenomeLocSortedSet.createSetFromSequenceDictionary(engine.getReferenceDataSource().getReference().getSequenceDictionary()); else targetIntervals = this.engine.getIntervals(); targetSize = targetIntervals.coveredSize(); } private void createNewPerformanceLog() { synchronized(performanceLogLock) { try { performanceLog = new PrintStream(new FileOutputStream(engine.getArguments().performanceLog)); List<String> pLogHeader = Arrays.asList("elapsed.time", "units.processed", "processing.speed", "bp.processed", "bp.speed", "genome.fraction.complete", "est.total.runtime", "est.time.remaining"); performanceLog.println(Utils.join("\t", pLogHeader)); } catch (FileNotFoundException e) { throw new UserException.CouldNotCreateOutputFile(engine.getArguments().performanceLog, e); } } } /** * Should be called to indicate that we're going to process records and the timer should start ticking */ public void startTimers() { timer.start(); lastProgressPrintTime = timer.currentTime(); } /** * @param curTime (current runtime, in millisecs) * @param lastPrintTime the last time we printed, in machine milliseconds * @param printFreq maximum permitted difference between last print and current times * * @return true if the maximum interval (in millisecs) has passed since the last printing */ private boolean maxElapsedIntervalForPrinting(final long curTime, long lastPrintTime, long printFreq) { return (curTime - lastPrintTime) > printFreq; } /** * Forward request to printProgress * * @param shard the given shard currently being processed. * @param loc the location */ public void printProgress(Shard shard, GenomeLoc loc) { // A bypass is inserted here for unit testing. // TODO: print metrics outside of the traversal engine to more easily handle cumulative stats. ReadMetrics cumulativeMetrics = engine.getCumulativeMetrics() != null ? engine.getCumulativeMetrics().clone() : new ReadMetrics(); cumulativeMetrics.incrementMetrics(shard.getReadMetrics()); printProgress(loc, cumulativeMetrics, false); } /** * Utility routine that prints out process information (including timing) every N records or * every M seconds, for N and M set in global variables. * * @param loc Current location, can be null if you are at the end of the traversal * @param metrics Metrics of reads filtered in/out. * @param mustPrint If true, will print out info, regardless of nRecords or time interval */ private void printProgress(GenomeLoc loc, ReadMetrics metrics, boolean mustPrint) { final long nRecords = metrics.getNumIterations(); - if ( nRecords == 1 ) { + if ( nRecords == 1 && mustPrint == false ) { logger.info("[INITIALIZATION COMPLETE; TRAVERSAL STARTING]"); logger.info(String.format("%15s processed.%s runtime per.1M.%s completed total.runtime remaining", "Location", getTraversalType(), getTraversalType())); } else { final long curTime = timer.currentTime(); boolean printProgress = mustPrint || maxElapsedIntervalForPrinting(curTime, lastProgressPrintTime, PROGRESS_PRINT_FREQUENCY); boolean printLog = performanceLog != null && maxElapsedIntervalForPrinting(curTime, lastPerformanceLogPrintTime, PERFORMANCE_LOG_PRINT_FREQUENCY); if ( printProgress || printLog ) { ProcessingHistory last = updateHistory(loc, metrics); final MyTime elapsed = new MyTime(last.elapsedSeconds); final MyTime bpRate = new MyTime(secondsPerMillionBP(last)); final MyTime unitRate = new MyTime(secondsPerMillionElements(last)); final double fractionGenomeTargetCompleted = calculateFractionGenomeTargetCompleted(last); final MyTime estTotalRuntime = new MyTime(elapsed.t / fractionGenomeTargetCompleted); final MyTime timeToCompletion = new MyTime(estTotalRuntime.t - elapsed.t); if ( printProgress ) { lastProgressPrintTime = curTime; // dynamically change the update rate so that short running jobs receive frequent updates while longer jobs receive fewer updates if ( estTotalRuntime.t > TWELVE_HOURS_IN_SECONDS ) PROGRESS_PRINT_FREQUENCY = 60 * 1000; // in milliseconds else if ( estTotalRuntime.t > TWO_HOURS_IN_SECONDS ) PROGRESS_PRINT_FREQUENCY = 30 * 1000; // in milliseconds else PROGRESS_PRINT_FREQUENCY = 10 * 1000; // in milliseconds // String common = String.format("%4.1e %s in %s, %s per 1M %s, %4.1f%% complete, est. runtime %s, %s remaining", // nRecords*1.0, getTraversalType(), elapsed, unitRate, // getTraversalType(), 100*fractionGenomeTargetCompleted, // estTotalRuntime, timeToCompletion); // // if (loc != null) // logger.info(String.format("%20s: processing %s", loc, common)); // else // logger.info(String.format("Processing %s", common)); logger.info(String.format("%15s %5.2e %s %s %4.1f%% %s %s", loc == null ? "done" : loc, nRecords*1.0, elapsed, unitRate, 100*fractionGenomeTargetCompleted, estTotalRuntime, timeToCompletion)); } if ( printLog ) { lastPerformanceLogPrintTime = curTime; synchronized(performanceLogLock) { performanceLog.printf("%.2f\t%d\t%.2e\t%d\t%.2e\t%.2e\t%.2f\t%.2f%n", elapsed.t, nRecords, unitRate.t, last.bpProcessed, bpRate.t, fractionGenomeTargetCompleted, estTotalRuntime.t, timeToCompletion.t); } } } } } /** * Keeps track of the last HISTORY_WINDOW_SIZE data points for the progress meter. Currently the * history isn't used in any way, but in the future it'll become valuable for more accurate estimates * for when a process will complete. * * @param loc our current position. If null, assumes we are done traversing * @param metrics information about what's been processed already * @return */ private final ProcessingHistory updateHistory(GenomeLoc loc, ReadMetrics metrics) { synchronized (lock) { if ( history.size() > HISTORY_WINDOW_SIZE ) history.pop(); long nRecords = metrics.getNumIterations(); long bpProcessed = loc == null ? targetSize : targetIntervals.sizeBeforeLoc(loc); // null -> end of processing history.add(new ProcessingHistory(timer.getElapsedTime(), loc, nRecords, bpProcessed)); return history.getLast(); } } /** How long in seconds to process 1M traversal units? */ private final double secondsPerMillionElements(ProcessingHistory last) { return (last.elapsedSeconds * 1000000.0) / Math.max(last.unitsProcessed, 1); } /** How long in seconds to process 1M bp on the genome? */ private final double secondsPerMillionBP(ProcessingHistory last) { return (last.elapsedSeconds * 1000000.0) / Math.max(last.bpProcessed, 1); } /** What fractoin of the target intervals have we covered? */ private final double calculateFractionGenomeTargetCompleted(ProcessingHistory last) { return (1.0*last.bpProcessed) / targetSize; } /** * Called after a traversal to print out information about the traversal process */ public void printOnTraversalDone(ReadMetrics cumulativeMetrics) { printProgress(null, cumulativeMetrics, true); final double elapsed = timer.getElapsedTime(); // count up the number of skipped reads by summing over all filters long nSkippedReads = 0L; for ( Map.Entry<Class, Long> countsByFilter: cumulativeMetrics.getCountsByFilter().entrySet()) nSkippedReads += countsByFilter.getValue(); logger.info(String.format("Total runtime %.2f secs, %.2f min, %.2f hours", elapsed, elapsed / 60, elapsed / 3600)); if ( cumulativeMetrics.getNumReadsSeen() > 0 ) logger.info(String.format("%d reads were filtered out during traversal out of %d total (%.2f%%)", nSkippedReads, cumulativeMetrics.getNumReadsSeen(), 100.0 * MathUtils.ratio(nSkippedReads,cumulativeMetrics.getNumReadsSeen()))); for ( Map.Entry<Class, Long> filterCounts : cumulativeMetrics.getCountsByFilter().entrySet() ) { long count = filterCounts.getValue(); logger.info(String.format(" -> %d reads (%.2f%% of total) failing %s", count, 100.0 * MathUtils.ratio(count,cumulativeMetrics.getNumReadsSeen()), Utils.getClassName(filterCounts.getKey()))); } if ( performanceLog != null ) performanceLog.close(); } /** * Gets the filename to which performance data is currently being written. * @return Filename to which performance data is currently being written. */ public String getPerformanceLogFileName() { synchronized(performanceLogLock) { return performanceLogFile.getAbsolutePath(); } } /** * Sets the filename of the log for performance. If set, will write performance data. * @param fileName filename to use when writing performance data. */ public void setPerformanceLogFileName(String fileName) { File file = new File(fileName); synchronized(performanceLogLock) { // Ignore multiple calls to reset the same lock. if(performanceLogFile != null && performanceLogFile.equals(fileName)) return; // Close an existing log if(performanceLog != null) performanceLog.close(); performanceLogFile = file; createNewPerformanceLog(); } } /** * Gets the frequency with which performance data is written. * @return Frequency, in seconds, of performance log writes. */ public long getPerformanceProgressPrintFrequencySeconds() { return PROGRESS_PRINT_FREQUENCY; } /** * How often should the performance log message be written? * @param seconds number of seconds between messages indicating performance frequency. */ public void setPerformanceProgressPrintFrequencySeconds(long seconds) { PROGRESS_PRINT_FREQUENCY = seconds; } }
true
true
private void printProgress(GenomeLoc loc, ReadMetrics metrics, boolean mustPrint) { final long nRecords = metrics.getNumIterations(); if ( nRecords == 1 ) { logger.info("[INITIALIZATION COMPLETE; TRAVERSAL STARTING]"); logger.info(String.format("%15s processed.%s runtime per.1M.%s completed total.runtime remaining", "Location", getTraversalType(), getTraversalType())); } else { final long curTime = timer.currentTime(); boolean printProgress = mustPrint || maxElapsedIntervalForPrinting(curTime, lastProgressPrintTime, PROGRESS_PRINT_FREQUENCY); boolean printLog = performanceLog != null && maxElapsedIntervalForPrinting(curTime, lastPerformanceLogPrintTime, PERFORMANCE_LOG_PRINT_FREQUENCY); if ( printProgress || printLog ) { ProcessingHistory last = updateHistory(loc, metrics); final MyTime elapsed = new MyTime(last.elapsedSeconds); final MyTime bpRate = new MyTime(secondsPerMillionBP(last)); final MyTime unitRate = new MyTime(secondsPerMillionElements(last)); final double fractionGenomeTargetCompleted = calculateFractionGenomeTargetCompleted(last); final MyTime estTotalRuntime = new MyTime(elapsed.t / fractionGenomeTargetCompleted); final MyTime timeToCompletion = new MyTime(estTotalRuntime.t - elapsed.t); if ( printProgress ) { lastProgressPrintTime = curTime; // dynamically change the update rate so that short running jobs receive frequent updates while longer jobs receive fewer updates if ( estTotalRuntime.t > TWELVE_HOURS_IN_SECONDS ) PROGRESS_PRINT_FREQUENCY = 60 * 1000; // in milliseconds else if ( estTotalRuntime.t > TWO_HOURS_IN_SECONDS ) PROGRESS_PRINT_FREQUENCY = 30 * 1000; // in milliseconds else PROGRESS_PRINT_FREQUENCY = 10 * 1000; // in milliseconds // String common = String.format("%4.1e %s in %s, %s per 1M %s, %4.1f%% complete, est. runtime %s, %s remaining", // nRecords*1.0, getTraversalType(), elapsed, unitRate, // getTraversalType(), 100*fractionGenomeTargetCompleted, // estTotalRuntime, timeToCompletion); // // if (loc != null) // logger.info(String.format("%20s: processing %s", loc, common)); // else // logger.info(String.format("Processing %s", common)); logger.info(String.format("%15s %5.2e %s %s %4.1f%% %s %s", loc == null ? "done" : loc, nRecords*1.0, elapsed, unitRate, 100*fractionGenomeTargetCompleted, estTotalRuntime, timeToCompletion)); } if ( printLog ) { lastPerformanceLogPrintTime = curTime; synchronized(performanceLogLock) { performanceLog.printf("%.2f\t%d\t%.2e\t%d\t%.2e\t%.2e\t%.2f\t%.2f%n", elapsed.t, nRecords, unitRate.t, last.bpProcessed, bpRate.t, fractionGenomeTargetCompleted, estTotalRuntime.t, timeToCompletion.t); } } } } }
private void printProgress(GenomeLoc loc, ReadMetrics metrics, boolean mustPrint) { final long nRecords = metrics.getNumIterations(); if ( nRecords == 1 && mustPrint == false ) { logger.info("[INITIALIZATION COMPLETE; TRAVERSAL STARTING]"); logger.info(String.format("%15s processed.%s runtime per.1M.%s completed total.runtime remaining", "Location", getTraversalType(), getTraversalType())); } else { final long curTime = timer.currentTime(); boolean printProgress = mustPrint || maxElapsedIntervalForPrinting(curTime, lastProgressPrintTime, PROGRESS_PRINT_FREQUENCY); boolean printLog = performanceLog != null && maxElapsedIntervalForPrinting(curTime, lastPerformanceLogPrintTime, PERFORMANCE_LOG_PRINT_FREQUENCY); if ( printProgress || printLog ) { ProcessingHistory last = updateHistory(loc, metrics); final MyTime elapsed = new MyTime(last.elapsedSeconds); final MyTime bpRate = new MyTime(secondsPerMillionBP(last)); final MyTime unitRate = new MyTime(secondsPerMillionElements(last)); final double fractionGenomeTargetCompleted = calculateFractionGenomeTargetCompleted(last); final MyTime estTotalRuntime = new MyTime(elapsed.t / fractionGenomeTargetCompleted); final MyTime timeToCompletion = new MyTime(estTotalRuntime.t - elapsed.t); if ( printProgress ) { lastProgressPrintTime = curTime; // dynamically change the update rate so that short running jobs receive frequent updates while longer jobs receive fewer updates if ( estTotalRuntime.t > TWELVE_HOURS_IN_SECONDS ) PROGRESS_PRINT_FREQUENCY = 60 * 1000; // in milliseconds else if ( estTotalRuntime.t > TWO_HOURS_IN_SECONDS ) PROGRESS_PRINT_FREQUENCY = 30 * 1000; // in milliseconds else PROGRESS_PRINT_FREQUENCY = 10 * 1000; // in milliseconds // String common = String.format("%4.1e %s in %s, %s per 1M %s, %4.1f%% complete, est. runtime %s, %s remaining", // nRecords*1.0, getTraversalType(), elapsed, unitRate, // getTraversalType(), 100*fractionGenomeTargetCompleted, // estTotalRuntime, timeToCompletion); // // if (loc != null) // logger.info(String.format("%20s: processing %s", loc, common)); // else // logger.info(String.format("Processing %s", common)); logger.info(String.format("%15s %5.2e %s %s %4.1f%% %s %s", loc == null ? "done" : loc, nRecords*1.0, elapsed, unitRate, 100*fractionGenomeTargetCompleted, estTotalRuntime, timeToCompletion)); } if ( printLog ) { lastPerformanceLogPrintTime = curTime; synchronized(performanceLogLock) { performanceLog.printf("%.2f\t%d\t%.2e\t%d\t%.2e\t%.2e\t%.2f\t%.2f%n", elapsed.t, nRecords, unitRate.t, last.bpProcessed, bpRate.t, fractionGenomeTargetCompleted, estTotalRuntime.t, timeToCompletion.t); } } } } }
diff --git a/src/com/vanomaly/superd/view/BaselineLeftStringCenterOverrunTableCell.java b/src/com/vanomaly/superd/view/BaselineLeftStringCenterOverrunTableCell.java index a0322cc..5b92250 100644 --- a/src/com/vanomaly/superd/view/BaselineLeftStringCenterOverrunTableCell.java +++ b/src/com/vanomaly/superd/view/BaselineLeftStringCenterOverrunTableCell.java @@ -1,49 +1,49 @@ /******************************************************************************* * Copyright 2013 Jason Sipula * * * * 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.vanomaly.superd.view; import javafx.geometry.Pos; import javafx.scene.control.OverrunStyle; import javafx.scene.control.TableCell; import com.vanomaly.superd.core.SimpleFileProperty; /** * @author Jason Sipula * */ public class BaselineLeftStringCenterOverrunTableCell extends TableCell<SimpleFileProperty, String> { public BaselineLeftStringCenterOverrunTableCell() { this(null); this.setStyle("-fx-padding: 5px"); this.setAlignment(Pos.BASELINE_LEFT); } public BaselineLeftStringCenterOverrunTableCell(String ellipsisString) { super(); - setTextOverrun(OverrunStyle.CENTER_WORD_ELLIPSIS); + setTextOverrun(OverrunStyle.CENTER_ELLIPSIS); if (ellipsisString != null && !"".equals(ellipsisString)) { setEllipsisString(ellipsisString); } } @Override protected void updateItem(String item, boolean empty) { super.updateItem(item, empty); setText(item == null ? "" : item); } }
true
true
public BaselineLeftStringCenterOverrunTableCell(String ellipsisString) { super(); setTextOverrun(OverrunStyle.CENTER_WORD_ELLIPSIS); if (ellipsisString != null && !"".equals(ellipsisString)) { setEllipsisString(ellipsisString); } }
public BaselineLeftStringCenterOverrunTableCell(String ellipsisString) { super(); setTextOverrun(OverrunStyle.CENTER_ELLIPSIS); if (ellipsisString != null && !"".equals(ellipsisString)) { setEllipsisString(ellipsisString); } }
diff --git a/src/main/java/com/hmsonline/storm/cassandra/trident/DefaultCassandraState.java b/src/main/java/com/hmsonline/storm/cassandra/trident/DefaultCassandraState.java index f08487d..c331c0b 100644 --- a/src/main/java/com/hmsonline/storm/cassandra/trident/DefaultCassandraState.java +++ b/src/main/java/com/hmsonline/storm/cassandra/trident/DefaultCassandraState.java @@ -1,279 +1,280 @@ package com.hmsonline.storm.cassandra.trident; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import storm.trident.state.JSONNonTransactionalSerializer; import storm.trident.state.JSONOpaqueSerializer; import storm.trident.state.JSONTransactionalSerializer; import storm.trident.state.OpaqueValue; import storm.trident.state.Serializer; import storm.trident.state.State; import storm.trident.state.StateFactory; import storm.trident.state.StateType; import storm.trident.state.TransactionalValue; import storm.trident.state.map.CachedMap; import storm.trident.state.map.IBackingMap; import storm.trident.state.map.MapState; import storm.trident.state.map.NonTransactionalMap; import storm.trident.state.map.OpaqueMap; import storm.trident.state.map.SnapshottableMap; import storm.trident.state.map.TransactionalMap; import backtype.storm.task.IMetricsContext; import backtype.storm.tuple.Values; import com.google.common.base.Function; import com.google.common.collect.Collections2; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.hmsonline.storm.cassandra.StormCassandraConstants; import com.netflix.astyanax.AstyanaxConfiguration; import com.netflix.astyanax.AstyanaxContext; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.connectionpool.ConnectionPoolConfiguration; import com.netflix.astyanax.connectionpool.ConnectionPoolMonitor; import com.netflix.astyanax.connectionpool.NodeDiscoveryType; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl; import com.netflix.astyanax.connectionpool.impl.CountingConnectionPoolMonitor; import com.netflix.astyanax.impl.AstyanaxConfigurationImpl; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.model.Composite; import com.netflix.astyanax.query.RowQuery; import com.netflix.astyanax.serializers.CompositeSerializer; import com.netflix.astyanax.serializers.StringSerializer; import com.netflix.astyanax.thrift.ThriftFamilyFactory; public class DefaultCassandraState<T> implements IBackingMap<T> { @SuppressWarnings("unused") private static final Logger LOG = LoggerFactory.getLogger(DefaultCassandraState.class); @SuppressWarnings("rawtypes") private static final Map<StateType, Serializer> DEFAULT_SERIALZERS = Maps.newHashMap(); public static final String CASSANDRA_CLUSTER_NAME = "cassandra.clusterName"; public static final String ASTYANAX_CONFIGURATION = "astyanax.configuration"; public static final String ASTYANAX_CONNECTION_POOL_CONFIGURATION = "astyanax.connectionPoolConfiguration"; public static final String ASTYANAX_CONNECTION_POOL_MONITOR = "astyanax.connectioPoolMonitor"; private final Map<String, Object> DEFAULTS = new ImmutableMap.Builder<String, Object>() .put(CASSANDRA_CLUSTER_NAME, "ClusterName") .put(ASTYANAX_CONFIGURATION, new AstyanaxConfigurationImpl().setDiscoveryType(NodeDiscoveryType.NONE)) .put(ASTYANAX_CONNECTION_POOL_CONFIGURATION, new ConnectionPoolConfigurationImpl("MyConnectionPool").setMaxConnsPerHost(1)) .put(ASTYANAX_CONNECTION_POOL_MONITOR, new CountingConnectionPoolMonitor()).build(); private Options<T> options; private Serializer<T> serializer; protected Keyspace keyspace; static { DEFAULT_SERIALZERS.put(StateType.NON_TRANSACTIONAL, new JSONNonTransactionalSerializer()); DEFAULT_SERIALZERS.put(StateType.TRANSACTIONAL, new JSONTransactionalSerializer()); DEFAULT_SERIALZERS.put(StateType.OPAQUE, new JSONOpaqueSerializer()); } protected AstyanaxContext<Keyspace> createContext(Map<String, Object> config) { Map<String, Object> settings = Maps.newHashMap(); for (Map.Entry<String, Object> defaultEntry : DEFAULTS.entrySet()) { if (config.containsKey(defaultEntry.getKey())) { settings.put(defaultEntry.getKey(), config.get(defaultEntry.getKey())); } else { settings.put(defaultEntry.getKey(), defaultEntry.getValue()); } } // in the defaults case, we don't know the seed hosts until context // creation time if (settings.get(ASTYANAX_CONNECTION_POOL_CONFIGURATION) instanceof ConnectionPoolConfigurationImpl) { ConnectionPoolConfigurationImpl cpConfig = (ConnectionPoolConfigurationImpl) settings .get(ASTYANAX_CONNECTION_POOL_CONFIGURATION); cpConfig.setSeeds((String) config.get(StormCassandraConstants.CASSANDRA_HOST)); } return new AstyanaxContext.Builder() .forCluster((String) settings.get(CASSANDRA_CLUSTER_NAME)) .forKeyspace((String) config.get(StormCassandraConstants.CASSANDRA_STATE_KEYSPACE)) .withAstyanaxConfiguration((AstyanaxConfiguration) settings.get(ASTYANAX_CONFIGURATION)) .withConnectionPoolConfiguration( (ConnectionPoolConfiguration) settings.get(ASTYANAX_CONNECTION_POOL_CONFIGURATION)) .withConnectionPoolMonitor((ConnectionPoolMonitor) settings.get(ASTYANAX_CONNECTION_POOL_MONITOR)) .buildKeyspace(ThriftFamilyFactory.getInstance()); } @SuppressWarnings("serial") public static class Options<T> implements Serializable { public Serializer<T> serializer = null; public int localCacheSize = 5000; public String globalKey = "globalkey"; public String columnFamily = "cassandra_state"; public String rowkey = "default_cassandra_state"; public String clientConfigKey = "cassandra.config"; } @SuppressWarnings("rawtypes") public static StateFactory opaque() { Options<OpaqueValue> options = new Options<OpaqueValue>(); return opaque(options); } @SuppressWarnings("rawtypes") public static StateFactory opaque(Options<OpaqueValue> opts) { return new Factory(StateType.OPAQUE, opts); } @SuppressWarnings("rawtypes") public static StateFactory transactional() { Options<TransactionalValue> options = new Options<TransactionalValue>(); return transactional(options); } @SuppressWarnings("rawtypes") public static StateFactory transactional(Options<TransactionalValue> opts) { return new Factory(StateType.TRANSACTIONAL, opts); } public static StateFactory nonTransactional() { Options<Object> options = new Options<Object>(); return nonTransactional(options); } public static StateFactory nonTransactional(Options<Object> opts) { return new Factory(StateType.NON_TRANSACTIONAL, opts); } protected static class Factory implements StateFactory { private static final long serialVersionUID = -2644278289157792107L; private StateType stateType; private Options<?> options; @SuppressWarnings({ "rawtypes", "unchecked" }) public Factory(StateType stateType, Options options) { this.stateType = stateType; this.options = options; if (this.options.serializer == null) { this.options.serializer = DEFAULT_SERIALZERS.get(stateType); } if (this.options.serializer == null) { throw new RuntimeException("Serializer should be specified for type: " + stateType); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public State makeState(Map conf, IMetricsContext metrics, int partitionIndex, int numPartitions) { DefaultCassandraState state = new DefaultCassandraState(options, conf); CachedMap cachedMap = new CachedMap(state, options.localCacheSize); MapState mapState; if (stateType == StateType.NON_TRANSACTIONAL) { mapState = NonTransactionalMap.build(cachedMap); } else if (stateType == StateType.OPAQUE) { mapState = OpaqueMap.build(cachedMap); } else if (stateType == StateType.TRANSACTIONAL) { mapState = TransactionalMap.build(cachedMap); } else { throw new RuntimeException("Unknown state type: " + stateType); } return new SnapshottableMap(mapState, new Values(options.globalKey)); } } @SuppressWarnings({ "rawtypes", "unchecked" }) public DefaultCassandraState(Options<T> options, Map conf) { this.options = options; this.serializer = options.serializer; AstyanaxContext<Keyspace> context = createContext((Map<String, Object>) conf.get(options.clientConfigKey)); context.start(); this.keyspace = context.getEntity(); } @Override public List<T> multiGet(List<List<Object>> keys) { Collection<Composite> columnNames = toColumnNames(keys); ColumnFamily<String, Composite> cf = new ColumnFamily<String, Composite>(this.options.columnFamily, StringSerializer.get(), CompositeSerializer.get()); RowQuery<String, Composite> query = this.keyspace.prepareQuery(cf).getKey(this.options.rowkey) .withColumnSlice(columnNames); ColumnList<Composite> result = null; try { result = query.execute().getResult(); } catch (ConnectionException e) { - e.printStackTrace(); + //TODO throw a specific error. + throw new RuntimeException(e); } Map<List<Object>, byte[]> resultMap = new HashMap<List<Object>, byte[]>(); Collection<Composite> columns = result.getColumnNames(); for (Composite columnName : columns) { List<Object> dimensions = new ArrayList<Object>(); for (int i = 0; i < columnName.size(); i++) { dimensions.add(columnName.get(i, StringSerializer.get())); } resultMap.put(dimensions, result.getByteArrayValue(columnName, new byte[0])); } List<T> values = new ArrayList<T>(); for (List<Object> key : keys) { byte[] bytes = resultMap.get(key); if (bytes != null) { values.add(serializer.deserialize(bytes)); } else { values.add(null); } } return values; } @Override public void multiPut(List<List<Object>> keys, List<T> values) { MutationBatch mutation = this.keyspace.prepareMutationBatch(); ColumnFamily<String, Composite> cf = new ColumnFamily<String, Composite>(this.options.columnFamily, StringSerializer.get(), CompositeSerializer.get()); for (int i = 0; i < keys.size(); i++) { Composite columnName = toColumnName(keys.get(i)); byte[] bytes = serializer.serialize(values.get(i)); mutation.withRow(cf, this.options.rowkey).putColumn(columnName, bytes); } try { mutation.execute(); } catch (ConnectionException e) { throw new RuntimeException("Batch mutation for state failed.", e); } } private Collection<Composite> toColumnNames(List<List<Object>> keys) { return Collections2.transform(keys, new Function<List<Object>, Composite>() { @Override public Composite apply(List<Object> key) { return toColumnName(key); } }); } private Composite toColumnName(List<Object> key) { Composite columnName = new Composite(); for (Object component : key) { if (component == null) { component = "[NULL]"; } columnName.addComponent(component.toString(), StringSerializer.get()); } return columnName; } }
true
true
public List<T> multiGet(List<List<Object>> keys) { Collection<Composite> columnNames = toColumnNames(keys); ColumnFamily<String, Composite> cf = new ColumnFamily<String, Composite>(this.options.columnFamily, StringSerializer.get(), CompositeSerializer.get()); RowQuery<String, Composite> query = this.keyspace.prepareQuery(cf).getKey(this.options.rowkey) .withColumnSlice(columnNames); ColumnList<Composite> result = null; try { result = query.execute().getResult(); } catch (ConnectionException e) { e.printStackTrace(); } Map<List<Object>, byte[]> resultMap = new HashMap<List<Object>, byte[]>(); Collection<Composite> columns = result.getColumnNames(); for (Composite columnName : columns) { List<Object> dimensions = new ArrayList<Object>(); for (int i = 0; i < columnName.size(); i++) { dimensions.add(columnName.get(i, StringSerializer.get())); } resultMap.put(dimensions, result.getByteArrayValue(columnName, new byte[0])); } List<T> values = new ArrayList<T>(); for (List<Object> key : keys) { byte[] bytes = resultMap.get(key); if (bytes != null) { values.add(serializer.deserialize(bytes)); } else { values.add(null); } } return values; }
public List<T> multiGet(List<List<Object>> keys) { Collection<Composite> columnNames = toColumnNames(keys); ColumnFamily<String, Composite> cf = new ColumnFamily<String, Composite>(this.options.columnFamily, StringSerializer.get(), CompositeSerializer.get()); RowQuery<String, Composite> query = this.keyspace.prepareQuery(cf).getKey(this.options.rowkey) .withColumnSlice(columnNames); ColumnList<Composite> result = null; try { result = query.execute().getResult(); } catch (ConnectionException e) { //TODO throw a specific error. throw new RuntimeException(e); } Map<List<Object>, byte[]> resultMap = new HashMap<List<Object>, byte[]>(); Collection<Composite> columns = result.getColumnNames(); for (Composite columnName : columns) { List<Object> dimensions = new ArrayList<Object>(); for (int i = 0; i < columnName.size(); i++) { dimensions.add(columnName.get(i, StringSerializer.get())); } resultMap.put(dimensions, result.getByteArrayValue(columnName, new byte[0])); } List<T> values = new ArrayList<T>(); for (List<Object> key : keys) { byte[] bytes = resultMap.get(key); if (bytes != null) { values.add(serializer.deserialize(bytes)); } else { values.add(null); } } return values; }
diff --git a/Chat/src/Server/ServerReady.java b/Chat/src/Server/ServerReady.java index 1509f96..6b209d7 100644 --- a/Chat/src/Server/ServerReady.java +++ b/Chat/src/Server/ServerReady.java @@ -1,61 +1,65 @@ package Server; import java.io.IOException; import Communications.TCP; import Messages.ClientRequestInfoMessage; import Messages.ClientRequestUpdateMessage; import Messages.ErrorMessage; import Messages.LookupFailedMessage; import Messages.Message; import Messages.NameCollisionMessage; import Messages.ServerConfirmationUpdateMessage; import Messages.ServerSendsInfoMessage; public class ServerReady extends ServerState{ public ServerState process(TCP tcp, Message tcpMessage, long timeEnteredState) { if(tcpMessage instanceof ClientRequestInfoMessage && tcpMessage.getCorrect()){ System.out.println("info message"); Message message = null; String user=((ClientRequestInfoMessage)tcpMessage).targetUsername; String ip=LookupTable.lookup(user); if(ip==null){ message=new LookupFailedMessage(12,LookupFailedMessage.minSize+Message.minSize,0,"",user); } else{ message=new ServerSendsInfoMessage(9,ServerSendsInfoMessage.minSize+Message.minSize,0,"",user,ip); } tcp.send(message); return this; } else if(tcpMessage instanceof ClientRequestUpdateMessage && tcpMessage.getCorrect()){ System.out.println("update message"); Message message = null; String user=((ClientRequestUpdateMessage)tcpMessage).senderUsername; String ip=((ClientRequestUpdateMessage)tcpMessage).senderIP; + System.out.println("past parsing"); if(LookupTable.lookup(user)!=null){ + System.out.println("already found"); message=new NameCollisionMessage(14,NameCollisionMessage.minSize+Message.minSize,0,"",user); } else{ + System.out.println("not found"); LookupTable.bind(user, ip); message=new ServerConfirmationUpdateMessage(7,ServerConfirmationUpdateMessage.minSize+Message.minSize,0,"",user,ip); } + System.out.println("sending"); tcp.send(message); return this; } else if(tcpMessage!=null){ tcp.send(new ErrorMessage(13,Message.minSize,0,"",new byte[0])); try { tcp.close(); } catch (IOException e) {} return new ServerDisconnected(); } else if(System.currentTimeMillis()-timeEnteredState>300000){ try { tcp.close(); } catch (IOException e) {} return new ServerDisconnected(); } return this; } }
false
true
public ServerState process(TCP tcp, Message tcpMessage, long timeEnteredState) { if(tcpMessage instanceof ClientRequestInfoMessage && tcpMessage.getCorrect()){ System.out.println("info message"); Message message = null; String user=((ClientRequestInfoMessage)tcpMessage).targetUsername; String ip=LookupTable.lookup(user); if(ip==null){ message=new LookupFailedMessage(12,LookupFailedMessage.minSize+Message.minSize,0,"",user); } else{ message=new ServerSendsInfoMessage(9,ServerSendsInfoMessage.minSize+Message.minSize,0,"",user,ip); } tcp.send(message); return this; } else if(tcpMessage instanceof ClientRequestUpdateMessage && tcpMessage.getCorrect()){ System.out.println("update message"); Message message = null; String user=((ClientRequestUpdateMessage)tcpMessage).senderUsername; String ip=((ClientRequestUpdateMessage)tcpMessage).senderIP; if(LookupTable.lookup(user)!=null){ message=new NameCollisionMessage(14,NameCollisionMessage.minSize+Message.minSize,0,"",user); } else{ LookupTable.bind(user, ip); message=new ServerConfirmationUpdateMessage(7,ServerConfirmationUpdateMessage.minSize+Message.minSize,0,"",user,ip); } tcp.send(message); return this; } else if(tcpMessage!=null){ tcp.send(new ErrorMessage(13,Message.minSize,0,"",new byte[0])); try { tcp.close(); } catch (IOException e) {} return new ServerDisconnected(); } else if(System.currentTimeMillis()-timeEnteredState>300000){ try { tcp.close(); } catch (IOException e) {} return new ServerDisconnected(); } return this; }
public ServerState process(TCP tcp, Message tcpMessage, long timeEnteredState) { if(tcpMessage instanceof ClientRequestInfoMessage && tcpMessage.getCorrect()){ System.out.println("info message"); Message message = null; String user=((ClientRequestInfoMessage)tcpMessage).targetUsername; String ip=LookupTable.lookup(user); if(ip==null){ message=new LookupFailedMessage(12,LookupFailedMessage.minSize+Message.minSize,0,"",user); } else{ message=new ServerSendsInfoMessage(9,ServerSendsInfoMessage.minSize+Message.minSize,0,"",user,ip); } tcp.send(message); return this; } else if(tcpMessage instanceof ClientRequestUpdateMessage && tcpMessage.getCorrect()){ System.out.println("update message"); Message message = null; String user=((ClientRequestUpdateMessage)tcpMessage).senderUsername; String ip=((ClientRequestUpdateMessage)tcpMessage).senderIP; System.out.println("past parsing"); if(LookupTable.lookup(user)!=null){ System.out.println("already found"); message=new NameCollisionMessage(14,NameCollisionMessage.minSize+Message.minSize,0,"",user); } else{ System.out.println("not found"); LookupTable.bind(user, ip); message=new ServerConfirmationUpdateMessage(7,ServerConfirmationUpdateMessage.minSize+Message.minSize,0,"",user,ip); } System.out.println("sending"); tcp.send(message); return this; } else if(tcpMessage!=null){ tcp.send(new ErrorMessage(13,Message.minSize,0,"",new byte[0])); try { tcp.close(); } catch (IOException e) {} return new ServerDisconnected(); } else if(System.currentTimeMillis()-timeEnteredState>300000){ try { tcp.close(); } catch (IOException e) {} return new ServerDisconnected(); } return this; }
diff --git a/TicTacToeTieAI/src2/tttai/Board.java b/TicTacToeTieAI/src2/tttai/Board.java index 0e4b192..6c7af3f 100644 --- a/TicTacToeTieAI/src2/tttai/Board.java +++ b/TicTacToeTieAI/src2/tttai/Board.java @@ -1,106 +1,106 @@ package tttai; import java.util.Arrays; import tictactoeai.Place; public class Board { String[] board = {"0","1","2","3", "4","5","6", "7","8","9"}; int spacesFree; String winner; Board(){ spacesFree = 9; winner = null; } /** * constructor for creating a new board with an updated move * @param b * @param space * @param player */ Board(Board b, int space, String player){ this.board = Arrays.copyOf(b.board, 10); this.spacesFree = b.spacesFree-1; this.board[space] = player; } /** * returns true if the game is over (won or full-tie) */ public boolean isOver(){ if(spacesFree==0) return true; if(this.isWon()) return true; else return false; } /** * returns true if the board is won */ public boolean isWon(){ if(this.testWon("X")){ this.winner = "X"; return true; } if(this.testWon("O")){ this.winner = "O"; return true; } else return false; } /** * returns true if string is the winner */ public boolean testWon(String s){ - if(board[1]==s&&board[2]==s&&board[3]==s) + if(board[1].equals(s)&&board[2].equals(s)&&board[3].equals(s)) return true; - if(board[4]==s&&board[5]==s&&board[6]==s) + if(board[4].equals(s)&&board[5].equals(s)&&board[6].equals(s)) return true; - if(board[7]==s&&board[8]==s&&board[9]==s) + if(board[7].equals(s)&&board[8].equals(s)&&board[9].equals(s)) return true; - if(board[1]==s&&board[4]==s&&board[7]==s) + if(board[1].equals(s)&&board[4].equals(s)&&board[7].equals(s)) return true; - if(board[2]==s&&board[5]==s&&board[8]==s) + if(board[2].equals(s)&&board[5].equals(s)&&board[8].equals(s)) return true; - if(board[3]==s&&board[6]==s&&board[9]==s) + if(board[3].equals(s)&&board[6].equals(s)&&board[9].equals(s)) return true; - if(board[1]==s&&board[5]==s&&board[9]==s) + if(board[1].equals(s)&&board[5].equals(s)&&board[9].equals(s)) return true; - if(board[3]==s&&board[5]==s&&board[7]==s) + if(board[3].equals(s)&&board[5].equals(s)&&board[7].equals(s)) return true; return false; } /** * returns true if two boards are the same */ public boolean equals(Board b){ for(int i=1; i<=9; i++){ if(b.board[i]!=this.board[i]) return false; } return true; } /** * returns a board with the current board plus the passed move */ public Board makeMove(String player, int square){ return new Board(this, square, player); } /** * toString() */ public String toString(){ StringBuilder sb = new StringBuilder(); for(int i=1; i<=9; i++){ sb.append(board[i]+" "); if(i%3==0){ sb.append("\n"); } } return sb.toString(); } }
false
true
public boolean testWon(String s){ if(board[1]==s&&board[2]==s&&board[3]==s) return true; if(board[4]==s&&board[5]==s&&board[6]==s) return true; if(board[7]==s&&board[8]==s&&board[9]==s) return true; if(board[1]==s&&board[4]==s&&board[7]==s) return true; if(board[2]==s&&board[5]==s&&board[8]==s) return true; if(board[3]==s&&board[6]==s&&board[9]==s) return true; if(board[1]==s&&board[5]==s&&board[9]==s) return true; if(board[3]==s&&board[5]==s&&board[7]==s) return true; return false; }
public boolean testWon(String s){ if(board[1].equals(s)&&board[2].equals(s)&&board[3].equals(s)) return true; if(board[4].equals(s)&&board[5].equals(s)&&board[6].equals(s)) return true; if(board[7].equals(s)&&board[8].equals(s)&&board[9].equals(s)) return true; if(board[1].equals(s)&&board[4].equals(s)&&board[7].equals(s)) return true; if(board[2].equals(s)&&board[5].equals(s)&&board[8].equals(s)) return true; if(board[3].equals(s)&&board[6].equals(s)&&board[9].equals(s)) return true; if(board[1].equals(s)&&board[5].equals(s)&&board[9].equals(s)) return true; if(board[3].equals(s)&&board[5].equals(s)&&board[7].equals(s)) return true; return false; }
diff --git a/src/main/java/axirassa/util/MessagingTools.java b/src/main/java/axirassa/util/MessagingTools.java index 762b4cc6..3c72c787 100644 --- a/src/main/java/axirassa/util/MessagingTools.java +++ b/src/main/java/axirassa/util/MessagingTools.java @@ -1,19 +1,19 @@ package axirassa.util; import org.hornetq.api.core.TransportConfiguration; import org.hornetq.api.core.client.ClientSession; import org.hornetq.api.core.client.ClientSessionFactory; import org.hornetq.api.core.client.HornetQClient; import org.hornetq.api.core.client.ServerLocator; import org.hornetq.core.remoting.impl.netty.NettyConnectorFactory; public class MessagingTools { public static ClientSession getEmbeddedSession() throws Exception { TransportConfiguration configuration = new TransportConfiguration(NettyConnectorFactory.class.getName()); - ServerLocator locator = HornetQClient.createServerLocatorWithHA(configuration); + ServerLocator locator = HornetQClient.createServerLocatorWithoutHA(configuration); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(); return session; } }
true
true
public static ClientSession getEmbeddedSession() throws Exception { TransportConfiguration configuration = new TransportConfiguration(NettyConnectorFactory.class.getName()); ServerLocator locator = HornetQClient.createServerLocatorWithHA(configuration); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(); return session; }
public static ClientSession getEmbeddedSession() throws Exception { TransportConfiguration configuration = new TransportConfiguration(NettyConnectorFactory.class.getName()); ServerLocator locator = HornetQClient.createServerLocatorWithoutHA(configuration); ClientSessionFactory factory = locator.createSessionFactory(); ClientSession session = factory.createSession(); return session; }
diff --git a/src/topiaryexplorer/ColorByPopupMenu.java b/src/topiaryexplorer/ColorByPopupMenu.java index 6b43408..9a610c6 100644 --- a/src/topiaryexplorer/ColorByPopupMenu.java +++ b/src/topiaryexplorer/ColorByPopupMenu.java @@ -1,124 +1,123 @@ package topiaryexplorer; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.table.*; import javax.swing.event.*; import javax.swing.filechooser.FileNameExtensionFilter; import javax.jnlp.*; /** * This pop-up menu contains values by which branches * and nodes of the tree can be colored. * @author Meg Pirrung &lt;&gt; * @see #JpopupMenu */ class ColorByPopupMenu extends JPopupMenu{ private TopiaryWindow parent; private MainFrame frame; private ColorPanel colorPanel; private int elementType = 0; private JMenu colorByOtuMetadataMenu = new JMenu("Tip Data"); private JMenu colorBySampleMetadataMenu = new JMenu("Sample Data"); private ButtonGroup colorByGroup = new ButtonGroup(); /** * Creates a pop-up menu for the specified element type. */ ColorByPopupMenu(MainFrame _frame, TopiaryWindow _parent, ColorPanel _colorPanel, int _elementType) { frame = _frame; parent = _parent; colorPanel = _colorPanel; elementType = _elementType; //set up the "color by" submenus add((JMenuItem)colorByOtuMetadataMenu); add((JMenuItem)colorBySampleMetadataMenu); } /** * Resets colorby OTU menu when a new otu table is loaded. */ void resetColorByOtuMenu() { /* noColoringMenuItem.setSelected(true);*/ colorByOtuMetadataMenu.removeAll(); ArrayList<String> data = frame.otuMetadata.getColumnNames(); //start at 1 to skip ID column for (int i = 1; i < data.size(); i++) { String value = data.get(i); JRadioButtonMenuItem item = new JRadioButtonMenuItem(value); colorByGroup.add(item); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //get the category to color by String value = e.getActionCommand(); frame.currTable = frame.otuMetadata; frame.colorPane.setSelectedIndex(elementType); if(elementType == 0) { ((TreeWindow)parent).colorBranchesByValue(value); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.coloringMenuItem.setSelected(false); ((TreeWindow)parent).tree.setColorBranches(true); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.majorityColoringMenuItem.setEnabled(true); } else if(elementType == 1) ((TreeWindow)parent).colorLabelsByValue(value); frame.schemeList.setSelectedIndex(0); colorPanel.setCurrentValue(value); TableColumn column = colorPanel.getColorKeyTable().getColumnModel().getColumn(0); column.setHeaderValue(value); } }); colorByOtuMetadataMenu.add(item); } } /** * Resets colorby Sample menu when a new sample metadata table is loaded. */ void resetColorBySampleMenu() { /* noColoringMenuItem.setSelected(true);*/ colorBySampleMetadataMenu.removeAll(); // colorBySampleMetadataMenu.add(new JRadioButtonMenuItem("hurf")); ArrayList<String> data = frame.sampleMetadata.getColumnNames(); - //start at 1 to skip ID column // System.out.println(frame.sampleMetadata.getColumnNames().size()); - for (int i = 1; i < data.size(); i++) { + for (int i = 0; i < data.size(); i++) { String value = data.get(i); JRadioButtonMenuItem item = new JRadioButtonMenuItem(value); // System.out.println("["+value+"]"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //get the category to color by String value = e.getActionCommand(); frame.currTable = frame.sampleMetadata; frame.colorPane.setSelectedIndex(elementType); if(elementType == 0) { ((TreeWindow)parent).colorBranchesByValue(value); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.coloringMenuItem.setSelected(false); ((TreeWindow)parent).tree.setColorBranches(true); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.coloringMenuItem.setEnabled(true); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.majorityColoringMenuItem.setEnabled(true); } else if(elementType == 1) ((TreeWindow)parent).colorLabelsByValue(value); frame.schemeList.setSelectedIndex(0); colorPanel.setCurrentValue(value); TableColumn column = colorPanel.getColorKeyTable().getColumnModel().getColumn(0); column.setHeaderValue(value); } }); colorByGroup.add(item); colorBySampleMetadataMenu.add(item); } // colorBySampleMetadataMenu.add(new JRadioButtonMenuItem("durf")); } }
false
true
void resetColorBySampleMenu() { /* noColoringMenuItem.setSelected(true);*/ colorBySampleMetadataMenu.removeAll(); // colorBySampleMetadataMenu.add(new JRadioButtonMenuItem("hurf")); ArrayList<String> data = frame.sampleMetadata.getColumnNames(); //start at 1 to skip ID column // System.out.println(frame.sampleMetadata.getColumnNames().size()); for (int i = 1; i < data.size(); i++) { String value = data.get(i); JRadioButtonMenuItem item = new JRadioButtonMenuItem(value); // System.out.println("["+value+"]"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //get the category to color by String value = e.getActionCommand(); frame.currTable = frame.sampleMetadata; frame.colorPane.setSelectedIndex(elementType); if(elementType == 0) { ((TreeWindow)parent).colorBranchesByValue(value); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.coloringMenuItem.setSelected(false); ((TreeWindow)parent).tree.setColorBranches(true); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.coloringMenuItem.setEnabled(true); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.majorityColoringMenuItem.setEnabled(true); } else if(elementType == 1) ((TreeWindow)parent).colorLabelsByValue(value); frame.schemeList.setSelectedIndex(0); colorPanel.setCurrentValue(value); TableColumn column = colorPanel.getColorKeyTable().getColumnModel().getColumn(0); column.setHeaderValue(value); } }); colorByGroup.add(item); colorBySampleMetadataMenu.add(item); } // colorBySampleMetadataMenu.add(new JRadioButtonMenuItem("durf")); }
void resetColorBySampleMenu() { /* noColoringMenuItem.setSelected(true);*/ colorBySampleMetadataMenu.removeAll(); // colorBySampleMetadataMenu.add(new JRadioButtonMenuItem("hurf")); ArrayList<String> data = frame.sampleMetadata.getColumnNames(); // System.out.println(frame.sampleMetadata.getColumnNames().size()); for (int i = 0; i < data.size(); i++) { String value = data.get(i); JRadioButtonMenuItem item = new JRadioButtonMenuItem(value); // System.out.println("["+value+"]"); item.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //get the category to color by String value = e.getActionCommand(); frame.currTable = frame.sampleMetadata; frame.colorPane.setSelectedIndex(elementType); if(elementType == 0) { ((TreeWindow)parent).colorBranchesByValue(value); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.coloringMenuItem.setSelected(false); ((TreeWindow)parent).tree.setColorBranches(true); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.coloringMenuItem.setEnabled(true); ((TreeWindow)parent).treeEditToolbar.branchEditPanel.majorityColoringMenuItem.setEnabled(true); } else if(elementType == 1) ((TreeWindow)parent).colorLabelsByValue(value); frame.schemeList.setSelectedIndex(0); colorPanel.setCurrentValue(value); TableColumn column = colorPanel.getColorKeyTable().getColumnModel().getColumn(0); column.setHeaderValue(value); } }); colorByGroup.add(item); colorBySampleMetadataMenu.add(item); } // colorBySampleMetadataMenu.add(new JRadioButtonMenuItem("durf")); }
diff --git a/android/src/edu/ucla/cens/wetap/survey.java b/android/src/edu/ucla/cens/wetap/survey.java index 2037f86..c6b71b3 100644 --- a/android/src/edu/ucla/cens/wetap/survey.java +++ b/android/src/edu/ucla/cens/wetap/survey.java @@ -1,547 +1,547 @@ package edu.ucla.cens.wetap; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import android.content.Context; import android.content.Intent; import android.content.DialogInterface; import android.content.SharedPreferences; import android.view.View; import android.view.View.OnClickListener; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageView; import android.widget.Button; import android.widget.RadioButton; import android.widget.Toast; import android.widget.CheckBox; import android.widget.TableRow; import android.app.AlertDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import java.io.File; import java.util.Iterator; import java.util.List; import java.util.ArrayList; import java.util.Date; import edu.ucla.cens.wetap.survey_db; import edu.ucla.cens.wetap.survey_db.survey_db_row; public class survey extends Activity { private String TAG = "Survey"; private ArrayList<ArrayList<CheckBox>> group_box_list = new ArrayList<ArrayList<CheckBox>>(); private Button take_picture; private Button submit_button; //private Button clear_history; private ImageView image_thumbnail; private String filename = ""; private survey_db sdb; private SharedPreferences preferences; private final int GB_INDEX_OPER = 0; private final int GB_INDEX_TASTE = 1; private final int GB_INDEX_FLOW = 2; private final int GB_INDEX_WHEEL = 3; private final int GB_INDEX_CHILD = 4; private final int GB_INDEX_REFILL = 5; private final int GB_INDEX_REFILL_AUX = 6; private final int GB_INDEX_VIS = 7; private final int GB_INDEX_LOC = 8; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.survey); preferences = getSharedPreferences(getString(R.string.preferences), Activity.MODE_PRIVATE); // allow users to collect data even if they are not yet authenticated // let the survey_upload service make sure they are auth'd before // uploading... (lets users collect data without internet conn) //if (!preferences.getBoolean("authenticated", false)) { // Log.d(TAG, "exiting (not authenticated)"); // survey.this.finish(); // return; //} sdb = new survey_db(this); /* start location service */ - startService (new Intent(ctx, light_loc.class)); + startService (new Intent(survey.this, light_loc.class)); preferences.edit().putBoolean ("light_loc", true).commit (); Log.d(TAG, "gps listener and db are started"); ArrayList<CheckBox> lcb; // add operable boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.operable_functioning) ); lcb.add( (CheckBox) findViewById(R.id.operable_broken) ); lcb.add( (CheckBox) findViewById(R.id.operable_needs_repair) ); group_box_list.add(lcb); Log.d(TAG, "added operable boxes"); // add taste boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.taste_same) ); lcb.add( (CheckBox) findViewById(R.id.taste_good) ); lcb.add( (CheckBox) findViewById(R.id.taste_bad) ); lcb.add( (CheckBox) findViewById(R.id.taste_other) ); group_box_list.add(lcb); Log.d(TAG, "added taste boxes"); // add flow boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.flow_strong) ); lcb.add( (CheckBox) findViewById(R.id.flow_trickle) ); lcb.add( (CheckBox) findViewById(R.id.flow_too_strong) ); lcb.add( (CheckBox) findViewById(R.id.flow_cant_answer) ); group_box_list.add(lcb); Log.d(TAG, "added flow boxes"); // add access wheelchair box: lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_5_option_0) ); group_box_list.add(lcb); Log.d(TAG, "added wheelchair box"); // add access child box: lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_5_option_1) ); group_box_list.add(lcb); Log.d(TAG, "added child box"); // add access refill box: lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_5_option_2) ); group_box_list.add(lcb); Log.d(TAG, "added refill box"); // add alternate accessibility questions lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_6_option_0) ); lcb.add( (CheckBox) findViewById(R.id.question_6_option_1) ); lcb.add( (CheckBox) findViewById(R.id.question_6_option_2) ); group_box_list.add(lcb); Log.d(TAG, "added alternate accessibility boxes"); // add visibility boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.visibility_visible) ); lcb.add( (CheckBox) findViewById(R.id.visibility_hidden) ); group_box_list.add(lcb); Log.d(TAG, "added visibility boxes"); // add location boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.location_indoor) ); lcb.add( (CheckBox) findViewById(R.id.location_outdoors) ); group_box_list.add(lcb); Log.d(TAG, "added location boxes"); // add submit button submit_button = (Button) findViewById(R.id.upload_button); // add picture button take_picture = (Button) findViewById(R.id.picture_button); // add clear history button //clear_history = (Button) findViewById(R.id.clear_history_button); Log.d(TAG, "added buttons"); // add image thumbnail view image_thumbnail = (ImageView) findViewById(R.id.thumbnail); // add check box listeners for (int j = 0; j < group_box_list.size(); j++) { lcb = group_box_list.get(j); for (int i = 0; i < lcb.size(); i++) { CheckBox cb = (CheckBox) lcb.get(i); cb.setOnClickListener(check_box_listener); } } // add submit button listener submit_button.setOnClickListener(submit_button_listener); // add take picture button listener take_picture.setOnClickListener(take_picture_listener); // add clear history button listener //clear_history.setOnClickListener(clear_history_listener); // restore previous state (if available) if (savedInstanceState != null && savedInstanceState.getBoolean("started")) { for (int i = 0; i < group_box_list.size(); i++) { lcb = group_box_list.get(i); int k = savedInstanceState.getInt(Integer.toString(i)); for (int j = 0; j < lcb.size(); j++) { CheckBox cb = (CheckBox) lcb.get(j); if (j == k) { cb.setChecked(true); update_checkbox_status (cb); break; // } else { // cb.setChecked(false); } } } filename = savedInstanceState.getString("filename"); if ((null != filename) && (!filename.toString().equals(""))) { Bitmap bm = BitmapFactory.decodeFile(filename); if (bm != null) { take_picture.setText("Retake Picture"); image_thumbnail.setVisibility(View.VISIBLE); image_thumbnail.setImageBitmap(bm); } } } return; } @Override public boolean onCreateOptionsMenu (Menu m) { super.onCreateOptionsMenu (m); m.add (Menu.NONE, 0, Menu.NONE, "Home").setIcon (android.R.drawable.ic_menu_revert); m.add (Menu.NONE, 1, Menu.NONE, "Map").setIcon (android.R.drawable.ic_menu_mapmode); m.add (Menu.NONE, 2, Menu.NONE, "About").setIcon (android.R.drawable.ic_menu_info_details); m.add (Menu.NONE, 3, Menu.NONE, "Instructions").setIcon (android.R.drawable.ic_menu_help); return true; } @Override public boolean onOptionsItemSelected (MenuItem index) { Context ctx = survey.this; Intent i; switch (index.getItemId()) { case 0: i = new Intent (ctx, home.class); break; case 1: i = new Intent (ctx, map.class); break; case 2: i = new Intent (ctx, about.class); break; case 3: i = new Intent (ctx, instructions.class); break; default: return false; } ctx.startActivity (i); this.finish(); return true; } private void alert_no_gps() { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Yout GPS seems to be disabled, You need GPS to run this application. do you want to enable it?") .setCancelable(false) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { survey.this.startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 3); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(final DialogInterface dialog, final int id) { survey.this.finish(); } }); final AlertDialog alert = builder.create(); alert.show(); } // if this activity gets killed for any reason, save the status of the // check boxes so that they are filled in the next time it gets run public void onSaveInstanceState(Bundle savedInstanceState) { savedInstanceState.putBoolean("started", true); savedInstanceState.putString("filename", filename); List<CheckBox> lcb; CheckBox cb; for (int i = 0; i < group_box_list.size(); i++) { lcb = group_box_list.get(i); for (int j = 0; j < lcb.size(); j++) { cb = (CheckBox) lcb.get(j); if (cb.isChecked()) { savedInstanceState.putInt(Integer.toString(i), j); } } } super.onSaveInstanceState(savedInstanceState); } public void update_checkbox_status (CheckBox cb) { List<CheckBox> lcb; boolean checked = cb.isChecked(); if (R.id.question_5_option_2 == cb.getId()) { TableRow tr = (TableRow) findViewById(R.id.question_6_row); tr.setVisibility(checked ? View.GONE : View.VISIBLE); return; } if (R.id.operable_broken == cb.getId()) { View v = findViewById(R.id.taste_row); v.setVisibility(checked ? View.GONE : View.VISIBLE); v = (TableRow) findViewById(R.id.flow_row); v.setVisibility(checked ? View.GONE : View.VISIBLE); CheckBox ncb = (CheckBox) findViewById(R.id.question_5_option_2); ncb.setVisibility(checked ? View.GONE : View.VISIBLE); if (false == ncb.isChecked()) { v = findViewById(R.id.question_6_row); v.setVisibility(checked ? View.GONE : View.VISIBLE); } } // dont do anything if this box was unchecked if (false == checked) { return; } for (int i = 0; i < group_box_list.size(); i++) { lcb = group_box_list.get(i); int index = lcb.indexOf(cb); // continue on if the check box wasn't found in this checkbox group if(-1 == index) { continue; } // switch all of the other checkboxes in this group off for (i = 0; i < lcb.size(); i++) { cb = (CheckBox) lcb.get(i); if (i != index && cb.isChecked()) { cb.setChecked(false); checked = false; if (R.id.operable_broken == cb.getId()) { View v = findViewById(R.id.taste_row); v.setVisibility(checked ? View.GONE : View.VISIBLE); v = findViewById(R.id.flow_row); v.setVisibility(checked ? View.GONE : View.VISIBLE); v = findViewById(R.id.question_5_row); v.setVisibility(checked ? View.GONE : View.VISIBLE); CheckBox ncb = (CheckBox) findViewById(R.id.question_5_option_2); ncb.setVisibility(checked ? View.GONE : View.VISIBLE); if (false == ncb.isChecked()) { v = findViewById(R.id.question_6_row); v.setVisibility(checked ? View.GONE : View.VISIBLE); } } } } return; } } OnClickListener check_box_listener = new OnClickListener() { public void onClick(View v) { update_checkbox_status ((CheckBox) v); } }; OnClickListener submit_button_listener = new OnClickListener() { private String get_group_result (int index) { List<CheckBox> lcb = group_box_list.get(index); for (int i = 0; i < lcb.size(); i++) { CheckBox cb = (CheckBox) lcb.get(i); if (cb.isChecked()) { return Integer.toString(i+1); } } return "0"; } public void onClick(View v) { Date d = new Date(); String q_location = "0"; String q_visibility = "0"; String q_operable = "0"; String q_wheel = "0"; String q_child = "0"; String q_refill = "0"; String q_refill_aux = "0"; String q_taste = "0"; String q_flow = "0"; q_location = get_group_result (GB_INDEX_LOC); q_visibility = get_group_result (GB_INDEX_VIS); q_operable = get_group_result (GB_INDEX_OPER); q_wheel = get_group_result (GB_INDEX_WHEEL); q_child = get_group_result (GB_INDEX_CHILD); q_refill = get_group_result (GB_INDEX_REFILL); q_refill_aux = get_group_result (GB_INDEX_REFILL_AUX); q_taste = get_group_result (GB_INDEX_TASTE); q_flow = get_group_result (GB_INDEX_FLOW); /* make sure they dont submit an incomplete survey */ if (q_location.equals("0") || q_visibility.equals("0") || q_operable.equals("0")) { Toast .makeText (survey.this, "You have not answered one or more questions. Please fill them all out.", Toast.LENGTH_LONG) .show(); return; } if (!q_operable.equals("2") && !q_refill.equals("1") && q_refill_aux.equals("0")) { Toast .makeText (survey.this, "You have not marked why you couldn't refill from this fountain.", Toast.LENGTH_LONG) .show(); return; } if (!q_operable.equals("2") && (q_taste.equals("0") || q_flow.equals("0"))) { Toast .makeText (survey.this, "You must fill out both the taste and flow questions.", Toast.LENGTH_LONG) .show(); return; } /* if the fountain was broken then throw out anything that couldn't * have been answered */ if (q_operable.equals("2")) { q_refill = q_refill_aux = q_taste = q_flow = "0"; } /* if they could refill a bottle at the fountain then throw out * refill aux questions */ if (q_refill.equals("1")) { q_refill_aux = "0"; } String longitude = ""; String latitude = ""; String time = Long.toString(d.getTime()); String photo_filename = filename; sdb.open(); long row_id = sdb.createEntry(q_location, q_visibility, q_operable, q_wheel, q_child, q_refill, q_refill_aux, q_taste, q_flow, longitude, latitude, time, getString(R.string.version), photo_filename); sdb.close(); sdb.open(); survey_db_row sr = sdb.fetchEntry(row_id); sdb.close(); Log.d("SUBMIT SURVEY", Long.toString(sr.row_id) + ", " + sr.q_taste + ", " + sr.q_visibility + ", " + sr.q_operable + ", " + sr.q_flow + ", " + sr.q_location + ", " + sr.longitude + ", " + sr.latitude + ", " + sr.time + ", " + sr.version + ", " + sr.photo_filename + "."); /* start location service */ if (!preferences.getBoolean("light_loc", false)) { startService (new Intent(survey.this, light_loc.class)); preferences.edit().putBoolean ("light_loc", true).commit (); } // popup success toast and return to home page Toast.makeText(survey.this, "Survey successfully submitted!", Toast.LENGTH_LONG).show(); survey.this.startActivity (new Intent(survey.this, home.class)); survey.this.finish(); } }; OnClickListener take_picture_listener = new OnClickListener() { public void onClick(View v) { Intent photo_intent = new Intent(survey.this, photo.class); startActivityForResult(photo_intent, 0); } }; OnClickListener clear_history_listener = new OnClickListener() { public void onClick(View v) { sdb.open(); ArrayList<survey_db_row> sr_list = sdb.fetchAllEntries(); sdb.close(); for (int i = 0; i < sr_list.size(); i++) { survey_db_row sr = sr_list.get(i); File file = null; if ((sr.photo_filename != null) && (!sr.photo_filename.toString().equals(""))) { file = new File(sr.photo_filename.toString()); } if(file != null) { file.delete(); } sdb.open(); sdb.deleteEntry(sr.row_id); sdb.close(); } /* sdb.open(); sdb.refresh_db(); sdb.close(); */ } }; protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (RESULT_CANCELED != resultCode) { filename = data.getAction().toString(); if ((null != filename) && (!filename.toString().equals(""))) { Bitmap bm = BitmapFactory.decodeFile(filename); if (bm != null) { take_picture.setText("Retake Picture"); image_thumbnail.setVisibility(View.VISIBLE); image_thumbnail.setImageBitmap(bm); } } } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.survey); preferences = getSharedPreferences(getString(R.string.preferences), Activity.MODE_PRIVATE); // allow users to collect data even if they are not yet authenticated // let the survey_upload service make sure they are auth'd before // uploading... (lets users collect data without internet conn) //if (!preferences.getBoolean("authenticated", false)) { // Log.d(TAG, "exiting (not authenticated)"); // survey.this.finish(); // return; //} sdb = new survey_db(this); /* start location service */ startService (new Intent(ctx, light_loc.class)); preferences.edit().putBoolean ("light_loc", true).commit (); Log.d(TAG, "gps listener and db are started"); ArrayList<CheckBox> lcb; // add operable boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.operable_functioning) ); lcb.add( (CheckBox) findViewById(R.id.operable_broken) ); lcb.add( (CheckBox) findViewById(R.id.operable_needs_repair) ); group_box_list.add(lcb); Log.d(TAG, "added operable boxes"); // add taste boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.taste_same) ); lcb.add( (CheckBox) findViewById(R.id.taste_good) ); lcb.add( (CheckBox) findViewById(R.id.taste_bad) ); lcb.add( (CheckBox) findViewById(R.id.taste_other) ); group_box_list.add(lcb); Log.d(TAG, "added taste boxes"); // add flow boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.flow_strong) ); lcb.add( (CheckBox) findViewById(R.id.flow_trickle) ); lcb.add( (CheckBox) findViewById(R.id.flow_too_strong) ); lcb.add( (CheckBox) findViewById(R.id.flow_cant_answer) ); group_box_list.add(lcb); Log.d(TAG, "added flow boxes"); // add access wheelchair box: lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_5_option_0) ); group_box_list.add(lcb); Log.d(TAG, "added wheelchair box"); // add access child box: lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_5_option_1) ); group_box_list.add(lcb); Log.d(TAG, "added child box"); // add access refill box: lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_5_option_2) ); group_box_list.add(lcb); Log.d(TAG, "added refill box"); // add alternate accessibility questions lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_6_option_0) ); lcb.add( (CheckBox) findViewById(R.id.question_6_option_1) ); lcb.add( (CheckBox) findViewById(R.id.question_6_option_2) ); group_box_list.add(lcb); Log.d(TAG, "added alternate accessibility boxes"); // add visibility boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.visibility_visible) ); lcb.add( (CheckBox) findViewById(R.id.visibility_hidden) ); group_box_list.add(lcb); Log.d(TAG, "added visibility boxes"); // add location boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.location_indoor) ); lcb.add( (CheckBox) findViewById(R.id.location_outdoors) ); group_box_list.add(lcb); Log.d(TAG, "added location boxes"); // add submit button submit_button = (Button) findViewById(R.id.upload_button); // add picture button take_picture = (Button) findViewById(R.id.picture_button); // add clear history button //clear_history = (Button) findViewById(R.id.clear_history_button); Log.d(TAG, "added buttons"); // add image thumbnail view image_thumbnail = (ImageView) findViewById(R.id.thumbnail); // add check box listeners for (int j = 0; j < group_box_list.size(); j++) { lcb = group_box_list.get(j); for (int i = 0; i < lcb.size(); i++) { CheckBox cb = (CheckBox) lcb.get(i); cb.setOnClickListener(check_box_listener); } } // add submit button listener submit_button.setOnClickListener(submit_button_listener); // add take picture button listener take_picture.setOnClickListener(take_picture_listener); // add clear history button listener //clear_history.setOnClickListener(clear_history_listener); // restore previous state (if available) if (savedInstanceState != null && savedInstanceState.getBoolean("started")) { for (int i = 0; i < group_box_list.size(); i++) { lcb = group_box_list.get(i); int k = savedInstanceState.getInt(Integer.toString(i)); for (int j = 0; j < lcb.size(); j++) { CheckBox cb = (CheckBox) lcb.get(j); if (j == k) { cb.setChecked(true); update_checkbox_status (cb); break; // } else { // cb.setChecked(false); } } } filename = savedInstanceState.getString("filename"); if ((null != filename) && (!filename.toString().equals(""))) { Bitmap bm = BitmapFactory.decodeFile(filename); if (bm != null) { take_picture.setText("Retake Picture"); image_thumbnail.setVisibility(View.VISIBLE); image_thumbnail.setImageBitmap(bm); } } } return; }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.survey); preferences = getSharedPreferences(getString(R.string.preferences), Activity.MODE_PRIVATE); // allow users to collect data even if they are not yet authenticated // let the survey_upload service make sure they are auth'd before // uploading... (lets users collect data without internet conn) //if (!preferences.getBoolean("authenticated", false)) { // Log.d(TAG, "exiting (not authenticated)"); // survey.this.finish(); // return; //} sdb = new survey_db(this); /* start location service */ startService (new Intent(survey.this, light_loc.class)); preferences.edit().putBoolean ("light_loc", true).commit (); Log.d(TAG, "gps listener and db are started"); ArrayList<CheckBox> lcb; // add operable boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.operable_functioning) ); lcb.add( (CheckBox) findViewById(R.id.operable_broken) ); lcb.add( (CheckBox) findViewById(R.id.operable_needs_repair) ); group_box_list.add(lcb); Log.d(TAG, "added operable boxes"); // add taste boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.taste_same) ); lcb.add( (CheckBox) findViewById(R.id.taste_good) ); lcb.add( (CheckBox) findViewById(R.id.taste_bad) ); lcb.add( (CheckBox) findViewById(R.id.taste_other) ); group_box_list.add(lcb); Log.d(TAG, "added taste boxes"); // add flow boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.flow_strong) ); lcb.add( (CheckBox) findViewById(R.id.flow_trickle) ); lcb.add( (CheckBox) findViewById(R.id.flow_too_strong) ); lcb.add( (CheckBox) findViewById(R.id.flow_cant_answer) ); group_box_list.add(lcb); Log.d(TAG, "added flow boxes"); // add access wheelchair box: lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_5_option_0) ); group_box_list.add(lcb); Log.d(TAG, "added wheelchair box"); // add access child box: lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_5_option_1) ); group_box_list.add(lcb); Log.d(TAG, "added child box"); // add access refill box: lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_5_option_2) ); group_box_list.add(lcb); Log.d(TAG, "added refill box"); // add alternate accessibility questions lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.question_6_option_0) ); lcb.add( (CheckBox) findViewById(R.id.question_6_option_1) ); lcb.add( (CheckBox) findViewById(R.id.question_6_option_2) ); group_box_list.add(lcb); Log.d(TAG, "added alternate accessibility boxes"); // add visibility boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.visibility_visible) ); lcb.add( (CheckBox) findViewById(R.id.visibility_hidden) ); group_box_list.add(lcb); Log.d(TAG, "added visibility boxes"); // add location boxes lcb = new ArrayList<CheckBox>(); lcb.add( (CheckBox) findViewById(R.id.location_indoor) ); lcb.add( (CheckBox) findViewById(R.id.location_outdoors) ); group_box_list.add(lcb); Log.d(TAG, "added location boxes"); // add submit button submit_button = (Button) findViewById(R.id.upload_button); // add picture button take_picture = (Button) findViewById(R.id.picture_button); // add clear history button //clear_history = (Button) findViewById(R.id.clear_history_button); Log.d(TAG, "added buttons"); // add image thumbnail view image_thumbnail = (ImageView) findViewById(R.id.thumbnail); // add check box listeners for (int j = 0; j < group_box_list.size(); j++) { lcb = group_box_list.get(j); for (int i = 0; i < lcb.size(); i++) { CheckBox cb = (CheckBox) lcb.get(i); cb.setOnClickListener(check_box_listener); } } // add submit button listener submit_button.setOnClickListener(submit_button_listener); // add take picture button listener take_picture.setOnClickListener(take_picture_listener); // add clear history button listener //clear_history.setOnClickListener(clear_history_listener); // restore previous state (if available) if (savedInstanceState != null && savedInstanceState.getBoolean("started")) { for (int i = 0; i < group_box_list.size(); i++) { lcb = group_box_list.get(i); int k = savedInstanceState.getInt(Integer.toString(i)); for (int j = 0; j < lcb.size(); j++) { CheckBox cb = (CheckBox) lcb.get(j); if (j == k) { cb.setChecked(true); update_checkbox_status (cb); break; // } else { // cb.setChecked(false); } } } filename = savedInstanceState.getString("filename"); if ((null != filename) && (!filename.toString().equals(""))) { Bitmap bm = BitmapFactory.decodeFile(filename); if (bm != null) { take_picture.setText("Retake Picture"); image_thumbnail.setVisibility(View.VISIBLE); image_thumbnail.setImageBitmap(bm); } } } return; }
diff --git a/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/XtextResourceChecker.java b/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/XtextResourceChecker.java index 8031415b7..1ebb62311 100644 --- a/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/XtextResourceChecker.java +++ b/plugins/org.eclipse.xtext.ui.core/src/org/eclipse/xtext/ui/core/editor/XtextResourceChecker.java @@ -1,245 +1,247 @@ /******************************************************************************* * Copyright (c) 2008 itemis AG (http://www.itemis.eu) 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 * *******************************************************************************/ package org.eclipse.xtext.ui.core.editor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IMarker; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.jobs.ISchedulingRule; import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EValidator; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.util.Diagnostician; import org.eclipse.ui.actions.WorkspaceModifyOperation; import org.eclipse.xtext.parsetree.AbstractNode; import org.eclipse.xtext.parsetree.NodeAdapter; import org.eclipse.xtext.parsetree.NodeUtil; import org.eclipse.xtext.resource.XtextResource; /** * @author Dennis H�bner - Initial contribution and API * */ public class XtextResourceChecker { private static final int MAX_ERRORS = 99; private static final Logger log = Logger.getLogger(XtextResourceChecker.class); private XtextResourceChecker() { } /** * @author Sven Efftinge - Initial contribution and API * */ public static final class AddMarkersOperation extends WorkspaceModifyOperation { /** * */ private final List<Map<String, Object>> issues; private final IFile file; private final String markerId; private final boolean deleteMarkers; /** * @param rule * @param issues */ public AddMarkersOperation(ISchedulingRule rule, List<Map<String, Object>> issues, IFile file, String markerId, boolean deleteMarkers) { super(rule); this.issues = issues; this.file = file; this.markerId = markerId; this.deleteMarkers = deleteMarkers; } @Override protected void execute(final IProgressMonitor monitor) throws CoreException, InvocationTargetException, InterruptedException { if (!file.exists()) return; if (deleteMarkers) file.deleteMarkers(markerId, true, IResource.DEPTH_INFINITE); if (!issues.isEmpty()) { // update for (Map<String, Object> map : issues) { if (monitor.isCanceled()) return; IMarker marker = file.createMarker(markerId); Object lNr = map.get(IMarker.LINE_NUMBER); String lineNR = ""; if (lNr != null) { lineNR = "line: " + lNr + " "; } map.put(IMarker.LOCATION, lineNR + file.getFullPath().toString()); marker.setAttributes(map); } } } } public static void addMarkers(final IFile file, final List<Map<String, Object>> issues, boolean deleteOldMarkers, IProgressMonitor monitor) { try { new AddMarkersOperation(ResourcesPlugin.getWorkspace().getRuleFactory().markerRule(file), issues, file, EValidator.MARKER, deleteOldMarkers) .run(monitor); } catch (InvocationTargetException e) { log.error("Could not create marker.", e); } catch (InterruptedException e) { log.error("Could not create marker.", e); } } /** * Checks an {@link XtextResource} * * @param resource * @return a {@link List} of {@link IMarker} attributes */ public static List<Map<String, Object>> check(final Resource resource, Map<?, ?> context, IProgressMonitor monitor) { List<Map<String, Object>> markers = new ArrayList<Map<String, Object>>(); try { // Syntactical errors // Collect EMF Resource Diagnostics - for (org.eclipse.emf.ecore.resource.Resource.Diagnostic error : resource.getErrors()) - markers.add(markerFromXtextResourceDiagnostic(error, IMarker.SEVERITY_ERROR)); + for(int i = 0 ; i < resource.getErrors().size(); i++) { + markers.add(markerFromXtextResourceDiagnostic(resource.getErrors().get(i), IMarker.SEVERITY_ERROR)); + } if (monitor.isCanceled()) return null; - for (org.eclipse.emf.ecore.resource.Resource.Diagnostic warning : resource.getWarnings()) - markers.add(markerFromXtextResourceDiagnostic(warning, IMarker.SEVERITY_WARNING)); + for(int i = 0 ; i < resource.getWarnings().size(); i++) { + markers.add(markerFromXtextResourceDiagnostic(resource.getWarnings().get(i), IMarker.SEVERITY_WARNING)); + } if (monitor.isCanceled()) return null; boolean syntaxDiagFail = !markers.isEmpty(); logCheckStatus(resource, syntaxDiagFail, "Syntax"); for (EObject ele : resource.getContents()) { try { Diagnostic diagnostic = Diagnostician.INSTANCE.validate(ele, context); if (monitor.isCanceled()) return null; if (!diagnostic.getChildren().isEmpty()) { for (Diagnostic childDiagnostic : diagnostic.getChildren()) { Map<String, Object> marker = markerFromEValidatorDiagnostic(childDiagnostic); if (marker != null) { markers.add(marker); if (markers.size() > MAX_ERRORS) return markers; } } } else { Map<String, Object> marker = markerFromEValidatorDiagnostic(diagnostic); if (marker != null) { markers.add(marker); if (markers.size() > MAX_ERRORS) return markers; } } } catch (RuntimeException e) { log.error(e.getMessage(), e); } } } catch (RuntimeException e) { log.error(e.getMessage(), e); } return markers; } private static void logCheckStatus(final Resource resource, boolean parserDiagFail, String string) { if (log.isDebugEnabled()) { log.debug(string + " check " + (parserDiagFail ? "FAIL" : "OK") + "! Resource: " + resource.getURI()); } } private static Map<String, Object> markerFromXtextResourceDiagnostic( org.eclipse.emf.ecore.resource.Resource.Diagnostic diagnostic, Object severity) { Map<String, Object> map = new HashMap<String, Object>(); map.put(IMarker.SEVERITY, severity); map.put(IMarker.LINE_NUMBER, diagnostic.getLine()); map.put(IMarker.MESSAGE, diagnostic.getMessage()); map.put(IMarker.PRIORITY, Integer.valueOf(IMarker.PRIORITY_LOW)); if (diagnostic instanceof org.eclipse.xtext.diagnostics.Diagnostic) { org.eclipse.xtext.diagnostics.Diagnostic xtextDiagnostic = (org.eclipse.xtext.diagnostics.Diagnostic) diagnostic; map.put(IMarker.CHAR_START, xtextDiagnostic.getOffset()); map.put(IMarker.CHAR_END, xtextDiagnostic.getOffset() + xtextDiagnostic.getLength()); } return map; } private static Map<String, Object> markerFromEValidatorDiagnostic(Diagnostic diagnostic) { if (diagnostic.getSeverity() == Diagnostic.OK) return null; Map<String, Object> map = new HashMap<String, Object>(); int sever = IMarker.SEVERITY_ERROR; switch (diagnostic.getSeverity()) { case Diagnostic.WARNING: sever = IMarker.SEVERITY_WARNING; break; case Diagnostic.INFO: sever = IMarker.SEVERITY_INFO; break; } map.put(IMarker.SEVERITY, sever); Iterator<?> data = diagnostic.getData().iterator(); // causer is the first element see Diagnostician.getData Object causer = data.next(); if (causer instanceof EObject) { EObject ele = (EObject) causer; NodeAdapter nodeAdapter = NodeUtil.getNodeAdapter(ele); if (nodeAdapter != null) { AbstractNode parserNode = nodeAdapter.getParserNode(); // feature is the second element see Diagnostician.getData Object feature = data.hasNext() ? data.next() : null; EStructuralFeature structuralFeature = resolveStructuralFeature(ele, feature); if (structuralFeature != null) { List<AbstractNode> nodes = NodeUtil.findNodesForFeature(ele, structuralFeature); if (!nodes.isEmpty()) parserNode = nodes.iterator().next(); } map.put(IMarker.LINE_NUMBER, Integer.valueOf(parserNode.getLine())); int offset = parserNode.getOffset(); map.put(IMarker.CHAR_START, Integer.valueOf(offset)); map.put(IMarker.CHAR_END, Integer.valueOf(offset + parserNode.getLength())); } } map.put(IMarker.MESSAGE, diagnostic.getMessage()); map.put(IMarker.PRIORITY, Integer.valueOf(IMarker.PRIORITY_LOW)); return map; } private static EStructuralFeature resolveStructuralFeature(EObject ele, Object feature) { if (feature instanceof String) { return ele.eClass().getEStructuralFeature((String) feature); } else if (feature instanceof EStructuralFeature) { return (EStructuralFeature) feature; } else if (feature instanceof Integer) { return ele.eClass().getEStructuralFeature((Integer) feature); } return null; } }
false
true
public static List<Map<String, Object>> check(final Resource resource, Map<?, ?> context, IProgressMonitor monitor) { List<Map<String, Object>> markers = new ArrayList<Map<String, Object>>(); try { // Syntactical errors // Collect EMF Resource Diagnostics for (org.eclipse.emf.ecore.resource.Resource.Diagnostic error : resource.getErrors()) markers.add(markerFromXtextResourceDiagnostic(error, IMarker.SEVERITY_ERROR)); if (monitor.isCanceled()) return null; for (org.eclipse.emf.ecore.resource.Resource.Diagnostic warning : resource.getWarnings()) markers.add(markerFromXtextResourceDiagnostic(warning, IMarker.SEVERITY_WARNING)); if (monitor.isCanceled()) return null; boolean syntaxDiagFail = !markers.isEmpty(); logCheckStatus(resource, syntaxDiagFail, "Syntax"); for (EObject ele : resource.getContents()) { try { Diagnostic diagnostic = Diagnostician.INSTANCE.validate(ele, context); if (monitor.isCanceled()) return null; if (!diagnostic.getChildren().isEmpty()) { for (Diagnostic childDiagnostic : diagnostic.getChildren()) { Map<String, Object> marker = markerFromEValidatorDiagnostic(childDiagnostic); if (marker != null) { markers.add(marker); if (markers.size() > MAX_ERRORS) return markers; } } } else { Map<String, Object> marker = markerFromEValidatorDiagnostic(diagnostic); if (marker != null) { markers.add(marker); if (markers.size() > MAX_ERRORS) return markers; } } } catch (RuntimeException e) { log.error(e.getMessage(), e); } } } catch (RuntimeException e) { log.error(e.getMessage(), e); } return markers; }
public static List<Map<String, Object>> check(final Resource resource, Map<?, ?> context, IProgressMonitor monitor) { List<Map<String, Object>> markers = new ArrayList<Map<String, Object>>(); try { // Syntactical errors // Collect EMF Resource Diagnostics for(int i = 0 ; i < resource.getErrors().size(); i++) { markers.add(markerFromXtextResourceDiagnostic(resource.getErrors().get(i), IMarker.SEVERITY_ERROR)); } if (monitor.isCanceled()) return null; for(int i = 0 ; i < resource.getWarnings().size(); i++) { markers.add(markerFromXtextResourceDiagnostic(resource.getWarnings().get(i), IMarker.SEVERITY_WARNING)); } if (monitor.isCanceled()) return null; boolean syntaxDiagFail = !markers.isEmpty(); logCheckStatus(resource, syntaxDiagFail, "Syntax"); for (EObject ele : resource.getContents()) { try { Diagnostic diagnostic = Diagnostician.INSTANCE.validate(ele, context); if (monitor.isCanceled()) return null; if (!diagnostic.getChildren().isEmpty()) { for (Diagnostic childDiagnostic : diagnostic.getChildren()) { Map<String, Object> marker = markerFromEValidatorDiagnostic(childDiagnostic); if (marker != null) { markers.add(marker); if (markers.size() > MAX_ERRORS) return markers; } } } else { Map<String, Object> marker = markerFromEValidatorDiagnostic(diagnostic); if (marker != null) { markers.add(marker); if (markers.size() > MAX_ERRORS) return markers; } } } catch (RuntimeException e) { log.error(e.getMessage(), e); } } } catch (RuntimeException e) { log.error(e.getMessage(), e); } return markers; }
diff --git a/src/org/omegat/filters2/master/FiltersTableModel.java b/src/org/omegat/filters2/master/FiltersTableModel.java index efc03d9d..4f0de8a9 100644 --- a/src/org/omegat/filters2/master/FiltersTableModel.java +++ b/src/org/omegat/filters2/master/FiltersTableModel.java @@ -1,128 +1,128 @@ /************************************************************************** OmegaT - Computer Assisted Translation (CAT) tool with fuzzy matching, translation memory, keyword search, glossaries, and translation leveraging into updated projects. Copyright (C) 2000-2006 Keith Godfrey and Maxym Mykhalchuk Home page: http://www.omegat.org/ Support center: http://groups.yahoo.com/group/OmegaT/ 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA **************************************************************************/ package org.omegat.filters2.master; import gen.core.filters.Filter; import gen.core.filters.Filters; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.TreeMap; import javax.swing.table.AbstractTableModel; import org.omegat.filters2.IFilter; import org.omegat.util.OStrings; /** * Wrapper around all the file filter classes. Is a JavaBean, so that it's easy * to write/read it to/from XML file and provides a table model. * * @author Maxym Mykhalchuk */ public class FiltersTableModel extends AbstractTableModel { private final List<Filter> filters; private final Map<String, String> filterNames = new TreeMap<String, String>(); public FiltersTableModel(final Filters config) { filters = new ArrayList<Filter>(); // add only exist filters for (Filter f : config.getFilter()) { IFilter fi = FilterMaster.getInstance().getFilterInstance(f.getClassName()); - filterNames.put(f.getClassName(), fi.getFileFormatName()); if (fi != null) { // filter exist filters.add(f); + filterNames.put(f.getClassName(), fi.getFileFormatName()); } } } // //////////////////////////////////////////////////////////////////////// // TableModel implementation // //////////////////////////////////////////////////////////////////////// public int getColumnCount() { return 2; } public String getColumnName(int columnIndex) { switch (columnIndex) { case 0: return OStrings.getString("FILTERS_FILE_FORMAT"); case 1: return OStrings.getString("FILTERS_ON"); } return null; } public Class<?> getColumnClass(int columnIndex) { switch (columnIndex) { case 0: return String.class; case 1: return Boolean.class; } return null; } public int getRowCount() { return filters.size(); } public Object getValueAt(int rowIndex, int columnIndex) { Filter filter = filters.get(rowIndex); switch (columnIndex) { case 0: return filterNames.get(filter.getClassName()); case 1: return new Boolean(filter.isEnabled()); } return null; } public void setValueAt(Object aValue, int rowIndex, int columnIndex) { Filter filter = filters.get(rowIndex); switch (columnIndex) { case 1: filter.setEnabled(((Boolean) aValue).booleanValue()); break; default: throw new IllegalArgumentException(OStrings.getString("FILTERS_ERROR_COLUMN_INDEX_NOT_1")); } } public boolean isCellEditable(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return false; case 1: return true; } return false; } }
false
true
public FiltersTableModel(final Filters config) { filters = new ArrayList<Filter>(); // add only exist filters for (Filter f : config.getFilter()) { IFilter fi = FilterMaster.getInstance().getFilterInstance(f.getClassName()); filterNames.put(f.getClassName(), fi.getFileFormatName()); if (fi != null) { // filter exist filters.add(f); } } }
public FiltersTableModel(final Filters config) { filters = new ArrayList<Filter>(); // add only exist filters for (Filter f : config.getFilter()) { IFilter fi = FilterMaster.getInstance().getFilterInstance(f.getClassName()); if (fi != null) { // filter exist filters.add(f); filterNames.put(f.getClassName(), fi.getFileFormatName()); } } }
diff --git a/src/org/torproject/android/SettingsPreferences.java b/src/org/torproject/android/SettingsPreferences.java index 8137548..a61c5d9 100644 --- a/src/org/torproject/android/SettingsPreferences.java +++ b/src/org/torproject/android/SettingsPreferences.java @@ -1,33 +1,33 @@ /* Copyright (c) 2009, Nathan Freitas, Orbot / The Guardian Project - http://openideals.com/guardian */ /* See LICENSE for licensing information */ package org.torproject.android; import org.torproject.android.service.TorServiceUtils; import android.os.Bundle; import android.preference.PreferenceActivity; import android.util.Log; public class SettingsPreferences extends PreferenceActivity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); if (!TorServiceUtils.hasRoot()) - getPreferenceScreen().getPreference(3).setEnabled(false); + getPreferenceScreen().getPreference(0).setEnabled(false); } /* (non-Javadoc) * @see android.app.Activity#onStop() */ @Override protected void onStop() { super.onStop(); Log.i(getClass().getName(),"Exiting Preferences"); } }
true
true
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); if (!TorServiceUtils.hasRoot()) getPreferenceScreen().getPreference(3).setEnabled(false); }
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); if (!TorServiceUtils.hasRoot()) getPreferenceScreen().getPreference(0).setEnabled(false); }
diff --git a/modules/world/avatarbase/src/classes/org/jdesktop/wonderland/modules/avatarbase/client/jme/cellrenderer/NameTagNode.java b/modules/world/avatarbase/src/classes/org/jdesktop/wonderland/modules/avatarbase/client/jme/cellrenderer/NameTagNode.java index f70f2e65e..93117f13e 100644 --- a/modules/world/avatarbase/src/classes/org/jdesktop/wonderland/modules/avatarbase/client/jme/cellrenderer/NameTagNode.java +++ b/modules/world/avatarbase/src/classes/org/jdesktop/wonderland/modules/avatarbase/client/jme/cellrenderer/NameTagNode.java @@ -1,343 +1,344 @@ /** * Project Wonderland * * Copyright (c) 2004-2009, Sun Microsystems, Inc., All Rights Reserved * * Redistributions in source code form must reproduce the above * copyright and this condition. * * The contents of this file are subject to the GNU General Public * License, Version 2 (the "License"); you may not use this file * except in compliance with the License. A copy of the License is * available at http://www.opensource.org/licenses/gpl-license.php. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied * this code. */ package org.jdesktop.wonderland.modules.avatarbase.client.jme.cellrenderer; import com.jme.math.Matrix3f; import com.jme.math.Vector3f; import com.jme.scene.Node; import com.jme.scene.Spatial; import org.jdesktop.mtgame.processor.WorkProcessor.WorkCommit; import org.jdesktop.wonderland.client.jme.utils.TextLabel2D; import org.jdesktop.wonderland.client.jme.ClientContextJME; import java.awt.Color; import java.awt.Font; import java.util.HashMap; import java.util.logging.Logger; /** * TODO make this a component * * @author jprovino * @author nsimpson */ public class NameTagNode extends Node { private static final Logger logger = Logger.getLogger(NameTagNode.class.getName()); public enum EventType { STARTED_SPEAKING, STOPPED_SPEAKING, MUTE, UNMUTE, CHANGE_NAME, ENTERED_CONE_OF_SILENCE, EXITED_CONE_OF_SILENCE, HIDE, SMALL_FONT, REGULAR_FONT, LARGE_FONT } // colors public static final Color SPEAKING_COLOR = Color.RED; public static final Color NOT_SPEAKING_COLOR = Color.WHITE; public static final Color CONE_OF_SILENCE_COLOR = Color.BLACK; private Color foregroundColor = NOT_SPEAKING_COLOR; private Color backgroundColor = new Color(0f, 0f, 0f); // fonts public static final String DEFAULT_FONT_NAME = "SANS_SERIF"; public static final String DEFAULT_FONT_NAME_TYPE = "PLAIN"; public static final String DEFAULT_FONT_ALIAS_TYPE = "ITALIC"; public static final int DEFAULT_FONT_SIZE = 32; public static final Font REAL_NAME_FONT = fontDecode(DEFAULT_FONT_NAME, DEFAULT_FONT_NAME_TYPE, DEFAULT_FONT_SIZE); public static final Font ALIAS_NAME_FONT = fontDecode(DEFAULT_FONT_NAME, DEFAULT_FONT_ALIAS_TYPE, DEFAULT_FONT_SIZE); private int fontSize = DEFAULT_FONT_SIZE; private Font currentFont = REAL_NAME_FONT; // name tag heights public static final float SMALL_SIZE = 0.2f; public static final float REGULAR_SIZE = 0.3f; public static final float LARGE_SIZE = 0.5f; private float currentHeight = REGULAR_SIZE; // status indicators public static final String LEFT_MUTE = "["; public static final String RIGHT_MUTE = "]"; public static final String SPEAKING = "..."; private boolean inConeOfSilence; private boolean isSpeaking; private boolean isMuted; private boolean labelHidden; // private boolean done; private TextLabel2D label = null; private final float heightAbove; private String name; private Spatial q; private String usernameAlias; private boolean visible; private static HashMap<String, NameTagNode> nameTagMap = new HashMap(); private static Font fontDecode(String fontName, String fontType, int fontSize) { return Font.decode(fontName + " " + fontType + " " + fontSize); } public NameTagNode(String name, float heightAbove) { this.name = name; this.heightAbove = heightAbove; visible = true; nameTagMap.put(name, this); setLabelText(name); } public void done() { if (done) { return; } done = true; nameTagMap.remove(name); detachChild(q); } public static String getDisplayName(String name, boolean isSpeaking, boolean isMuted) { if (isMuted) { return LEFT_MUTE + name + RIGHT_MUTE; } if (isSpeaking) { return name + SPEAKING; } return name; } public static String getUsername(String name) { String s = name.replaceAll("\\" + LEFT_MUTE, ""); s = s.replaceAll("\\" + RIGHT_MUTE, ""); return s.replaceAll("\\" + SPEAKING, ""); } public void setForegroundColor(Color foregroundColor) { this.foregroundColor = foregroundColor; } public Color getForegroundColor() { return foregroundColor; } public void setBackgroundColor(Color backgroundColor) { this.backgroundColor = backgroundColor; } public Color getBackgroundColor() { return backgroundColor; } public void setLabelText(String labelText) { this.name = labelText; } public void setFont(Font font) { currentFont = font; } public void setFontSize(int fontSize) { this.fontSize = fontSize; } public void setHeight(float height) { currentHeight = height; } public void setVisible(boolean visible) { this.visible = visible; if (visible) { updateLabel(getDisplayName(name, isSpeaking, isMuted)); } else { removeLabel(); } } /** * Returns whether the name tag is visible. */ public boolean isVisible() { return visible; } public static void setMyNameTag(EventType eventType, String username, String usernameAlias) { NameTagNode nameTag = nameTagMap.get(username); if (nameTag == null) { logger.warning("can't find name tag for " + username); return; } nameTag.setNameTag(eventType, username, usernameAlias); } public static void setOtherNameTags(EventType eventType, String username, String usernameAlias) { String[] keys = nameTagMap.keySet().toArray(new String[0]); for (int i = 0; i < keys.length; i++) { if (keys[i].equals(username)) { continue; } NameTagNode nameTag = nameTagMap.get(keys[i]); logger.fine("set other name tags: " + eventType + ", username: " + username + ", usernameAlias: " + usernameAlias); nameTag.setNameTag(eventType, username, usernameAlias); } } public void setNameTag(EventType eventType, String username, String alias) { setNameTag(eventType, username, alias, foregroundColor, currentFont); } public synchronized void setNameTag(EventType eventType, String username, String alias, Color foregroundColor, Font font) { logger.fine("set name tag: " + eventType + ", username: " + username + ", alias: " + alias + ", color: " + foregroundColor + ", font: " + font); switch (eventType) { case HIDE: labelHidden = true; removeLabel(); return; case SMALL_FONT: labelHidden = false; removeLabel(); setHeight(SMALL_SIZE); break; case REGULAR_FONT: labelHidden = false; removeLabel(); setHeight(REGULAR_SIZE); break; case LARGE_FONT: labelHidden = false; removeLabel(); setHeight(LARGE_SIZE); break; case ENTERED_CONE_OF_SILENCE: inConeOfSilence = true; setForegroundColor(CONE_OF_SILENCE_COLOR); break; case EXITED_CONE_OF_SILENCE: inConeOfSilence = false; setForegroundColor(NOT_SPEAKING_COLOR); break; case STARTED_SPEAKING: isSpeaking = true; setForegroundColor(SPEAKING_COLOR); break; case STOPPED_SPEAKING: isSpeaking = false; setForegroundColor(NOT_SPEAKING_COLOR); break; case MUTE: isMuted = true; setForegroundColor(NOT_SPEAKING_COLOR); removeLabel(); break; case UNMUTE: isMuted = false; setForegroundColor(NOT_SPEAKING_COLOR); break; case CHANGE_NAME: removeLabel(); usernameAlias = alias; break; default: logger.warning("unhandled name tag event type: " + eventType); break; } - if ((usernameAlias != null) && !username.equals(usernameAlias)) { + if ((alias != null) && !alias.equals(username)) { // displaying an alias setFont(ALIAS_NAME_FONT); + usernameAlias = alias; updateLabel(getDisplayName(usernameAlias, isSpeaking, isMuted)); } else { // displaying user name setFont(REAL_NAME_FONT); updateLabel(getDisplayName(name, isSpeaking, isMuted)); } if (foregroundColor != null) { setForegroundColor(foregroundColor); } } private void removeLabel() { if (label != null) { detachChild(label); label = null; } } private void updateLabel(final String displayName) { if (labelHidden) { return; } ClientContextJME.getSceneWorker().addWorker(new WorkCommit() { public void commit() { if (visible) { if (label == null) { label = new TextLabel2D(displayName, foregroundColor, backgroundColor, currentHeight, true, currentFont); label.setLocalTranslation(0, heightAbove, 0); Matrix3f rot = new Matrix3f(); rot.fromAngleAxis((float) Math.PI, new Vector3f(0f, 1f, 0f)); label.setLocalRotation(rot); attachChild(label); } else { label.setText(displayName, foregroundColor, backgroundColor); } ClientContextJME.getWorldManager().addToUpdateList(NameTagNode.this); } } }); } }
false
true
public synchronized void setNameTag(EventType eventType, String username, String alias, Color foregroundColor, Font font) { logger.fine("set name tag: " + eventType + ", username: " + username + ", alias: " + alias + ", color: " + foregroundColor + ", font: " + font); switch (eventType) { case HIDE: labelHidden = true; removeLabel(); return; case SMALL_FONT: labelHidden = false; removeLabel(); setHeight(SMALL_SIZE); break; case REGULAR_FONT: labelHidden = false; removeLabel(); setHeight(REGULAR_SIZE); break; case LARGE_FONT: labelHidden = false; removeLabel(); setHeight(LARGE_SIZE); break; case ENTERED_CONE_OF_SILENCE: inConeOfSilence = true; setForegroundColor(CONE_OF_SILENCE_COLOR); break; case EXITED_CONE_OF_SILENCE: inConeOfSilence = false; setForegroundColor(NOT_SPEAKING_COLOR); break; case STARTED_SPEAKING: isSpeaking = true; setForegroundColor(SPEAKING_COLOR); break; case STOPPED_SPEAKING: isSpeaking = false; setForegroundColor(NOT_SPEAKING_COLOR); break; case MUTE: isMuted = true; setForegroundColor(NOT_SPEAKING_COLOR); removeLabel(); break; case UNMUTE: isMuted = false; setForegroundColor(NOT_SPEAKING_COLOR); break; case CHANGE_NAME: removeLabel(); usernameAlias = alias; break; default: logger.warning("unhandled name tag event type: " + eventType); break; } if ((usernameAlias != null) && !username.equals(usernameAlias)) { // displaying an alias setFont(ALIAS_NAME_FONT); updateLabel(getDisplayName(usernameAlias, isSpeaking, isMuted)); } else { // displaying user name setFont(REAL_NAME_FONT); updateLabel(getDisplayName(name, isSpeaking, isMuted)); } if (foregroundColor != null) { setForegroundColor(foregroundColor); } }
public synchronized void setNameTag(EventType eventType, String username, String alias, Color foregroundColor, Font font) { logger.fine("set name tag: " + eventType + ", username: " + username + ", alias: " + alias + ", color: " + foregroundColor + ", font: " + font); switch (eventType) { case HIDE: labelHidden = true; removeLabel(); return; case SMALL_FONT: labelHidden = false; removeLabel(); setHeight(SMALL_SIZE); break; case REGULAR_FONT: labelHidden = false; removeLabel(); setHeight(REGULAR_SIZE); break; case LARGE_FONT: labelHidden = false; removeLabel(); setHeight(LARGE_SIZE); break; case ENTERED_CONE_OF_SILENCE: inConeOfSilence = true; setForegroundColor(CONE_OF_SILENCE_COLOR); break; case EXITED_CONE_OF_SILENCE: inConeOfSilence = false; setForegroundColor(NOT_SPEAKING_COLOR); break; case STARTED_SPEAKING: isSpeaking = true; setForegroundColor(SPEAKING_COLOR); break; case STOPPED_SPEAKING: isSpeaking = false; setForegroundColor(NOT_SPEAKING_COLOR); break; case MUTE: isMuted = true; setForegroundColor(NOT_SPEAKING_COLOR); removeLabel(); break; case UNMUTE: isMuted = false; setForegroundColor(NOT_SPEAKING_COLOR); break; case CHANGE_NAME: removeLabel(); usernameAlias = alias; break; default: logger.warning("unhandled name tag event type: " + eventType); break; } if ((alias != null) && !alias.equals(username)) { // displaying an alias setFont(ALIAS_NAME_FONT); usernameAlias = alias; updateLabel(getDisplayName(usernameAlias, isSpeaking, isMuted)); } else { // displaying user name setFont(REAL_NAME_FONT); updateLabel(getDisplayName(name, isSpeaking, isMuted)); } if (foregroundColor != null) { setForegroundColor(foregroundColor); } }
diff --git a/TPE3/src/hopfield/AsynchronichHopfieldNet.java b/TPE3/src/hopfield/AsynchronichHopfieldNet.java index 5edc01d..4792e75 100644 --- a/TPE3/src/hopfield/AsynchronichHopfieldNet.java +++ b/TPE3/src/hopfield/AsynchronichHopfieldNet.java @@ -1,36 +1,36 @@ package hopfield; import java.util.Arrays; public class AsynchronichHopfieldNet extends HopfieldNet { public AsynchronichHopfieldNet(int N) { super(N); } @Override public int[] iterateUntilConvergence() { int[] prevStates = states.clone(); do { int index = (int) (Math.random() * getNumNeurons()); int state = states[index]; float h = 0; for (int i = 0; i < getNumNeurons(); i++) { h += weights[index][i] * states[i]; } states[index] = sgn(h, state); - } while(Arrays.equals(prevStates, states)); + } while (!Arrays.equals(prevStates, states)); return prevStates; } private int sgn(float h, int prevState) { if (h == 0) { return prevState; } if (h > 0) { return STATE_POSITIVE; } return STATE_NEGATIVE; } }
true
true
public int[] iterateUntilConvergence() { int[] prevStates = states.clone(); do { int index = (int) (Math.random() * getNumNeurons()); int state = states[index]; float h = 0; for (int i = 0; i < getNumNeurons(); i++) { h += weights[index][i] * states[i]; } states[index] = sgn(h, state); } while(Arrays.equals(prevStates, states)); return prevStates; }
public int[] iterateUntilConvergence() { int[] prevStates = states.clone(); do { int index = (int) (Math.random() * getNumNeurons()); int state = states[index]; float h = 0; for (int i = 0; i < getNumNeurons(); i++) { h += weights[index][i] * states[i]; } states[index] = sgn(h, state); } while (!Arrays.equals(prevStates, states)); return prevStates; }
diff --git a/src/main/java/de/codeinfection/quickwango/AntiGuest/Prevention.java b/src/main/java/de/codeinfection/quickwango/AntiGuest/Prevention.java index 235e8b7..4a03e98 100644 --- a/src/main/java/de/codeinfection/quickwango/AntiGuest/Prevention.java +++ b/src/main/java/de/codeinfection/quickwango/AntiGuest/Prevention.java @@ -1,169 +1,169 @@ package de.codeinfection.quickwango.AntiGuest; import java.util.HashMap; import org.bukkit.ChatColor; import org.bukkit.Server; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.Cancellable; import org.bukkit.event.Listener; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; import org.bukkit.plugin.Plugin; /** * * @author CodeInfection */ public abstract class Prevention implements Listener { private final String name; private final Permission permission; private String message; private int messageDelay; private final Plugin plugin; private boolean enabled; private final HashMap<Player, Long> throttleTimestamps; public Prevention(final String name, final Plugin plugin) { this(name, "antiguest.preventions." + name, plugin); } public Prevention(final String name, final String permission, final Plugin plugin) { this.name = name; this.permission = new Permission(permission, PermissionDefault.OP); this.throttleTimestamps = new HashMap<Player, Long>(0); this.message = null; this.messageDelay = 0; this.plugin = plugin; this.enabled = false; } public ConfigurationSection getDefaultConfig() { ConfigurationSection defaultConfig = new MemoryConfiguration(); defaultConfig.set("enable", false); defaultConfig.set("message", "&4You are not allowed to do this."); return defaultConfig; } public void initialize(final Server server, final ConfigurationSection config) { this.messageDelay = config.getInt("messageDelay") * 1000; this.message = config.getString("message"); if (this.message != null) { if (this.message.length() == 0) { this.message = null; } else { - this.message = this.message.replaceAll("&([a-fk0-9])", ChatColor.COLOR_CHAR + "$1"); + this.message = this.message.replaceAll("(?i)&([a-fk0-9])", ChatColor.COLOR_CHAR + "$1"); } } } public void disable() { this.throttleTimestamps.clear(); } public final boolean isEnabled() { return this.enabled; } public final void setEnabled(boolean enable) { this.enabled = enable; } public String getName() { return this.name; } public Permission getPermission() { return this.permission; } public String getMessage() { return this.message; } public Plugin getPlugin() { return this.plugin; } public int getMessageDelay() { return this.messageDelay; } public boolean can(final Player player) { AntiGuest.debug("Checking permission: " + this.permission.getName()); return player.hasPermission(this.permission); } public void sendMessage(final Player player) { if (this.message != null) { player.sendMessage(this.message); } } public void sendThrottledMessage(final Player player) { this.sendThrottledMessage(player, this.messageDelay); } public void sendThrottledMessage(final Player player, final int delay) { Long last = this.throttleTimestamps.get(player); last = (last == null ? 0 : last); final long current = System.currentTimeMillis(); if (last + delay < current) { this.sendMessage(player); this.throttleTimestamps.put(player, current); } } @Override public String toString() { return this.name; } public void prevent(final Cancellable event, final Player player) { if (!this.can(player)) { event.setCancelled(true); this.sendMessage(player); } } public void preventThrottled(final Cancellable event, final Player player) { if (!this.can(player)) { event.setCancelled(true); this.sendThrottledMessage(player); } } }
true
true
public void initialize(final Server server, final ConfigurationSection config) { this.messageDelay = config.getInt("messageDelay") * 1000; this.message = config.getString("message"); if (this.message != null) { if (this.message.length() == 0) { this.message = null; } else { this.message = this.message.replaceAll("&([a-fk0-9])", ChatColor.COLOR_CHAR + "$1"); } } }
public void initialize(final Server server, final ConfigurationSection config) { this.messageDelay = config.getInt("messageDelay") * 1000; this.message = config.getString("message"); if (this.message != null) { if (this.message.length() == 0) { this.message = null; } else { this.message = this.message.replaceAll("(?i)&([a-fk0-9])", ChatColor.COLOR_CHAR + "$1"); } } }