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/me/neatmonster/spacertk/PingListener.java b/src/me/neatmonster/spacertk/PingListener.java
index c447e84..860957b 100644
--- a/src/me/neatmonster/spacertk/PingListener.java
+++ b/src/me/neatmonster/spacertk/PingListener.java
@@ -1,130 +1,131 @@
/*
* This file is part of SpaceRTK (http://spacebukkit.xereo.net/).
*
* SpaceRTK is free software: you can redistribute it and/or modify it under the terms of the
* Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license as published by the Creative Common organization,
* either version 3.0 of the license, or (at your option) any later version.
*
* SpaceRTK 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 Attribution-NonCommercial-ShareAlike
* Unported (CC BY-NC-SA) license for more details.
*
* You should have received a copy of the Attribution-NonCommercial-ShareAlike Unported (CC BY-NC-SA) license along with
* this program. If not, see <http://creativecommons.org/licenses/by-nc-sa/3.0/>.
*/
package me.neatmonster.spacertk;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Pings the Module to ensure it is functioning correctly
*/
public class PingListener extends Thread {
public static final int REQUEST_THRESHOLD = 60000; // Sixty seconds
public static final int SLEEP_TIME = 30000; // Thirty seconds
private boolean lostModule;
private DatagramSocket socket;
private AtomicBoolean running = new AtomicBoolean(false);
private InetAddress localHost;
/**
* Creates a new PingListener
*/
public PingListener() {
super("Ping Listener Main Thread");
try {
this.localHost = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
handleException(e, "Unable to get the Local Host!");
}
this.lostModule = false;
try {
this.socket = new DatagramSocket();
} catch (IOException e) {
handleException(e, "Unable to start the PingListener!");
}
}
/**
* Starts the Ping Listener
*/
public void startup() {
this.running.set(true);
this.start();
}
@Override
public void run() {
try {
socket.setSoTimeout(REQUEST_THRESHOLD);
} catch (SocketException e) {
handleException(e, "Error setting the So Timeout!");
}
while (running.get()) {
byte[] buffer = new byte[512];
+ buffer[0] = 1;
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localHost, SpaceRTK.getInstance().rPingPort);
socket.send(packet);
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
handleException(e, "Error sleeping in the run() loop!");
}
socket.receive(packet);
} catch (SocketTimeoutException e) {
onModuleNotFound();
} catch (IOException e) {
handleException(e, "Error sending and receiving the RTK packet!");
}
}
}
/**
* Shuts down the Ping Listener
*/
public void shutdown() {
this.running.set(false);
}
/**
* Called when an exception is thrown
*
* @param e
* Exception thrown
*/
public void handleException(Exception e, String reason) {
shutdown();
System.err.println("[SpaceBukkit] Ping Listener Error!");
System.err.println(reason);
System.err.println("Error message:");
e.printStackTrace();
}
/**
* Called when the Module can't be found
*/
public void onModuleNotFound() {
if (lostModule) {
return;
}
shutdown();
System.err.println("[SpaceBukkit] Unable to ping the Module!");
System.err
.println("[SpaceBukkit] Please insure the correct ports are open");
System.err
.println("[SpaceBukkit] Please contact the forums (http://forums.xereo.net/) or IRC (#SpaceBukkit on irc.esper.net)");
lostModule = true;
}
}
| true | true | public void run() {
try {
socket.setSoTimeout(REQUEST_THRESHOLD);
} catch (SocketException e) {
handleException(e, "Error setting the So Timeout!");
}
while (running.get()) {
byte[] buffer = new byte[512];
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localHost, SpaceRTK.getInstance().rPingPort);
socket.send(packet);
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
handleException(e, "Error sleeping in the run() loop!");
}
socket.receive(packet);
} catch (SocketTimeoutException e) {
onModuleNotFound();
} catch (IOException e) {
handleException(e, "Error sending and receiving the RTK packet!");
}
}
}
| public void run() {
try {
socket.setSoTimeout(REQUEST_THRESHOLD);
} catch (SocketException e) {
handleException(e, "Error setting the So Timeout!");
}
while (running.get()) {
byte[] buffer = new byte[512];
buffer[0] = 1;
try {
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localHost, SpaceRTK.getInstance().rPingPort);
socket.send(packet);
try {
Thread.sleep(SLEEP_TIME);
} catch (InterruptedException e) {
handleException(e, "Error sleeping in the run() loop!");
}
socket.receive(packet);
} catch (SocketTimeoutException e) {
onModuleNotFound();
} catch (IOException e) {
handleException(e, "Error sending and receiving the RTK packet!");
}
}
}
|
diff --git a/src/main/java/org/exolab/castor/xml/UnmarshalHandler.java b/src/main/java/org/exolab/castor/xml/UnmarshalHandler.java
index 6ccc9f3f..3c8dcffc 100644
--- a/src/main/java/org/exolab/castor/xml/UnmarshalHandler.java
+++ b/src/main/java/org/exolab/castor/xml/UnmarshalHandler.java
@@ -1,3846 +1,3857 @@
/**
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "Exolab" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of Intalio, Inc. For written permission,
* please contact [email protected].
*
* 4. Products derived from this Software may not be called "Exolab"
* nor may "Exolab" appear in their names without prior written
* permission of Intalio, Inc. Exolab is a registered
* trademark of Intalio, Inc.
*
* 5. Due credit should be given to the Exolab Project
* (http://www.exolab.org/).
*
* THIS SOFTWARE IS PROVIDED BY INTALIO, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* INTALIO, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 1999-2004 (C) Intalio, Inc. All Rights Reserved.
*
* Portions of this file developed by Keith Visco after Jan 19 2005 are
* Copyright (C) Keith Visco. All Rights Reserverd.
*
* $Id$
*/
package org.exolab.castor.xml;
//-- Castor imports
import org.castor.util.Base64Decoder;
import org.exolab.castor.util.Configuration;
import org.exolab.castor.util.ObjectFactory;
import org.exolab.castor.util.DefaultObjectFactory;
import org.exolab.castor.xml.descriptors.PrimitivesClassDescriptor;
import org.exolab.castor.xml.descriptors.StringClassDescriptor;
import org.exolab.castor.xml.util.*;
import org.exolab.castor.mapping.ClassDescriptor;
import org.exolab.castor.mapping.ExtendedFieldHandler;
import org.exolab.castor.mapping.FieldHandler;
import org.exolab.castor.mapping.MapItem;
import org.exolab.castor.mapping.loader.FieldHandlerImpl;
//-- xml related imports
import org.xml.sax.*;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Stack;
import java.util.Enumeration;
import java.util.StringTokenizer;
/**
* An unmarshaller to allowing unmarshalling of XML documents to
* Java Objects. The Class must specify
* the proper access methods (setters/getters) in order for instances
* of the Class to be properly unmarshalled.
*
* @author <a href="mailto:keith AT kvisco DOT com">Keith Visco</a>
* @version $Revision$ $Date$
*/
public final class UnmarshalHandler extends MarshalFramework
implements ContentHandler, DocumentHandler, ErrorHandler {
//---------------------------/
//- Private Class Variables -/
//---------------------------/
/**
* The error message when no class descriptor has been found
* TODO: move to resource bundle
*/
private static final String ERROR_DID_NOT_FIND_CLASSDESCRIPTOR =
"unable to find or create a ClassDescriptor for class: ";
/**
* The built-in XML prefix used for xml:space, xml:lang
* and, as the XML 1.0 Namespaces document specifies, are
* reserved for use by XML and XML related specs.
**/
private static final String XML_PREFIX = "xml";
/**
* Attribute name for default namespace declaration
**/
private static final String XMLNS = "xmlns";
/**
* Attribute prefix for prefixed namespace declaration
**/
private final static String XMLNS_PREFIX = "xmlns:";
private final static int XMLNS_PREFIX_LENGTH = XMLNS_PREFIX.length();
/**
* The type attribute (xsi:type) used to denote the
* XML Schema type of the parent element
**/
private static final String XSI_TYPE = "type";
private static final String XML_SPACE = "space";
private static final String XML_SPACE_WITH_PREFIX = "xml:space";
private static final String PRESERVE = "preserve";
//----------------------------/
//- Private Member Variables -/
//----------------------------/
private Stack _stateInfo = null;
private UnmarshalState _topState = null;
private Class _topClass = null;
/**
* The top-level instance object, this may be set by the user
* by calling #setRootObject();
**/
private Object _topObject = null;
/**
* A StringBuffer used to created Debug/Log messages
**/
//private StringBuffer buf = null;
/**
* Indicates whether or not collections should be cleared
* upon first use (to remove default values, or old values).
* False by default for backward compatibility.
*/
private boolean _clearCollections = false;
/**
* The Castor configuration
*/
private Configuration _config = null;
/**
* A flag to indicate whether or not to generate debug information
**/
private boolean debug = false;
/**
* A flag to indicate we need to kill the _logWriter when
* debug mode is false
**/
private boolean killWriter = false;
/**
* The SAX Document Locator
**/
private Locator _locator = null;
/**
* The PrintWriter to print log information to
**/
private PrintWriter _logWriter = null;
/**
* The ClassDescriptorResolver which is used to "resolve"
* or find ClassDescriptors
**/
private ClassDescriptorResolver _cdResolver = null;
/**
* The IDResolver for resolving IDReferences
**/
private IDResolverImpl _idResolver = null;
/**
* The unmarshaller listener
*/
private UnmarshalListener _unmarshalListener = null;
/*
*
* A flag indicating whether or not to perform validation
**/
private boolean _validate = true;
private Hashtable _resolveTable = null;
private HashMap _javaPackages = null;
private ClassLoader _loader = null;
private static final StringClassDescriptor _stringDescriptor
= new StringClassDescriptor();
/**
* A SAX2ANY unmarshaller in case we are dealing with <any>
*/
private SAX2ANY _anyUnmarshaller = null;
/**
* The any branch depth
*/
private int _depth = 0;
/**
* The AnyNode to add (if any)
*/
private org.exolab.castor.types.AnyNode _node = null;
/**
* The namespace stack
*/
private Namespaces _namespaces = null;
/**
* A map of namespace URIs to Package Names
*/
private HashMap _namespaceToPackage = null;
/**
* A reference to the ObjectFactory used to create instances
* of the classes if the FieldHandler is not used.
*/
private ObjectFactory _objectFactory = new DefaultObjectFactory();
/**
* A boolean to indicate that objects should
* be re-used where appropriate
**/
private boolean _reuseObjects = false;
/**
* A boolean that indicates attribute processing should
* be strict and an error should be flagged if any
* extra attributes exist.
**/
private boolean _strictAttributes = false;
/**
* A boolean that indicates element processing should
* be strict and an error should be flagged if any
* extra elements exist
**/
private boolean _strictElements = true;
/**
* A depth counter that increases as we skip elements ( in startElement )
* and decreases as we process and endElement. Only active if _strictElemnts
*/
private int _ignoreElementDepth = 0;
/**
* A flag to keep track of when a new namespace scope is needed
*/
private boolean _createNamespaceScope = true;
/**
* Keeps track of the current element information
* as passed by the parser
*/
private ElementInfo _elemInfo = null;
/**
* A "reusable" AttributeSet, for use when handling
* SAX 2 ContentHandler
*/
private AttributeSetImpl _reusableAtts = null;
private ArrayList _statePool = null;
/**
* The top-level xml:space value
*/
private boolean _wsPreserve = false;
//----------------/
//- Constructors -/
//----------------/
/**
* Creates a new UnmarshalHandler
* The "root" class will be obtained by looking into the mapping
* for a descriptor that matches the root element.
**/
protected UnmarshalHandler() {
this(null);
} //-- UnmarshalHandler
/**
* Creates a new UnmarshalHandler
*
* @param _class the Class to create the UnmarshalHandler for
*/
protected UnmarshalHandler(Class _class) {
super();
_stateInfo = new Stack();
_idResolver = new IDResolverImpl();
_javaPackages = new HashMap();
_topClass = _class;
_namespaces = new Namespaces();
_statePool = new ArrayList();
_namespaceToPackage = new HashMap();
} //-- UnmarshalHandler(Class)
/**
* Adds a mapping from the given namespace URI to the given
* package name
*
* @param nsURI the namespace URI to map from
* @param packageName the package name to map to
*/
public void addNamespaceToPackageMapping(String nsURI, String packageName)
{
if (nsURI == null) nsURI = "";
if (packageName == null) packageName = "";
_namespaceToPackage.put(nsURI, packageName);
} //-- addNamespaceToPackageMapping
/**
* Returns the Object that the UnmarshalHandler is currently
* handling (within the object model), or null if the current
* element is a simpleType.
*
* @return the Object currently being unmarshalled, or null if the
* current element is a simpleType.
*/
public Object getCurrentObject() {
if (!_stateInfo.isEmpty()) {
UnmarshalState state = (UnmarshalState)_stateInfo.peek();
if (state != null) {
return state.object;
}
}
return null;
} //-- getCurrentObject
/**
* Returns the "root" Object (ie. the entire object model)
* being unmarshalled.
*
* @return the root Object being unmarshalled.
**/
public Object getObject() {
if (_topState != null) return _topState.object;
return null;
} //-- getObject
/**
* Sets the ClassLoader to use when loading classes
*
* @param loader the ClassLoader to use
**/
public void setClassLoader(ClassLoader loader) {
_loader = loader;
} //-- setClassLoader
/**
* Sets whether or not to clear collections (including arrays)
* upon first use to remove default values. By default, and
* for backward compatibility with previous versions of Castor
* this value is false, indicating that collections are not
* cleared before initial use by Castor.
*
* @param clear the boolean value that when true indicates
* collections should be cleared upon first use.
*/
public void setClearCollections(boolean clear) {
_clearCollections = clear;
} //-- setClearCollections
/**
* Turns debuging on or off. If no Log Writer has been set, then
* System.out will be used to display debug information
* @param debug the flag indicating whether to generate debug information.
* A value of true, will turn debuggin on.
* @see #setLogWriter
**/
public void setDebug(boolean debug) {
this.debug = debug;
if (this.debug && (_logWriter == null)) {
_logWriter = new PrintWriter(System.out, true);
killWriter = true;
}
if ((!this.debug) && killWriter) {
_logWriter = null;
killWriter = false;
}
} //-- setDebug
/**
* Sets the IDResolver to use when resolving IDREFs for
* which no associated element may exist in XML document.
*
* @param idResolver the IDResolver to use when resolving
* IDREFs for which no associated element may exist in the
* XML document.
**/
public void setIDResolver(IDResolver idResolver) {
_idResolver.setResolver(idResolver);
} //-- setIdResolver
/**
* Sets whether or not attributes that do not match
* a specific field should simply be ignored or
* reported as an error. By default, extra attributes
* are ignored.
*
* @param ignoreExtraAtts a boolean that when true will
* allow non-matched attributes to simply be ignored.
**/
public void setIgnoreExtraAttributes(boolean ignoreExtraAtts) {
_strictAttributes = (!ignoreExtraAtts);
} //-- setIgnoreExtraAttributes
/**
* Sets whether or not elements that do not match
* a specific field should simply be ignored or
* reported as an error. By default, extra attributes
* are ignored.
*
* @param ignoreExtraElems a boolean that when true will
* allow non-matched attributes to simply be ignored.
**/
public void setIgnoreExtraElements(boolean ignoreExtraElems) {
_strictElements = (!ignoreExtraElems);
} //-- setIgnoreExtraElements
/**
* Sets the PrintWriter used for printing log messages
* @param printWriter the PrintWriter to use when printing
* log messages
**/
public void setLogWriter(PrintWriter printWriter) {
this._logWriter = printWriter;
killWriter = false;
} //-- setLogWriter
/**
* Sets a boolean that when true indicates that objects
* contained within the object model should be re-used
* where appropriate. This is only valid when unmarshalling
* to an existing object.
*
* @param reuse the boolean indicating whether or not
* to re-use existing objects in the object model.
**/
public void setReuseObjects(boolean reuse) {
_reuseObjects = reuse;
} //-- setReuseObjects
/**
* Sets the ClassDescriptorResolver to use for loading and
* resolving ClassDescriptors
*
* @param cdResolver the ClassDescriptorResolver to use
**/
public void setResolver(ClassDescriptorResolver cdResolver) {
this._cdResolver = cdResolver;
} //-- setResolver
/**
* Sets the root (top-level) object to use for unmarshalling into.
*
* @param root the instance to unmarshal into.
**/
public void setRootObject(Object root) {
_topObject = root;
} //-- setRootObject
/**
* Sets an {@link UnmarshalListener}.
*
* @param listener the UnmarshalListener to use with this instance
* of the UnmarshalHandler.
**/
public void setUnmarshalListener (UnmarshalListener listener) {
_unmarshalListener = listener;
}
/**
* Sets the flag for validation
* @param validate, a boolean to indicate whether or not
* validation should be done during umarshalling. <br />
* By default, validation will be performed.
**/
public void setValidation(boolean validate) {
this._validate = validate;
} //-- setValidation
/**
* Sets the top-level whitespace (xml:space) to either
* preserving or non preserving. The XML document
* can override this value using xml:space on specific
* elements. This sets the "default" behavior
* when xml:space="default".
*
* @param preserve a boolean that when true enables
* whitespace preserving by default.
*/
public void setWhitespacePreserve(boolean preserve) {
_wsPreserve = preserve;
} //-- setWhitespacePreserve
//-----------------------------------/
//- SAX Methods for DocumentHandler -/
//-----------------------------------/
public void characters(char[] ch, int start, int length)
throws SAXException
{
if (debug) {
StringBuffer sb = new StringBuffer(21 + length);
sb.append("#characters: ");
sb.append(ch, start, length);
message(sb.toString());
}
//-- If we are skipping elements that have appeared in the XML but for
//-- which we have no mapping, skip the text and return
if ( _ignoreElementDepth > 0) {
return;
}
if (_stateInfo.empty()) {
return;
}
if (_anyUnmarshaller != null)
_anyUnmarshaller.characters(ch, start, length);
else {
UnmarshalState state = (UnmarshalState)_stateInfo.peek();
//-- handle whitespace
boolean removedTrailingWhitespace = false;
boolean removedLeadingWhitespace = false;
if (!state.wsPreserve) {
//-- trim leading whitespace characters
while (length > 0) {
boolean whitespace = false;
switch(ch[start]) {
case ' ':
case '\r':
case '\n':
case '\t':
whitespace = true;
break;
default:
break;
}
if (!whitespace) break;
removedLeadingWhitespace = true;
++start;
--length;
}
if (length == 0) {
//-- we also need to mark trailing whitespace removed
//-- when we received only whitespace characters
removedTrailingWhitespace = removedLeadingWhitespace;
}
else {
//-- trim trailing whitespace characters
while (length > 0) {
boolean whitespace = false;
switch(ch[start+length-1]) {
case ' ':
case '\r':
case '\n':
case '\t':
whitespace = true;
break;
default:
break;
}
if (!whitespace) break;
removedTrailingWhitespace = true;
--length;
}
}
}
if (state.buffer == null) state.buffer = new StringBuffer();
else {
//-- non-whitespace content exists, add a space
if ((!state.wsPreserve) && (length > 0)) {
if (state.trailingWhitespaceRemoved || removedLeadingWhitespace)
{
state.buffer.append(' ');
}
}
}
state.trailingWhitespaceRemoved = removedTrailingWhitespace;
state.buffer.append(ch, start, length);
}
} //-- characters
public void endDocument()
throws org.xml.sax.SAXException
{
//-- I've found many application don't always call
//-- #endDocument, so I usually never put any
//-- important logic here
} //-- endDocument
public void endElement(String name)
throws org.xml.sax.SAXException
{
if (debug) {
message("#endElement: " + name);
}
//-- If we are skipping elements that have appeared in the XML but for
//-- which we have no mapping, decrease the ignore depth counter and return
if ( _ignoreElementDepth > 0) {
--_ignoreElementDepth;
return;
}
//-- Do delagation if necessary
if (_anyUnmarshaller != null) {
_anyUnmarshaller.endElement(name);
--_depth;
//we are back to the starting node
if (_depth == 0) {
_node = _anyUnmarshaller.getStartingNode();
_anyUnmarshaller = null;
}
else return;
}
if (_stateInfo.empty()) {
throw new SAXException("missing start element: " + name);
}
//-- * Begin Namespace Handling
//-- XXX Note: This code will change when we update the XML event API
int idx = name.indexOf(':');
if (idx >= 0) {
name = name.substring(idx+1);
}
//-- * End Namespace Handling
UnmarshalState state = (UnmarshalState) _stateInfo.pop();
//-- make sure we have the correct closing tag
XMLFieldDescriptor descriptor = state.fieldDesc;
if (!state.elementName.equals(name)) {
//maybe there is still a container to end
if (descriptor.isContainer()) {
_stateInfo.push(state);
//-- check for possible characters added to
//-- the container's state that should
//-- really belong to the parent state
StringBuffer tmpBuffer = null;
if (state.buffer != null) {
if (!isWhitespace(state.buffer)) {
if (state.classDesc.getContentDescriptor() == null) {
tmpBuffer = state.buffer;
state.buffer = null;
}
}
}
//-- end container
endElement(state.elementName);
if (tmpBuffer != null) {
state = (UnmarshalState) _stateInfo.peek();
if (state.buffer == null)
state.buffer = tmpBuffer;
else
state.buffer.append(tmpBuffer.toString());
}
endElement(name);
return;
}
String err = "error in xml, expecting </" + state.elementName;
err += ">, but received </" + name + "> instead.";
throw new SAXException(err);
}
//-- clean up current Object
Class type = state.type;
if ( type == null ) {
if (!state.wrapper) {
//-- this message will only show up if debug
//-- is turned on...how should we handle this case?
//-- should it be a fatal error?
message("Ignoring " + state.elementName + " no descriptor was found");
}
//-- handle possible location text content
//-- TODO: cleanup location path support.
//-- the following code needs to be improved as
//-- for searching descriptors in this manner can
//-- be slow
StringBuffer tmpBuffer = null;
if (state.buffer != null) {
if (!isWhitespace(state.buffer)) {
tmpBuffer = state.buffer;
state.buffer = null;
}
}
if (tmpBuffer != null) {
UnmarshalState targetState = state;
String locPath = targetState.elementName;
while ((targetState = targetState.parent) != null) {
if ((targetState.wrapper) ||
(targetState.classDesc == null))
{
locPath = targetState.elementName + "/" + locPath;
continue;
}
XMLFieldDescriptor tmpDesc = targetState.classDesc.getContentDescriptor();
if (tmpDesc != null && locPath.equals(tmpDesc.getLocationPath())) {
if (targetState.buffer == null)
targetState.buffer = tmpBuffer;
else
targetState.buffer.append(tmpBuffer.toString());
}
}
}
//-- remove current namespace scoping
_namespaces = _namespaces.getParent();
freeState(state);
return;
}
//-- check for special cases
boolean byteArray = false;
if (type.isArray())
byteArray = (type.getComponentType() == Byte.TYPE);
//-- If we don't have an instance object and the Class type
//-- is not a primitive or a byte[] we must simply return
if ((state.object == null) && (!state.primitiveOrImmutable)) {
//-- remove current namespace scoping
_namespaces = _namespaces.getParent();
freeState(state);
return;
}
/// DEBUG System.out.println("end: " + name);
if (state.primitiveOrImmutable) {
String str = null;
if (state.buffer != null) {
str = state.buffer.toString();
state.buffer.setLength(0);
}
if (type == String.class) {
if (str != null)
state.object = str;
else if (state.nil) {
state.object = null;
}
else {
state.object = "";
}
}
//-- special handling for byte[]
else if (byteArray) {
if (str == null)
state.object = new byte[0];
else {
//-- Base64 decoding
state.object = Base64Decoder.decode(str);
}
}
else if (state.args != null) {
state.object = createInstance(state.type, state.args);
}
else state.object = toPrimitiveObject(type,str,state.fieldDesc);
}
else if (ArrayHandler.class.isAssignableFrom(state.type)) {
state.object = ((ArrayHandler)state.object).getObject();
state.type = state.object.getClass();
}
//-- check for character content
if ((state.buffer != null) &&
(state.buffer.length() > 0) &&
(state.classDesc != null)) {
XMLFieldDescriptor cdesc = state.classDesc.getContentDescriptor();
if (cdesc != null) {
Object value = state.buffer.toString();
if (isPrimitive(cdesc.getFieldType()))
value = toPrimitiveObject(cdesc.getFieldType(), (String)value, state.fieldDesc);
else {
Class valueType = cdesc.getFieldType();
//-- handle base64
if (valueType.isArray()
&& (valueType.getComponentType() == Byte.TYPE)) {
value = Base64Decoder.decode((String) value);
}
}
try {
FieldHandler handler = cdesc.getHandler();
boolean addObject = true;
if (_reuseObjects) {
//-- check to see if we need to
//-- add the object or not
Object tmp = handler.getValue(state.object);
if (tmp != null) {
//-- Do not add object if values
//-- are equal
addObject = (!tmp.equals(value));
}
}
if (addObject) handler.setValue(state.object, value);
}
catch(java.lang.IllegalStateException ise) {
String err = "unable to add text content to ";
err += descriptor.getXMLName();
err += " due to the following error: " + ise;
throw new SAXException(err, ise);
}
}
//-- Handle references
else if (descriptor.isReference()) {
UnmarshalState pState = (UnmarshalState)_stateInfo.peek();
processIDREF(state.buffer.toString(), descriptor, pState.object);
_namespaces = _namespaces.getParent();
freeState(state);
return;
}
else {
//-- check for non-whitespace...and report error
if (!isWhitespace(state.buffer)) {
String err = "Illegal Text data found as child of: "
+ name;
err += "\n value: \"" + state.buffer + "\"";
throw new SAXException(err);
}
}
}
//-- We're finished processing the object, so notify the
//-- Listener (if any).
if ( _unmarshalListener != null && state.object != null ) {
_unmarshalListener.unmarshalled(state.object);
}
//-- if we are at root....just validate and we are done
if (_stateInfo.empty()) {
if (_validate) {
ValidationException first = null;
ValidationException last = null;
//-- check unresolved references
if (_resolveTable != null) {
Enumeration enumeration = _resolveTable.keys();
while (enumeration.hasMoreElements()) {
Object ref = enumeration.nextElement();
//if (ref.toString().startsWith(MapItem.class.getName())) continue;
String msg = "unable to resolve reference: " + ref;
if (first == null) {
first = new ValidationException(msg);
last = first;
}
else {
last.setNext(new ValidationException(msg));
last = last.getNext();
}
}
}
try {
Validator validator = new Validator();
ValidationContext context = new ValidationContext();
context.setResolver(_cdResolver);
context.setConfiguration(_config);
validator.validate(state.object, context);
}
catch(ValidationException vEx) {
if (first == null)
first = vEx;
else
last.setNext(vEx);
}
if (first != null) {
throw new SAXException(first);
}
}
return;
}
//-- Add object to parent if necessary
if (descriptor.isIncremental()) {
//-- remove current namespace scoping
_namespaces = _namespaces.getParent();
freeState(state);
return; //-- already added
}
Object val = state.object;
//--special code for AnyNode handling
if (_node != null) {
val = _node;
_node = null;
}
//-- save fieldState
UnmarshalState fieldState = state;
//-- have we seen this object before?
boolean firstOccurance = false;
//-- get target object
state = (UnmarshalState) _stateInfo.peek();
if (state.wrapper) {
state = fieldState.targetState;
}
//-- check to see if we have already read in
//-- an element of this type.
//-- (Q: if we have a container, do we possibly need to
//-- also check the container's multivalued status?)
if ( ! descriptor.isMultivalued() ) {
if (state.isUsed(descriptor)) {
String err = "element \"" + name;
err += "\" occurs more than once. (parent class: " + state.type.getName() + ")";
String location = name;
while (!_stateInfo.isEmpty()) {
UnmarshalState tmpState = (UnmarshalState)_stateInfo.pop();
if (!tmpState.wrapper) {
if (tmpState.fieldDesc.isContainer()) continue;
}
location = state.elementName + "/" + location;
}
err += "\n location: /" + location;
ValidationException vx =
new ValidationException(err);
throw new SAXException(vx);
}
state.markAsUsed(descriptor);
//-- if this is the identity then save id
if (state.classDesc.getIdentity() == descriptor) {
state.key = val;
}
}
else {
//-- check occurance of descriptor
if (!state.isUsed(descriptor)) {
firstOccurance = true;
}
//-- record usage of descriptor
state.markAsUsed(descriptor);
}
try {
FieldHandler handler = descriptor.getHandler();
//check if the value is a QName that needs to
//be resolved (ns:value -> {URI}value)
String valueType = descriptor.getSchemaType();
if ((valueType != null) && (valueType.equals(QNAME_NAME))) {
val = resolveNamespace(val);
}
boolean addObject = true;
if (_reuseObjects && fieldState.primitiveOrImmutable) {
//-- check to see if we need to
//-- add the object or not
Object tmp = handler.getValue(state.object);
if (tmp != null) {
//-- Do not add object if values
//-- are equal
addObject = (!tmp.equals(val));
}
}
//-- special handling for mapped objects
if (descriptor.isMapped()) {
if (!(val instanceof MapItem)) {
MapItem mapItem = new MapItem(fieldState.key, val);
val = mapItem;
}
else {
//-- make sure value exists (could be a reference)
MapItem mapItem = (MapItem)val;
if (mapItem.getValue() == null) {
//-- save for later...
addObject = false;
addReference(mapItem.toString(), state.object, descriptor);
}
}
}
if (addObject) {
//-- clear any collections if necessary
if (firstOccurance && _clearCollections) {
handler.resetValue(state.object);
}
//-- finally set the value!!
handler.setValue(state.object, val);
// If there is a parent for this object, pass along
// a notification that we've finished adding a child
if ( _unmarshalListener != null ) {
_unmarshalListener.fieldAdded(descriptor.getFieldName(), state.object, fieldState.object);
}
}
}
/*
catch(java.lang.reflect.InvocationTargetException itx) {
Throwable toss = itx.getTargetException();
if (toss == null) toss = itx;
String err = "unable to add '" + name + "' to <";
err += state.descriptor.getXMLName();
err += "> due to the following exception: " + toss;
throw new SAXException(err);
}
*/
catch(Exception ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
pw.flush();
String err = "unable to add '" + name + "' to <";
err += state.fieldDesc.getXMLName();
err += "> due to the following exception: \n";
err += ">>>--- Begin Exception ---<<< \n";
err += sw.toString();
err += ">>>---- End Exception ----<<< \n";
throw new SAXException(err);
}
//-- remove current namespace scoping
_namespaces = _namespaces.getParent();
//-- free fieldState
freeState(fieldState);
} //-- endElement
/**
* <p>ContentHandler#endElement</p>
*
* Signals the end of an element
*
* @param name the name of the element
*/
public void endElement(String namespaceURI, String localName, String qName)
throws org.xml.sax.SAXException
{
if ((qName == null) || (qName.length() == 0)) {
if ((localName == null) || (localName.length() == 0)) {
String error = "Missing either 'qName' or 'localName', both cannot be null or emtpy.";
throw new SAXException(error);
}
qName = localName;
if ((namespaceURI != null) && (namespaceURI.length() > 0)) {
//-- rebuild qName, for now
String prefix = _namespaces.getNamespacePrefix(namespaceURI);
if ((prefix != null) && (prefix.length() > 0))
qName = prefix + ":" + localName;
}
}
endElement(qName);
} //-- endElement
/**
* Signals to end the namespace prefix mapping
*
* @param prefix the namespace prefix
*/
public void endPrefixMapping(String prefix)
throws SAXException
{
//-- nothing to do , already taken care of in
//-- endElement except if we are unmarshalling an
//-- AnyNode
if (_anyUnmarshaller != null) {
_anyUnmarshaller.endPrefixMapping(prefix);
}
} //-- endPrefixMapping
public void ignorableWhitespace(char[] ch, int start, int length)
throws org.xml.sax.SAXException
{
//-- If we are skipping elements that have appeared in the XML but for
//-- which we have no mapping, skip the text and return
if ( _ignoreElementDepth > 0) {
return;
}
if (_stateInfo.empty()) {
return;
}
if (_anyUnmarshaller != null)
_anyUnmarshaller.ignorableWhitespace(ch, start, length);
else {
UnmarshalState state = (UnmarshalState)_stateInfo.peek();
if (state.wsPreserve) {
if (state.buffer == null) state.buffer = new StringBuffer();
state.buffer.append(ch, start, length);
}
}
} //-- ignorableWhitespace
public void processingInstruction(String target, String data)
throws org.xml.sax.SAXException
{
//-- do nothing for now
} //-- processingInstruction
public void setDocumentLocator(Locator locator) {
this._locator = locator;
} //-- setDocumentLocator
public Locator getDocumentLocator() {
return _locator;
} //-- getDocumentLocator
/**
* Signals that an entity was skipped by the parser
*
* @param name the skipped entity's name
*/
public void skippedEntity(String name)
throws SAXException
{
//-- do nothing
} //-- skippedEntity
/**
* Signals the start of a new document
*/
public void startDocument()
throws org.xml.sax.SAXException
{
//-- I've found many application don't always call
//-- #startDocument, so I usually never put any
//-- important logic here
} //-- startDocument
/**
* <p>ContentHandler#startElement</p>
*
* Signals the start of element
*
* @param name the name of the element
* @param atts the AttributeList containing the associated
* attributes for the element
*/
public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
throws org.xml.sax.SAXException
{
if (debug) {
if ((qName != null) && (qName.length() > 0))
message("#startElement: " + qName);
else
message("#startElement: " + localName);
}
//-- If we are skipping elements that have appeared in the XML but for
//-- which we have no mapping, increase the ignore depth counter and return
if ((!_strictElements) && (_ignoreElementDepth > 0)) {
++_ignoreElementDepth;
return;
}
//-- if we are in an <any> section
//-- we delegate the event handling
if (_anyUnmarshaller != null) {
_depth++;
_anyUnmarshaller.startElement(namespaceURI, localName, qName, atts);
return;
}
//-- Create a new namespace scope if necessary and
//-- make sure the flag is reset to true
if (_createNamespaceScope)
_namespaces = _namespaces.createNamespaces();
else
_createNamespaceScope = true;
if (_reusableAtts == null) {
if (atts != null)
_reusableAtts = new AttributeSetImpl(atts.getLength());
else {
//-- we can't pass a null AttributeSet to the
//-- startElement
_reusableAtts = new AttributeSetImpl();
}
}
else {
_reusableAtts.clear();
}
//-- process attributes
boolean hasQNameAtts = false;
if ((atts != null) && (atts.getLength() > 0)) {
//-- look for any potential namespace declarations
//-- in case namespace processing was disable
//-- on the parser
for (int i = 0; i < atts.getLength(); i++) {
String attName = atts.getQName(i);
if ((attName != null) && (attName.length() > 0)) {
if (attName.equals(XMLNS)) {
_namespaces.addNamespace("", atts.getValue(i));
}
else if (attName.startsWith(XMLNS_PREFIX)) {
String prefix = attName.substring(XMLNS_PREFIX.length());
_namespaces.addNamespace(prefix, atts.getValue(i));
}
else {
//-- check for prefix
if (attName.indexOf(':') < 0) {
_reusableAtts.setAttribute(attName,
atts.getValue(i), atts.getURI(i));
}
else hasQNameAtts = true;
}
}
else {
//-- if attName is null or empty, just process as a normal
//-- attribute
attName = atts.getLocalName(i);
if (XMLNS.equals(attName)) {
_namespaces.addNamespace("", atts.getValue(i));
}
else {
_reusableAtts.setAttribute(attName, atts.getValue(i), atts.getURI(i));
}
}
}
}
//-- if we found any qName-only atts, process those
if (hasQNameAtts) {
for (int i = 0; i < atts.getLength(); i++) {
String attName = atts.getQName(i);
if ((attName != null) && (attName.length() > 0)) {
//-- process any non-namespace qName atts
if ((!attName.equals(XMLNS)) && (!attName.startsWith(XMLNS_PREFIX)))
{
int idx = attName.indexOf(':');
if (idx >= 0) {
String prefix = attName.substring(0, idx);
attName = attName.substring(idx+1);
String nsURI = atts.getURI(i);
if ((nsURI == null) || (nsURI.length() == 0)) {
nsURI = _namespaces.getNamespaceURI(prefix);
}
_reusableAtts.setAttribute(attName, atts.getValue(i), nsURI);
}
}
}
//-- else skip already processed in previous loop
}
}
//-- preserve parser passed arguments for any potential
//-- delegation
if (_elemInfo == null) {
_elemInfo = new ElementInfo(null, atts);
}
else {
_elemInfo.clear();
_elemInfo.attributes = atts;
}
if ((localName == null) || (localName.length() == 0)) {
if ((qName == null) || (qName.length() == 0)) {
String error = "Missing either 'localName' or 'qName', both cannot be emtpy or null.";
throw new SAXException(error);
}
localName = qName;
_elemInfo.qName = qName;
}
else {
if ((qName == null) || (qName.length() == 0)) {
if ((namespaceURI == null) || (namespaceURI.length() == 0)) {
_elemInfo.qName = localName;
}
else {
String prefix = _namespaces.getNamespacePrefix(namespaceURI);
if ((prefix != null) && (prefix.length() > 0)) {
_elemInfo.qName = prefix + ":" + localName;
}
}
}
}
int idx = localName.indexOf(':');
if (idx >= 0) {
String prefix = localName.substring(0, idx);
localName = localName.substring(idx+1);
if ((namespaceURI == null) || (namespaceURI.length() == 0)) {
namespaceURI = _namespaces.getNamespaceURI(prefix);
}
}
else {
//-- adjust empty namespace
if ((namespaceURI != null) && (namespaceURI.length() == 0))
namespaceURI = null;
}
//-- call private startElement
startElement(localName, namespaceURI, _reusableAtts);
} //-- startElement
/**
* <p>DocumentHandler#startElement</p>
*
* Signals the start of element
*
* @param name the name of the element
* @param atts the AttributeList containing the associated
* attributes for the element
*/
public void startElement(String name, AttributeList attList)
throws org.xml.sax.SAXException
{
if (debug) {
message("#startElement: " + name);
}
//-- If we are skipping elements that have appeared in the XML but for
//-- which we have no mapping, increase the ignore depth counter and return
if ((!_strictElements) && (_ignoreElementDepth > 0)) {
++_ignoreElementDepth;
return;
}
//-- if we are in an <any> section
//-- we delegate the event handling
if (_anyUnmarshaller != null) {
_depth++;
_anyUnmarshaller.startElement(name,attList);
return;
}
if (_elemInfo == null) {
_elemInfo = new ElementInfo(name, attList);
}
else {
_elemInfo.clear();
_elemInfo.qName = name;
_elemInfo.attributeList = attList;
}
//-- The namespace of the given element
String namespace = null;
//-- Begin Namespace Handling :
//-- XXX Note: This code will change when we update the XML event API
_namespaces = _namespaces.createNamespaces();
//-- convert AttributeList to AttributeSet and process
//-- namespace declarations
AttributeSet atts = processAttributeList(attList);
String prefix = "";
//String qName = name;
int idx = name.indexOf(':');
if (idx >= 0) {
prefix = name.substring(0,idx);
name = name.substring(idx+1);
}
namespace = _namespaces.getNamespaceURI(prefix);
//-- End Namespace Handling
//-- call private startElement method
startElement(name, namespace, atts);
} //-- startElement
/**
* Signals the start of an element with the given name.
*
* @param name the NCName of the element. It is an error
* if the name is a QName (ie. contains a prefix).
* @param namespace the namespace of the element. This may be null.
* Note: A null namespace is not the same as the default namespace unless
* the default namespace is also null.
* @param atts the AttributeSet containing the attributes associated
* with the element.
*/
private void startElement
(String name, String namespace, AttributeSet atts)
throws SAXException
{
UnmarshalState state = null;
String xmlSpace = null;
//-- handle special atts
if (atts != null) {
//-- xml:space
xmlSpace = atts.getValue(XML_SPACE, Namespaces.XML_NAMESPACE);
if (xmlSpace == null) {
xmlSpace = atts.getValue(XML_SPACE_WITH_PREFIX, "");
}
}
if (_stateInfo.empty()) {
//-- Initialize since this is the first element
if (_topClass == null) {
if (_topObject != null) {
_topClass = _topObject.getClass();
}
}
if (_cdResolver == null) {
if (_topClass == null) {
String err = "The class for the root element '" +
name + "' could not be found.";
throw new SAXException(err);
}
_cdResolver = new ClassDescriptorResolverImpl(_loader);
}
_topState = getState();
_topState.elementName = name;
_topState.wsPreserve = (xmlSpace != null) ? PRESERVE.equals(xmlSpace) : _wsPreserve;
XMLClassDescriptor classDesc = null;
//-- If _topClass is null, then we need to search
//-- the resolver for one
String instanceClassname = null;
if (_topClass == null) {
//-- check for xsi:type
instanceClassname = getInstanceType(atts, null);
if (instanceClassname != null) {
//-- first try loading class directly
try {
_topClass = loadClass(instanceClassname, null);
}
catch(ClassNotFoundException cnfe) {}
if (_topClass == null) {
classDesc = getClassDescriptor(instanceClassname);
if (classDesc != null) {
_topClass = classDesc.getJavaClass();
}
if (_topClass == null) {
throw new SAXException("Class not found: " +
instanceClassname);
}
}
}
else {
classDesc = resolveByXMLName(name, namespace, null);
if (classDesc == null) {
classDesc = getClassDescriptor(name, _loader);
if (classDesc == null) {
classDesc = getClassDescriptor(JavaNaming.toJavaClassName(name));
}
}
if (classDesc != null) {
_topClass = classDesc.getJavaClass();
}
}
if (_topClass == null) {
String err = "The class for the root element '" +
name + "' could not be found.";
throw new SAXException(err);
}
}
//-- create a "fake" FieldDescriptor for the root element
XMLFieldDescriptorImpl fieldDesc
= new XMLFieldDescriptorImpl(_topClass,
name,
name,
NodeType.Element);
_topState.fieldDesc = fieldDesc;
//-- look for XMLClassDescriptor if null
//-- always check resolver first
if (classDesc == null)
classDesc = getClassDescriptor(_topClass);
//-- check for top-level primitives
if (classDesc == null) {
if (isPrimitive(_topClass)) {
classDesc = new PrimitivesClassDescriptor(_topClass);
fieldDesc.setIncremental(false);
_topState.primitiveOrImmutable = true;
}
}
fieldDesc.setClassDescriptor(classDesc);
if (classDesc == null) {
//-- report error
if ((!isPrimitive(_topClass)) &&
(!Serializable.class.isAssignableFrom( _topClass )))
throw new SAXException(MarshalException.NON_SERIALIZABLE_ERR);
String err = "unable to create XMLClassDescriptor " +
"for class: " + _topClass.getName();
throw new SAXException(err);
}
_topState.classDesc = classDesc;
_topState.type = _topClass;
if ((_topObject == null) && (!_topState.primitiveOrImmutable)) {
// Retrieving the xsi:type attribute, if present
String topPackage = getJavaPackage(_topClass);
if (instanceClassname == null)
instanceClassname = getInstanceType(atts, topPackage);
else {
//-- instance type already processed above, reset
//-- to null to prevent entering next block
instanceClassname = null;
}
if (instanceClassname != null) {
Class instanceClass = null;
Object instance = null;
try {
XMLClassDescriptor xcd =
getClassDescriptor(instanceClassname);
boolean loadClass = true;
if (xcd != null) {
instanceClass = xcd.getJavaClass();
if (instanceClass != null) {
loadClass = (!instanceClassname.equals(instanceClass.getName()));
}
}
if (loadClass) {
try {
instanceClass = loadClass(instanceClassname, null);
}
catch(ClassNotFoundException cnfe) {
//-- revert back to ClassDescriptor's associated
//-- class
if (xcd != null)
instanceClass = xcd.getJavaClass();
}
}
if (instanceClass == null) {
throw new SAXException("Class not found: " +
instanceClassname);
}
if (!_topClass.isAssignableFrom(instanceClass)) {
String err = instanceClass + " is not a subclass of "
+ _topClass;
throw new SAXException(err);
}
}
catch(Exception ex) {
String msg = "unable to instantiate " +
instanceClassname + "; ";
throw new SAXException(msg + ex);
}
//-- try to create instance of the given Class
Arguments args = processConstructorArgs(atts, classDesc);
_topState.object = createInstance(instanceClass, args);
}
//-- no xsi type information present
else {
//-- try to create instance of the given Class
Arguments args = processConstructorArgs(atts, classDesc);
_topState.object = createInstance(_topClass, args);
}
}
//-- otherwise use _topObject
else {
_topState.object = _topObject;
}
_stateInfo.push(_topState);
if (!_topState.primitiveOrImmutable) {
//--The top object has just been initialized
//--notify the listener
if ( _unmarshalListener != null )
_unmarshalListener.initialized(_topState.object);
processAttributes(atts, classDesc);
if ( _unmarshalListener != null )
_unmarshalListener.attributesProcessed(_topState.object);
processNamespaces(classDesc);
}
String pkg = getJavaPackage(_topClass);
if (getMappedPackage(namespace) == null)
{
addNamespaceToPackageMapping(namespace, pkg);
}
return;
} //--rootElement
//-- get MarshalDescriptor for the given element
UnmarshalState parentState = (UnmarshalState)_stateInfo.peek();
//Test if we can accept the field in the parentState
//in case the parentState fieldDesc is a container
//-- This following logic tests to see if we are in a
//-- container and we need to close out the container
//-- before proceeding:
boolean canAccept = false;
while ((parentState.fieldDesc != null) &&
(parentState.fieldDesc.isContainer() && !canAccept) )
{
XMLClassDescriptor tempClassDesc = parentState.classDesc;
//-- Find ClassDescriptor for Parent
if (tempClassDesc == null) {
tempClassDesc = (XMLClassDescriptor)parentState.fieldDesc.getClassDescriptor();
if (tempClassDesc == null)
tempClassDesc = getClassDescriptor(parentState.object.getClass());
}
canAccept = tempClassDesc.canAccept(name, namespace, parentState.object);
if (!canAccept) {
//-- Does container class even handle this field?
if (tempClassDesc.getFieldDescriptor(name, namespace, NodeType.Element) != null) {
if (!parentState.fieldDesc.isMultivalued()) {
String error = "The container object (" + tempClassDesc.getJavaClass().getName();
error += ") cannot accept the child object associated with the element '" + name + "'";
error += " because the container is already full!";
ValidationException vx = new ValidationException(error);
throw new SAXException(vx);
}
}
endElement(parentState.elementName);
parentState = (UnmarshalState)_stateInfo.peek();
}
tempClassDesc = null;
}
//-- create new state object
state = getState();
state.elementName = name;
state.parent = parentState;
if (xmlSpace != null)
state.wsPreserve = PRESERVE.equals(xmlSpace);
else
state.wsPreserve = parentState.wsPreserve;
_stateInfo.push(state);
//-- make sure we should proceed
if (parentState.object == null) {
if (!parentState.wrapper) return;
}
Class _class = null;
//-- Find ClassDescriptor for Parent
XMLClassDescriptor classDesc = parentState.classDesc;
if (classDesc == null) {
classDesc = (XMLClassDescriptor)parentState.fieldDesc.getClassDescriptor();
if (classDesc == null)
classDesc = getClassDescriptor(parentState.object.getClass());
}
//----------------------------------------------------/
//- Find FieldDescriptor associated with the element -/
//----------------------------------------------------/
//-- A reference to the FieldDescriptor associated
//-- the the "current" element
XMLFieldDescriptor descriptor = null;
//-- inherited class descriptor
//-- (only needed if descriptor cannot be found directly)
XMLClassDescriptor cdInherited = null;
//-- loop through stack and find correct descriptor
//int pIdx = _stateInfo.size() - 2; //-- index of parentState
UnmarshalState targetState = parentState;
String path = "";
StringBuffer pathBuf = null;
int count = 0;
boolean isWrapper = false;
XMLClassDescriptor oldClassDesc = classDesc;
while (descriptor == null) {
//-- NOTE (kv 20050228):
//-- we need to clean this code up, I made this
//-- fix to make sure the correct descriptor which
//-- matches the location path is used
if (path.length() > 0) {
String tmpName = path + "/" + name;
descriptor = classDesc.getFieldDescriptor(tmpName, namespace, NodeType.Element);
}
//-- End Patch
if (descriptor == null) {
descriptor = classDesc.getFieldDescriptor(name, namespace, NodeType.Element);
}
//-- Namespace patch, should be moved to XMLClassDescriptor, but
//-- this is the least intrusive patch at the moment. kv - 20030423
if ((descriptor != null) && (!descriptor.isContainer())) {
if ((namespace != null) && (namespace.length() > 0)) {
if (!namespaceEquals(namespace, descriptor.getNameSpaceURI())) {
//-- if descriptor namespace is not null, then we must
//-- have a namespace match, so set descriptor to null,
//-- or if descriptor is not a wildcard we can also
//-- set to null.
if ((descriptor.getNameSpaceURI() != null) || (!descriptor.matches("*"))) {
descriptor = null;
}
}
}
}
//-- end namespace patch
/*
If descriptor is null, we need to handle possible inheritence,
which might not be described in the current ClassDescriptor.
This can be a slow process...for speed use the match attribute
of the xml element in the mapping file. This logic might
not be completely necessary, and perhaps we should remove it.
*/
// handle multiple level locations (where count > 0) (CASTOR-1039)
// if ((descriptor == null) && (count == 0) && (!targetState.wrapper)) {
if ((descriptor == null) && (!targetState.wrapper)) {
MarshalFramework.InheritanceMatch[] matches = null;
try {
matches = searchInheritance(name, namespace, classDesc, _cdResolver);
}
catch(MarshalException rx) {
//-- TODO:
}
if (matches.length != 0) {
- InheritanceMatch match = matches[0];
+ InheritanceMatch match = null;
+ // It may be the case that this class descriptor can
+ // appear under multiple parent field descriptors. Look
+ // for the first match whose parent file descriptor XML
+ // name matches the name of the element we are under
+ for(int i = 0; i < matches.length; i++) {
+ if(parentState.elementName.equals(matches[i].parentFieldDesc.getLocationPath())) {
+ match = matches[i];
+ break;
+ }
+ }
+ if(match == null) match = matches[0];
descriptor = match.parentFieldDesc;
cdInherited = match.inheritedClassDesc;
break; //-- found
}
/* */
// handle multiple level locations (where count > 0) (CASTOR-1039)
// isWrapper = (isWrapper || hasFieldsAtLocation(name, classDesc));
String tmpLocation = name;
if (count > 0) { tmpLocation = path + "/" + name; }
isWrapper = (isWrapper || hasFieldsAtLocation(tmpLocation, classDesc));
}
else if (descriptor != null) {
String tmpPath = descriptor.getLocationPath();
if (tmpPath == null) tmpPath = "";
if (path.equals(tmpPath))break; //-- found
descriptor = null; //-- not found, try again
}
else {
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(path);
pathBuf.append('/');
pathBuf.append(name);
isWrapper = (isWrapper || hasFieldsAtLocation(pathBuf.toString(), classDesc));
}
//-- Make sure there are more parent classes on stack
//-- otherwise break, since there is nothing to do
//if (pIdx == 0) break;
if (targetState == _topState) break;
//-- adjust name and try parent
if (count == 0)
path = targetState.elementName;
else {
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(targetState.elementName);
pathBuf.append('/');
pathBuf.append(path);
path = pathBuf.toString();
}
//-- get
//--pIdx;
//targetState = (UnmarshalState)_stateInfo.elementAt(pIdx);
targetState = targetState.parent;
classDesc = targetState.classDesc;
count++;
}
//-- The field descriptor is still null, we face a problem
if (descriptor == null) {
//-- reset classDesc
classDesc = oldClassDesc;
//-- isWrapper?
if (isWrapper) {
state.classDesc = new XMLClassDescriptorImpl(ContainerElement.class, name);
state.wrapper = true;
if (debug) {
message("wrapper-element: " + name);
}
//-- process attributes
processWrapperAttributes(atts);
return;
}
String mesg = "unable to find FieldDescriptor for '" + name;
mesg += "' in ClassDescriptor of " + classDesc.getXMLName();
//-- unwrap classDesc, if necessary, for the check
//-- Introspector.introspected done below
if (classDesc instanceof InternalXMLClassDescriptor) {
classDesc = ((InternalXMLClassDescriptor)classDesc).getClassDescriptor();
}
//-- If we are skipping elements that have appeared in the XML but for
//-- which we have no mapping, increase the ignore depth counter and return
if (! _strictElements) {
++_ignoreElementDepth;
//-- remove the StateInfo we just added
_stateInfo.pop();
if (debug) {
message(mesg + " - ignoring extra element.");
}
return;
}
//if we have no field descriptor and
//the class descriptor was introspected
//just log it
else if (Introspector.introspected(classDesc)) {
//if (warn)
message(mesg);
return;
}
//-- otherwise report error since we cannot find a suitable
//-- descriptor
else {
throw new SAXException(mesg);
}
} //-- end null descriptor
/// DEBUG: System.out.println("path: " + path);
//-- Save targetState (used in endElement)
if (targetState != parentState) {
state.targetState = targetState;
parentState = targetState; //-- reassign
}
Object object = parentState.object;
//--container support
if (descriptor.isContainer()) {
//create a new state to set the container as the object
//don't save the current state, it will be recreated later
if (debug) {
message("#container: " + descriptor.getFieldName());
}
//-- clear current state and re-use for the container
state.clear();
//-- inherit whitespace preserving from the parentState
state.wsPreserve = parentState.wsPreserve;
state.parent = parentState;
//here we can hard-code a name or take the field name
state.elementName = descriptor.getFieldName();
state.fieldDesc = descriptor;
state.classDesc = (XMLClassDescriptor)descriptor.getClassDescriptor();
Object containerObject = null;
//1-- the container is not multivalued (not a collection)
if (!descriptor.isMultivalued()) {
// Check if the container object has already been instantiated
FieldHandler handler = descriptor.getHandler();
containerObject = handler.getValue(object);
if (containerObject != null){
if (state.classDesc != null) {
if (state.classDesc.canAccept(name, namespace, containerObject)) {
//remove the descriptor from the used list
parentState.markAsNotUsed(descriptor);
}
}
else {
//remove the descriptor from the used list
parentState.markAsNotUsed(descriptor);
}
}
else {
containerObject = handler.newInstance(object);
}
}
//2-- the container is multivalued
else {
Class containerClass = descriptor.getFieldType();
try {
containerObject = containerClass.newInstance();
}
catch(Exception ex) {
throw new SAXException(ex);
}
}
state.object = containerObject;
state.type = containerObject.getClass();
//we need to recall startElement()
//so that we can find a more appropriate descriptor in for the given name
_namespaces = _namespaces.createNamespaces();
startElement(name, namespace, atts);
return;
}
//--End of the container support
//-- Find object type and create new Object of that type
state.fieldDesc = descriptor;
/* <update>
* we need to add this code back in, to make sure
* we have proper access rights.
*
if (!descriptor.getAccessRights().isWritable()) {
if (debug) {
buf.setLength(0);
buf.append("The field for element '");
buf.append(name);
buf.append("' is read-only.");
message(buf.toString());
}
return;
}
*/
//-- Find class to instantiate
//-- check xml names to see if we should look for a more specific
//-- ClassDescriptor, otherwise just use the one found in the
//-- descriptor
classDesc = null;
if (cdInherited != null) classDesc = cdInherited;
else if (!name.equals(descriptor.getXMLName()))
classDesc = resolveByXMLName(name, namespace, null);
if (classDesc == null)
classDesc = (XMLClassDescriptor)descriptor.getClassDescriptor();
FieldHandler handler = descriptor.getHandler();
boolean useHandler = true;
try {
//-- Get Class type...first use ClassDescriptor,
//-- since it could be more specific than
//-- the FieldDescriptor
if (classDesc != null) {
_class = classDesc.getJavaClass();
//-- XXXX This is a hack I know...but we
//-- XXXX can't use the handler if the field
//-- XXXX types are different
if (descriptor.getFieldType() != _class) {
state.derived = true;
}
}
else {
_class = descriptor.getFieldType();
}
//-- This *shouldn't* happen, but a custom implementation
//-- could return null in the XMLClassDesctiptor#getJavaClass
//-- or XMLFieldDescriptor#getFieldType. If so, just replace
//-- with java.lang.Object.class (basically "anyType").
if (_class == null) {
_class = java.lang.Object.class;
}
// Retrieving the xsi:type attribute, if present
String currentPackage = getJavaPackage(parentState.type);
String instanceType = getInstanceType(atts, currentPackage);
if (instanceType != null) {
Class instanceClass = null;
try {
XMLClassDescriptor instanceDesc
= getClassDescriptor(instanceType, _loader);
boolean loadClass = true;
if (instanceDesc != null) {
instanceClass = instanceDesc.getJavaClass();
classDesc = instanceDesc;
if (instanceClass != null) {
loadClass = (!instanceClass.getName().equals(instanceType));
}
}
if (loadClass) {
instanceClass = loadClass(instanceType, null);
//the FieldHandler can be either an XMLFieldHandler
//or a FieldHandlerImpl
FieldHandler tempHandler = descriptor.getHandler();
boolean collection = false;
if (tempHandler instanceof FieldHandlerImpl) {
collection = ((FieldHandlerImpl)tempHandler).isCollection();
}
else {
collection = Introspector.isCollection(instanceClass);
}
if ( (! collection ) &&
! _class.isAssignableFrom(instanceClass))
{
if (!isPrimitive(_class)) {
String err = instanceClass.getName()
+ " is not a subclass of " + _class.getName();
throw new SAXException(err);
}
}
}
_class = instanceClass;
useHandler = false;
}
catch(Exception ex) {
String msg = "unable to instantiate " + instanceType;
throw new SAXException(msg + "; " + ex);
}
}
//-- Handle ArrayHandler
if (_class == Object.class) {
if (parentState.object instanceof ArrayHandler)
_class = ((ArrayHandler)parentState.object).componentType();
}
//-- Handle support for "Any" type
if (_class == Object.class) {
Class pClass = parentState.type;
ClassLoader loader = pClass.getClassLoader();
//-- first look for a descriptor based
//-- on the XML name
classDesc = resolveByXMLName(name, namespace, loader);
//-- if null, create classname, and try resolving
String cname = null;
if (classDesc == null) {
//-- create class name
cname = JavaNaming.toJavaClassName(name);
classDesc = getClassDescriptor(cname, loader);
}
//-- if still null, try using parents package
if (classDesc == null) {
//-- use parent to get package information
String pkg = pClass.getName();
int idx = pkg.lastIndexOf('.');
if (idx > 0) {
pkg = pkg.substring(0,idx+1);
cname = pkg + cname;
classDesc = getClassDescriptor(cname, loader);
}
}
if (classDesc != null) {
_class = classDesc.getJavaClass();
useHandler = false;
}
else {
//we are dealing with an AnyNode
//1- creates a new SAX2ANY handler
_anyUnmarshaller = new SAX2ANY(_namespaces);
//2- delegates the element handling
if (_elemInfo.attributeList != null) {
//-- SAX 1
_anyUnmarshaller.startElement(_elemInfo.qName,
_elemInfo.attributeList);
}
else {
//-- SAX 2
_anyUnmarshaller.startElement(namespace, name, _elemInfo.qName,
_elemInfo.attributes);
}
//first element so depth can only be one at this point
_depth = 1;
state.object = _anyUnmarshaller.getStartingNode();
state.type = _class;
//don't need to continue
return;
}
}
boolean byteArray = false;
if (_class.isArray())
byteArray = (_class.getComponentType() == Byte.TYPE);
//-- check for immutable
if (isPrimitive(_class) ||
descriptor.isImmutable() ||
byteArray)
{
state.object = null;
state.primitiveOrImmutable = true;
//-- handle immutable types, such as java.util.Locale
if (descriptor.isImmutable()) {
if (classDesc == null)
classDesc = getClassDescriptor(_class);
state.classDesc = classDesc;
Arguments args = processConstructorArgs(atts, classDesc);
if ((args != null) && (args.size() > 0)) {
state.args = args;
}
}
}
else {
if (classDesc == null)
classDesc = getClassDescriptor(_class);
//-- XXXX should remove this test once we can
//-- XXXX come up with a better solution
if ((!state.derived) && useHandler) {
boolean create = true;
if (_reuseObjects) {
state.object = handler.getValue(parentState.object);
create = (state.object == null);
}
if (create) {
Arguments args = processConstructorArgs(atts, classDesc);
if ((args.values != null) && (args.values.length > 0)) {
if (handler instanceof ExtendedFieldHandler) {
ExtendedFieldHandler efh =
(ExtendedFieldHandler)handler;
state.object = efh.newInstance(parentState.object, args.values);
}
else {
String err = "constructor arguments can only be " +
"used with an ExtendedFieldHandler.";
throw new SAXException(err);
}
}
else {
state.object = handler.newInstance(parentState.object);
}
}
}
//-- reassign class in case there is a conflict
//-- between descriptor#getFieldType and
//-- handler#newInstance...I should hope not, but
//-- who knows
if (state.object != null) {
_class = state.object.getClass();
if (classDesc != null) {
if (classDesc.getJavaClass() != _class) {
classDesc = null;
}
}
}
else {
try {
if (_class.isArray()) {
state.object = new ArrayHandler(_class.getComponentType());
_class = ArrayHandler.class;
}
else {
Arguments args = processConstructorArgs(atts, classDesc);
state.object = createInstance(_class, args);
//state.object = _class.newInstance();
}
}
catch(java.lang.Exception ex) {
String err = "unable to instantiate a new type of: ";
err += className(_class);
err += "; " + ex.getMessage();
//storing causal exception using SAX non-standard method...
SAXException sx = new SAXException(err, ex);
//...and also using Java 1.4 method
sx.initCause(ex);
throw sx;
}
}
}
state.type = _class;
}
catch (java.lang.IllegalStateException ise) {
message(ise.toString());
throw new SAXException(ise);
}
//-- At this point we should have a new object, unless
//-- we are dealing with a primitive type, or a special
//-- case such as byte[]
if (classDesc == null) {
classDesc = getClassDescriptor(_class);
}
state.classDesc = classDesc;
if ((state.object == null) && (!state.primitiveOrImmutable))
{
String err = "unable to unmarshal: " + name + "\n";
err += " - unable to instantiate: " + className(_class);
throw new SAXException(err);
}
//-- assign object, if incremental
if (descriptor.isIncremental()) {
if (debug) {
message("debug: Processing incrementally for element: " + name);
}
try {
handler.setValue(parentState.object, state.object);
}
catch(java.lang.IllegalStateException ise) {
String err = "unable to add \"" + name + "\" to ";
err += parentState.fieldDesc.getXMLName();
err += " due to the following error: " + ise;
throw new SAXException(err);
}
}
if (state.object != null) {
//--The object has just been initialized
//--notify the listener
if ( _unmarshalListener != null )
_unmarshalListener.initialized(state.object);
processAttributes(atts, classDesc);
if ( _unmarshalListener != null )
_unmarshalListener.attributesProcessed(state.object);
processNamespaces(classDesc);
}
else if ((state.type != null) && (!state.primitiveOrImmutable)) {
if (atts != null) {
processWrapperAttributes(atts);
StringBuffer buffer = new StringBuffer();
buffer.append("The current object for element '");
buffer.append(name);
buffer.append("\' is null. Processing attributes as location");
buffer.append("/wrapper only and ignoring all other attribtes.");
message(buffer.toString());
}
}
else {
//-- check for special attributes, such as xsi:nil
if (atts != null) {
String nil = atts.getValue(NIL_ATTR, XSI_NAMESPACE);
state.nil = "true".equals(nil);
processWrapperAttributes(atts);
}
}
} //-- void startElement(String, AttributeList)
/**
* Signals to start the namespace - prefix mapping
*
* @param prefix the namespace prefix to map
* @param uri the namespace URI
*/
public void startPrefixMapping(String prefix, String uri)
throws SAXException
{
//-- Patch for Xerces 2.x bug
//-- prevent attempting to declare "XML" namespace
if (Namespaces.XML_NAMESPACE_PREFIX.equals(prefix) &&
Namespaces.XML_NAMESPACE.equals(uri))
{
return;
}
else if (XMLNS.equals(prefix)) {
return;
}
//-- end Xerces 2.x bug
//-- Forward the call to SAX2ANY
//-- or create a namespace node
if (_anyUnmarshaller != null) {
_anyUnmarshaller.startPrefixMapping(prefix, uri);
}
else if (_createNamespaceScope) {
_namespaces = _namespaces.createNamespaces();
_createNamespaceScope = false;
}
_namespaces.addNamespace(prefix, uri);
/*
//-- add namespace declarations to set of current attributes
String attName = null;
if ((prefix == null) || (prefix.length() == 0))
attName = XMLNS_DECL;
else
attName = XMLNS_PREFIX + prefix;
_currentAtts.addAttribute(attName, uri);
*/
} //-- startPrefixMapping
//------------------------------------/
//- org.xml.sax.ErrorHandler methods -/
//------------------------------------/
public void error(SAXParseException exception)
throws org.xml.sax.SAXException
{
String err = "Parsing Error : "+exception.getMessage()+'\n'+
"Line : "+ exception.getLineNumber() + '\n'+
"Column : "+exception.getColumnNumber() + '\n';
throw new SAXException (err);
} //-- error
public void fatalError(SAXParseException exception)
throws org.xml.sax.SAXException
{
String err = "Parsing Error : "+exception.getMessage()+'\n'+
"Line : "+ exception.getLineNumber() + '\n'+
"Column : "+exception.getColumnNumber() + '\n';
throw new SAXException (err);
} //-- fatalError
public void warning(SAXParseException exception)
throws org.xml.sax.SAXException
{
String err = "Parsing Error : "+exception.getMessage()+'\n'+
"Line : "+ exception.getLineNumber() + '\n'+
"Column : "+exception.getColumnNumber() + '\n';
throw new SAXException (err);
} //-- warning
//---------------------/
//- Protected Methods -/
//---------------------/
/**
* Sets the current Castor configuration. Currently this
* Configuration is only used during Validation (which is
* why this method is currently protected, since it has
* no effect at this point on the actual configuration of
* the unmarshaller)
*
* Currently, this method should only be called by the
* Unmarshaller.
*/
protected void setConfiguration(Configuration config) {
_config = config;
} //-- setConfiguration
//-------------------/
//- Private Methods -/
//-------------------/
/**
* Adds the given reference to the "queue" until the referenced object
* has been unmarshalled.
*
* @param idRef the ID being referenced
* @param parent the target/parent object for the field
* @param descriptor the XMLFieldDescriptor for the field
*/
private void addReference(String idRef, Object parent, XMLFieldDescriptor descriptor)
{
ReferenceInfo refInfo = new ReferenceInfo(idRef, parent, descriptor);
if (_resolveTable == null)
_resolveTable = new Hashtable();
else {
refInfo.next = (ReferenceInfo)_resolveTable.get(idRef);
}
_resolveTable.put(idRef, refInfo);
} //-- addReference
/**
* Creates an instance of the given class
*/
private Object createInstance(Class type, Arguments args)
throws SAXException
{
Object instance = null;
try {
if (args == null) {
instance = _objectFactory.createInstance(type);
}
else {
instance = _objectFactory.createInstance(type, args.types, args.values);
}
}
catch(Exception ex) {
String msg = "unable to instantiate " + type.getName() + "; ";
// storing causal exception using SAX non-standard method...
SAXException sx = new SAXException(msg, ex);
//...and also using Java 1.4 method
sx.initCause(ex);
throw sx;
}
return instance;
} //-- createInstance
/**
* Marks the given state as available for use
*/
private void freeState(UnmarshalState state) {
state.clear();
_statePool.add(state);
} //-- freeState
/**
* Returns a free state from the state pool
*
* @return a free state from the state pool
*/
private UnmarshalState getState() {
if (_statePool.isEmpty()) return new UnmarshalState();
return (UnmarshalState) _statePool.remove(_statePool.size()-1);
} //-- freeState
/**
* Returns the resolved instance type attribute (xsi:type).
* If present the instance type attribute is resolved into
* a java class name and then returned.
*
* @param atts the AttributeList to search for the instance type
* attribute.
* @return the java class name corresponding to the value of
* the instance type attribute, or null if no instance type
* attribute exists in the given AttributeList.
*/
private String getInstanceType(AttributeSet atts, String currentPackage)
throws SAXException
{
if (atts == null) return null;
//-- find xsi:type attribute
String type = atts.getValue(XSI_TYPE, XSI_NAMESPACE);
if (type != null) {
if (type.startsWith(JAVA_PREFIX)) {
return type.substring(JAVA_PREFIX.length());
}
// check for namespace prefix in type
int idx = type.indexOf(':');
String typeNamespaceURI = null;
if (idx >= 0) {
// there is a namespace prefix
String prefix = type.substring(0, idx);
type = type.substring(idx + 1);
typeNamespaceURI = _namespaces.getNamespaceURI(prefix);
}
//-- Retrieve the type corresponding to the schema name and
//-- return it.
XMLClassDescriptor classDesc = null;
try {
classDesc = _cdResolver.resolveByXMLName(type, typeNamespaceURI, _loader);
if (classDesc != null)
return classDesc.getJavaClass().getName();
//-- if class descriptor is not found here, then no descriptors
//-- existed in memory...try to load one based on name of
//-- Schema type
final String className = JavaNaming.toJavaClassName(type);
String adjClassName = className;
String mappedPackage = getMappedPackage(typeNamespaceURI);
if ((mappedPackage != null) && (mappedPackage.length() > 0)) {
adjClassName = mappedPackage + "." + className;
}
classDesc = _cdResolver.resolve(adjClassName, _loader);
if (classDesc != null)
return classDesc.getJavaClass().getName();
//-- try to use "current Package"
if ((currentPackage != null) && currentPackage.length() > 0) {
adjClassName = currentPackage + '.' + className;
}
classDesc = _cdResolver.resolve(adjClassName, _loader);
if (classDesc != null)
return classDesc.getJavaClass().getName();
//-- Still can't find type, this may be due to an
//-- attempt to unmarshal an older XML instance
//-- that was marshalled with a previous Castor. A
//-- bug fix in the XMLMappingLoader prevents old
//-- xsi:type that are missing the "java:"
classDesc = _cdResolver.resolve(type, _loader);
if (classDesc != null)
return classDesc.getJavaClass().getName();
}
catch(ResolverException rx) {
throw new SAXException(rx);
}
}
return null;
} //-- getInstanceType
/**
* Looks up the package name from the given namespace URI
*
* @param namespace the namespace URI to lookup
* @return the package name or null.
*/
private String getMappedPackage(String namespace) {
String lookUpKey = (namespace != null) ? namespace : "";
return (String)_namespaceToPackage.get(lookUpKey);
} //-- getMappedPackage
/**
* Processes the given attribute list, and attempts to add each
* Attribute to the current Object on the stack
*
* @param atts the AttributeSet to process
* @param classDesc the classDesc to use during processing
* @param element the element name used for error reporting
**/
private void processAttributes
(AttributeSet atts, XMLClassDescriptor classDesc)
throws org.xml.sax.SAXException
{
//-- handle empty attributes
if ((atts == null) || (atts.getSize() == 0)) {
if (classDesc != null) {
XMLFieldDescriptor[] descriptors
= classDesc.getAttributeDescriptors();
for (int i = 0; i < descriptors.length; i++) {
XMLFieldDescriptor descriptor = descriptors[i];
if (descriptor == null) continue;
//-- Since many attributes represent primitive
//-- fields, we add an extra validation check here
//-- in case the class doesn't have a "has-method".
if (descriptor.isRequired() && (_validate || debug)) {
String err = classDesc.getXMLName() + " is missing " +
"required attribute: " + descriptor.getXMLName();
if (_locator != null) {
err += "\n - line: " + _locator.getLineNumber() +
" column: " + _locator.getColumnNumber();
}
if (_validate) throw new SAXException(err);
if (debug) message(err);
}
}
}
return;
}
UnmarshalState state = (UnmarshalState)_stateInfo.peek();
Object object = state.object;
if (classDesc == null) {
classDesc = state.classDesc;
if (classDesc == null) {
//-- no class desc, cannot process atts
//-- except for wrapper/location atts
processWrapperAttributes(atts);
return;
}
}
//-- First loop through Attribute Descriptors.
//-- Then, if we have any attributes which
//-- haven't been processed we can ask
//-- the XMLClassDescriptor for the FieldDescriptor.
XMLFieldDescriptor[] descriptors = classDesc.getAttributeDescriptors();
boolean[] processedAtts = new boolean[atts.getSize()];
for (int i = 0; i < descriptors.length; i++) {
XMLFieldDescriptor descriptor = descriptors[i];
String name = descriptor.getXMLName();
String namespace = descriptor.getNameSpaceURI();
int index = atts.getIndex(name, namespace);
if (index >= 0) {
processedAtts[index] = true;
}
//-- otherwise...for now just continue, this code needs to
//-- change when we upgrade to new event API
else continue;
try {
processAttribute(name, namespace, atts.getValue(index), descriptor, classDesc, object);
}
catch(java.lang.IllegalStateException ise) {
String err = "unable to add attribute \"" + name + "\" to '";
err += state.classDesc.getJavaClass().getName();
err += "' due to the following error: " + ise;
throw new SAXException(err);
}
}
//-- Handle any non processed attributes...
//-- This is useful for descriptors that might use
//-- wild-cards or other types of matching...as well
//-- as backward compatibility...attribute descriptors
//-- were erronously getting set with the default
//-- namespace by the source generator...this is
//-- also true of the generated classes for the
//-- Mapping Framework...we need to clean this up
//-- at some point in the future.
for (int i = 0; i < processedAtts.length; i++) {
if (processedAtts[i]) continue;
String namespace = atts.getNamespace(i);
String name = atts.getName(i);
//-- skip XSI attributes
if (XSI_NAMESPACE.equals(namespace)) {
if (NIL_ATTR.equals(name)) {
String value = atts.getValue(i);
state.nil = ("true".equals(value));
}
continue;
}
if (name.startsWith(XML_PREFIX + ':')) {
//-- XML specification specific attribute
//-- It should be safe to ignore these...but
//-- if you think otherwise...let use know!
if (debug) {
String msg = "ignoring attribute '" + name +
"' for class: " +
state.classDesc.getJavaClass().getName();
message(msg);
}
continue;
}
//-- This really should handle namespace...but it currently
//-- doesn't. Ignoring namespaces also helps with the
//-- backward compatibility issue mentioned above.
XMLFieldDescriptor descriptor =
classDesc.getFieldDescriptor(name, namespace, NodeType.Attribute);
if (descriptor == null) {
//-- check for nested attribute...loop through
//-- stack and find correct descriptor
int pIdx = _stateInfo.size() - 2; //-- index of parentState
String path = state.elementName;
StringBuffer pathBuf = null;
while (pIdx >= 0) {
UnmarshalState targetState = (UnmarshalState)_stateInfo.elementAt(pIdx);
--pIdx;
if (targetState.wrapper) {
//path = targetState.elementName + "/" + path;
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(targetState.elementName);
pathBuf.append('/');
pathBuf.append(path);
path = pathBuf.toString();
continue;
}
classDesc = targetState.classDesc;
descriptor = classDesc.getFieldDescriptor(name, namespace, NodeType.Attribute);
if (descriptor != null) {
String tmpPath = descriptor.getLocationPath();
if (tmpPath == null) tmpPath = "";
if (path.equals(tmpPath)) break; //-- found
}
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(targetState.elementName);
pathBuf.append('/');
pathBuf.append(path);
path = pathBuf.toString();
//path = targetState.elementName + "/" + path;
//-- reset descriptor to make sure we don't
//-- exit the loop with a reference to a
//-- potentially incorrect one.
descriptor = null;
}
}
if (descriptor == null) {
if (_strictAttributes) {
//-- handle error
String error = "The attribute '" + name +
"' appears illegally on element '" +
state.elementName + "'.";
throw new SAXException(error);
}
continue;
}
try {
processAttribute(name, namespace, atts.getValue(i), descriptor, classDesc, object);
}
catch(java.lang.IllegalStateException ise) {
String err = "unable to add attribute \"" + name + "\" to '";
err += state.classDesc.getJavaClass().getName();
err += "' due to the following error: " + ise;
throw new SAXException(err);
}
}
} //-- processAttributes
/**
* Processes the given AttributeSet for wrapper elements.
*
* @param atts the AttributeSet to process
*/
private void processWrapperAttributes(AttributeSet atts)
throws org.xml.sax.SAXException
{
UnmarshalState state = (UnmarshalState)_stateInfo.peek();
//-- loop through attributes and look for the
//-- ancestor objects that they may belong to
for (int i = 0; i < atts.getSize(); i++) {
String name = atts.getName(i);
String namespace = atts.getNamespace(i);
//-- skip XSI attributes
if (XSI_NAMESPACE.equals(namespace))
continue;
XMLFieldDescriptor descriptor = null;
XMLClassDescriptor classDesc = null;
//-- check for nested attribute...loop through
//-- stack and find correct descriptor
int pIdx = _stateInfo.size() - 2; //-- index of parentState
String path = state.elementName;
StringBuffer pathBuf = null;
UnmarshalState targetState = null;
while (pIdx >= 0) {
targetState = (UnmarshalState)_stateInfo.elementAt(pIdx);
--pIdx;
if (targetState.wrapper) {
//path = targetState.elementName + "/" + path;
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(targetState.elementName);
pathBuf.append('/');
pathBuf.append(path);
path = pathBuf.toString();
continue;
}
classDesc = targetState.classDesc;
XMLFieldDescriptor[] descriptors = classDesc.getAttributeDescriptors();
boolean found = false;
for (int a = 0; a < descriptors.length; a++) {
descriptor = descriptors[a];
if (descriptor == null) continue;
if (descriptor.matches(name)) {
String tmpPath = descriptor.getLocationPath();
if (tmpPath == null) tmpPath = "";
if (path.equals(tmpPath)) {
found = true;
break;
}
}
}
if (found) break;
//path = targetState.elementName + "/" + path;
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(targetState.elementName);
pathBuf.append('/');
pathBuf.append(path);
path = pathBuf.toString();
//-- reset descriptor to make sure we don't
//-- exit the loop with a reference to a
//-- potentially incorrect one.
descriptor = null;
}
if (descriptor != null) {
try {
processAttribute(name,
namespace,
atts.getValue(i),
descriptor,
classDesc,
targetState.object);
}
catch(java.lang.IllegalStateException ise) {
String err = "unable to add attribute \"" + name + "\" to '";
err += state.classDesc.getJavaClass().getName();
err += "' due to the following error: " + ise;
throw new SAXException(err);
}
}
}
} //-- processWrapperAttributes
/**
* Processes the given Attribute
**/
private void processAttribute
(String attName, String attNamespace, String attValue,
XMLFieldDescriptor descriptor,
XMLClassDescriptor classDesc,
Object parent) throws org.xml.sax.SAXException
{
//Object value = attValue;
while (descriptor.isContainer()) {
FieldHandler handler = descriptor.getHandler();
Object containerObject = handler.getValue(parent);
if (containerObject == null) {
containerObject = handler.newInstance(parent);
handler.setValue(parent, containerObject);
}
ClassDescriptor containerClassDesc = ((XMLFieldDescriptorImpl)descriptor).getClassDescriptor();
descriptor = ((XMLClassDescriptor)containerClassDesc).getFieldDescriptor(
attName, attNamespace, NodeType.Attribute);
parent = containerObject;
}
if (attValue == null) {
//-- Since many attributes represent primitive
//-- fields, we add an extra validation check here
//-- in case the class doesn't have a "has-method".
if (descriptor.isRequired() && _validate) {
String err = classDesc.getXMLName() + " is missing " +
"required attribute: " + attName;
if (_locator != null) {
err += "\n - line: " + _locator.getLineNumber() +
" column: " + _locator.getColumnNumber();
}
throw new SAXException(err);
}
return;
}
//-- if this is the identity then save id
if (classDesc.getIdentity() == descriptor) {
_idResolver.bind(attValue, parent);
//-- save key in current state
UnmarshalState state = (UnmarshalState) _stateInfo.peek();
state.key = attValue;
//-- resolve waiting references
resolveReferences(attValue, parent);
}
//-- if this is an IDREF(S) then resolve reference(s)
else if (descriptor.isReference()) {
if (descriptor.isMultivalued()) {
StringTokenizer st = new StringTokenizer(attValue);
while (st.hasMoreTokens()) {
processIDREF(st.nextToken(), descriptor, parent);
}
}
else processIDREF(attValue, descriptor, parent);
//-- object values have been set by processIDREF
//-- simply return
return;
}
//-- if it's a constructor argument, we can exit at this point
//-- since constructor arguments have already been set
if (descriptor.isConstructorArgument())
return;
//-- attribute handler
FieldHandler handler = descriptor.getHandler();
if(handler==null)
return;
//-- attribute field type
Class type = descriptor.getFieldType();
String valueType = descriptor.getSchemaType();
boolean isPrimative = isPrimitive(type);
boolean isQName = valueType!=null && valueType.equals(QNAME_NAME);
//-- if this is an multi-value attribute
StringTokenizer attrValueTokenizer = null;
if (descriptor.isMultivalued())
{
attrValueTokenizer = new StringTokenizer(attValue);
if(attrValueTokenizer.hasMoreTokens())
attValue = attrValueTokenizer.nextToken();
}
while(true)
{
//-- value to set
Object value = attValue;
//-- check for proper type and do type conversion
if (isPrimative)
value = toPrimitiveObject(type, attValue, descriptor);
//-- check if the value is a QName that needs to
//-- be resolved (ns:value -> {URI}value)
if(isQName)
value = resolveNamespace(value);
//-- set value
handler.setValue(parent, value);
//-- more values?
if(attrValueTokenizer==null)
break;
if(!attrValueTokenizer.hasMoreTokens())
break;
//-- next value
attValue = attrValueTokenizer.nextToken();
}
} //-- processAttribute
/**
* Processes the given attribute set, and creates the
* constructor arguments
*
* @param atts the AttributeSet to process
* @param classDesc the XMLClassDescriptor of the objec
* @return the array of constructor argument values.
*/
private Arguments processConstructorArgs
(AttributeSet atts, XMLClassDescriptor classDesc)
throws org.xml.sax.SAXException
{
if (classDesc == null) return new Arguments();
//-- Loop through Attribute Descriptors and build
//-- the argument array
//-- NOTE: Due to IDREF being able to reference an
//-- un-yet unmarshalled object, we cannot handle
//-- references as constructor arguments.
//-- kvisco - 20030421
XMLFieldDescriptor[] descriptors = classDesc.getAttributeDescriptors();
int count = 0;
for (int i = 0; i < descriptors.length; i++) {
XMLFieldDescriptor descriptor = descriptors[i];
if (descriptor == null) continue;
if (descriptor.isConstructorArgument()) ++count;
}
Arguments args = new Arguments();
if (count == 0) return args;
args.values = new Object[count];
args.types = new Class[count];
for (int i = 0; i < descriptors.length; i++) {
XMLFieldDescriptor descriptor = descriptors[i];
if (descriptor == null) continue;
if (!descriptor.isConstructorArgument()) continue;
int argIndex = descriptor.getConstructorArgumentIndex();
if (argIndex >= count) {
String err = "argument index out of bounds: " + argIndex;
throw new SAXException(err);
}
args.types[argIndex] = descriptor.getFieldType();
String name = descriptor.getXMLName();
String namespace = descriptor.getNameSpaceURI();
int index = atts.getIndex(name, namespace);
if (index >= 0) {
Object value = atts.getValue(index);
//-- check for proper type and do type
//-- conversion
if (isPrimitive(args.types[argIndex]))
value = toPrimitiveObject(args.types[argIndex], (String)value, descriptor);
//check if the value is a QName that needs to
//be resolved (ns:value -> {URI}value)
String valueType = descriptor.getSchemaType();
if ((valueType != null) && (valueType.equals(QNAME_NAME))) {
value = resolveNamespace(value);
}
args.values[argIndex] = value;
}
else {
args.values[argIndex] = null;
}
}
return args;
} //-- processConstructorArgs
/**
* Processes the given IDREF
*
* @param idRef the ID of the object in which to reference
* @param descriptor the current FieldDescriptor
* @param parent the current parent object
* @return true if the ID was found and resolved properly
*/
private boolean processIDREF
(String idRef, XMLFieldDescriptor descriptor, Object parent)
{
Object value = _idResolver.resolve(idRef);
if (value == null) {
//-- save state to resolve later
addReference(idRef, parent, descriptor);
}
else {
FieldHandler handler = descriptor.getHandler();
if (handler != null)
handler.setValue(parent, value);
}
return (value != null);
} //-- processIDREF
/**
* Processes the attributes and namespace declarations found
* in the given SAX AttributeList. The global AttributeSet
* is cleared and updated with the attributes. Namespace
* declarations are added to the set of namespaces in scope.
*
* @param atts the AttributeList to process.
**/
private AttributeSet processAttributeList(AttributeList atts)
throws SAXException
{
if (atts == null) return new AttributeSetImpl(0);
//-- process all namespaces first
int attCount = 0;
boolean[] validAtts = new boolean[atts.getLength()];
for (int i = 0; i < validAtts.length; i++) {
String attName = atts.getName(i);
if (attName.equals(XMLNS)) {
_namespaces.addNamespace("", atts.getValue(i));
}
else if (attName.startsWith(XMLNS_PREFIX)) {
String prefix = attName.substring(XMLNS_PREFIX_LENGTH);
_namespaces.addNamespace(prefix, atts.getValue(i));
}
else {
validAtts[i] = true;
++attCount;
}
}
//-- process validAtts...if any exist
AttributeSetImpl attSet = null;
if (attCount > 0) {
attSet = new AttributeSetImpl(attCount);
for (int i = 0; i < validAtts.length; i++) {
if (!validAtts[i]) continue;
String namespace = null;
String attName = atts.getName(i);
int idx = attName.indexOf(':');
if (idx > 0) {
String prefix = attName.substring(0, idx);
if (!prefix.equals(XML_PREFIX)) {
attName = attName.substring(idx+1);
namespace = _namespaces.getNamespaceURI(prefix);
if (namespace == null) {
String error = "The namespace associated with "+
"the prefix '" + prefix +
"' could not be resolved.";
throw new SAXException(error);
}
}
}
attSet.setAttribute(attName, atts.getValue(i), namespace);
}
}
else attSet = new AttributeSetImpl(0);
return attSet;
} //-- method: processAttributeList
/**
* Saves local namespace declarations to the object
* model if necessary.
*
* @param classDesc the current ClassDescriptor.
**/
private void processNamespaces(XMLClassDescriptor classDesc) {
if (classDesc == null) return;
//-- process namespace nodes
XMLFieldDescriptor nsDescriptor =
classDesc.getFieldDescriptor(null, null, NodeType.Namespace);
if (nsDescriptor != null) {
UnmarshalState state = (UnmarshalState) _stateInfo.peek();
FieldHandler handler = nsDescriptor.getHandler();
if (handler != null) {
Enumeration enumeration = _namespaces.getLocalNamespacePrefixes();
while (enumeration.hasMoreElements()) {
String nsPrefix = (String)enumeration.nextElement();
if (nsPrefix == null) nsPrefix = "";
String nsURI = _namespaces.getNamespaceURI(nsPrefix);
if (nsURI == null) nsURI = "";
MapItem mapItem = new MapItem(nsPrefix, nsURI);
handler.setValue(state.object, mapItem);
}
}
}
} //-- processNamespaces
/**
* Extracts the prefix and resolves it to it's associated namespace.
* If the prefix is 'xml', then no resolution will occur, however
* in all other cases the resolution will change the prefix:value
* as {NamespaceURI}value
*
* @param value the QName to resolve.
*/
private Object resolveNamespace(Object value)
throws SAXException
{
if ( (value == null) || !(value instanceof String))
return value;
String result = (String)value;
int idx = result.indexOf(':');
String prefix = null;
if (idx > 0) {
prefix = result.substring(0,idx);
if (XML_PREFIX.equals(prefix)) {
//-- Do NOT Resolve the 'xml' prefix.
return value;
}
result = result.substring(idx+1);
}
String namespace = _namespaces.getNamespaceURI(prefix);
if ((namespace != null) && (namespace.length() > 0)) {
result = '{'+namespace+'}'+result;
return result;
}
else if ((namespace == null) && (prefix!=null))
throw new SAXException("The namespace associated with the prefix: '" +
prefix + "' is null.");
else
return result;
}
/**
* Sends a message to all observers. Currently the only observer is
* the logger.
* @param msg the message to send to all message observers
**/
private void message(String msg) {
if (_logWriter != null) {
_logWriter.println(msg);
_logWriter.flush();
}
} //-- message
/**
* Finds and returns an XMLClassDescriptor for the given class name.
* If a ClassDescriptor could not be found one will attempt to
* be generated.
* @param className the name of the class to find the descriptor for
**/
private XMLClassDescriptor getClassDescriptor (String className)
throws SAXException
{
Class type = null;
try {
//-- use specified ClassLoader if necessary
if (_loader != null) {
type = _loader.loadClass(className);
}
//-- no loader available use Class.forName
else type = Class.forName(className);
}
catch (ClassNotFoundException cnfe) {
return null;
}
return getClassDescriptor(type);
} //-- getClassDescriptor
/**
* Finds and returns an XMLClassDescriptor for the given class. If
* a ClassDescriptor could not be found one will attempt to
* be generated.
* @param _class the Class to get the ClassDescriptor for
**/
private XMLClassDescriptor getClassDescriptor(Class _class)
throws SAXException
{
if (_class == null) return null;
//-- special case for strings
if (_class == String.class)
return _stringDescriptor;
if (_class.isArray()) return null;
if (isPrimitive(_class)) return null;
if (_cdResolver == null)
_cdResolver = new ClassDescriptorResolverImpl();
XMLClassDescriptor classDesc = null;
try {
classDesc = _cdResolver.resolve(_class);
}
catch(ResolverException rx) {
// TODO
}
if (classDesc != null) {
return new InternalXMLClassDescriptor(classDesc);
}
if (debug) {
message(ERROR_DID_NOT_FIND_CLASSDESCRIPTOR + _class.getName());
}
return classDesc;
} //-- getClassDescriptor
/**
* Finds and returns a ClassDescriptor for the given class. If
* a ClassDescriptor could not be found one will attempt to
* be generated.
* @param className the name of the class to get the Descriptor for
**/
private XMLClassDescriptor getClassDescriptor
(String className, ClassLoader loader)
throws SAXException
{
if (_cdResolver == null)
_cdResolver = new ClassDescriptorResolverImpl();
XMLClassDescriptor classDesc = null;
try {
classDesc = _cdResolver.resolve(className, loader);
}
catch(ResolverException rx) {
throw new SAXException(rx);
}
if (classDesc != null) {
return new InternalXMLClassDescriptor(classDesc);
}
if (debug) {
message(ERROR_DID_NOT_FIND_CLASSDESCRIPTOR + className);
}
return classDesc;
} //-- getClassDescriptor
/**
* Returns the XMLClassLoader
*/
private XMLClassDescriptor resolveByXMLName
(String name, String namespace, ClassLoader loader)
throws SAXException
{
try {
return _cdResolver.resolveByXMLName(name, namespace, loader);
}
catch(ResolverException rx) {
throw new SAXException(rx);
}
}
/**
* Returns the package for the given Class
*
* @param type the Class to return the package of
* @return the package for the given Class
**/
private String getJavaPackage(Class type)
{
if (type == null)
return null;
String pkg = (String)_javaPackages.get(type);
if(pkg == null)
{
pkg = type.getName();
int idx = pkg.lastIndexOf('.');
if (idx > 0)
pkg = pkg.substring(0,idx);
else
pkg = "";
_javaPackages.put(type, pkg);
}
return pkg;
} //-- getJavaPackage
/**
* Returns the name of a class, handles array types
* @return the name of a class, handles array types
**/
private String className(Class type) {
if (type.isArray()) {
return className(type.getComponentType()) + "[]";
}
return type.getName();
} //-- className
/**
* Checks the given StringBuffer to determine if it only
* contains whitespace.
*
* @param sb the StringBuffer to check
* @return true if the only whitespace characters were
* found in the given StringBuffer
**/
private static boolean isWhitespace(StringBuffer sb) {
for (int i = 0; i < sb.length(); i++) {
char ch = sb.charAt(i);
switch (ch) {
case ' ':
case '\n':
case '\t':
case '\r':
break;
default:
return false;
}
}
return true;
} //-- isWhitespace
/**
* Checks the given StringBuffer to determine if it only
* contains whitespace.
*
* @param sb the StringBuffer to check
* @return true if the only whitespace characters were
* found in the given StringBuffer
**/
private static boolean isWhitespace(char[] chars, int start, int length) {
for (int i = start; i < length; i++) {
char ch = chars[i];
switch (ch) {
case ' ':
case '\n':
case '\t':
case '\r':
break;
default:
return false;
}
}
return true;
} //-- isWhitespace
/**
* Loads and returns the class with the given class name using the
* given loader.
* @param className the name of the class to load
* @param loader the ClassLoader to use, this may be null.
**/
private Class loadClass(String className, ClassLoader loader)
throws ClassNotFoundException
{
Class c = null;
//-- use passed in loader
if ( loader != null )
return loader.loadClass(className);
//-- use internal loader
else if (_loader != null)
return _loader.loadClass(className);
//-- no loader available use Class.forName
return Class.forName(className);
} //-- loadClass
/**
* Resolves the current set of waiting references for the given Id
* @param id the id that references are waiting for
* @param value, the value of the resolved id
**/
private void resolveReferences(String id, Object value)
throws org.xml.sax.SAXException
{
if ((id == null) || (value == null)) return;
if (_resolveTable == null) return;
ReferenceInfo refInfo = (ReferenceInfo)_resolveTable.remove(id);
while (refInfo != null) {
try {
FieldHandler handler = refInfo.descriptor.getHandler();
if (handler != null)
handler.setValue(refInfo.target, value);
//-- special handling for MapItems
if (refInfo.target instanceof MapItem) {
resolveReferences(refInfo.target.toString(), refInfo.target);
}
}
catch(java.lang.IllegalStateException ise) {
String err = "Attempting to resolve an IDREF: " +
id + "resulted in the following error: " +
ise.toString();
throw new SAXException(err);
}
refInfo = refInfo.next;
}
} //-- resolveReferences
/**
* Converts a String to the given primitive object type
*
* @param type the class type of the primitive in which
* to convert the String to
* @param value the String to convert to a primitive
* @return the new primitive Object
*/
private Object toPrimitiveObject
(Class type, String value, XMLFieldDescriptor fieldDesc)
throws SAXException
{
try {
return toPrimitiveObject(type, value);
}
catch(Exception ex) {
String err = "The following error occured while trying to ";
err += "unmarshal field " + fieldDesc.getFieldName();
UnmarshalState state = (UnmarshalState)_stateInfo.peek();
if (state != null) {
if (state.object != null) {
err += " of class " + state.object.getClass().getName();
}
}
err += "\n";
err += ex.getMessage();
throw new SAXException(err);
}
} //-- toPrimitiveObject
/**
* Converts a String to the given primitive object type
*
* @param type the class type of the primitive in which
* to convert the String to
* @param value the String to convert to a primitive
* @return the new primitive Object
*/
public static Object toPrimitiveObject(Class type, String value) {
Object primitive = value;
if (value != null) {
//-- trim any numeric values
if ((type != Character.TYPE) && (type != Character.class))
value = value.trim();
}
boolean isNull = ((value == null) || (value.length() == 0));
//-- I tried to order these in the order in which
//-- (I think) types are used more frequently
// int
if ((type == Integer.TYPE) || (type == Integer.class)) {
if (isNull)
primitive = new Integer(0);
else
primitive = new Integer(value);
}
// boolean
else if ((type == Boolean.TYPE) || (type == Boolean.class)) {
if (isNull)
primitive = new Boolean(false);
else
primitive = (value.equals("1") ||
value.toLowerCase().equals("true"))
? Boolean.TRUE : Boolean.FALSE;
}
// double
else if ((type == Double.TYPE) || (type == Double.class)) {
if (isNull)
primitive = new Double(0.0);
else
primitive = new Double(value);
}
// long
else if ((type == Long.TYPE) || (type == Long.class)) {
if (isNull)
primitive = new Long(0);
else
primitive = new Long(value);
}
// char
else if ((type == Character.TYPE) || (type == Character.class)) {
if (!isNull)
primitive = new Character(value.charAt(0));
else
primitive = new Character('\0');
}
// short
else if ((type == Short.TYPE) || (type == Short.class)) {
if (isNull)
primitive = new Short((short)0);
else
primitive = new Short(value);
}
// float
else if ((type == Float.TYPE) || (type == Float.class)) {
if (isNull)
primitive = new Float(0);
else
primitive = new Float(value);
}
// byte
else if ((type == Byte.TYPE) || (type == Byte.class)) {
if (isNull)
primitive = new Byte((byte)0);
else
primitive = new Byte(value);
}
//BigDecimal
else if (type == java.math.BigDecimal.class) {
if (isNull)
primitive = new java.math.BigDecimal(0);
else primitive = new java.math.BigDecimal(value);
}
//BigInteger
else if (type == java.math.BigInteger.class) {
if (isNull)
primitive = java.math.BigInteger.valueOf(0);
else primitive = new java.math.BigInteger(value);
}
return primitive;
} //-- toPrimitiveObject
/**
* A utility class for keeping track of the
* qName and how the SAX parser passed attributes
*/
class ElementInfo {
String qName = null;
Attributes attributes = null;
AttributeList attributeList = null;
ElementInfo() {
super();
}
ElementInfo(String qName, Attributes atts) {
super();
this.qName = qName;
this.attributes = atts;
}
ElementInfo(String qName, AttributeList atts) {
super();
this.qName = qName;
this.attributeList = atts;
}
void clear() {
qName = null;
attributes = null;
attributeList = null;
}
} //-- ElementInfo
/**
* Local IDResolver
**/
class IDResolverImpl implements IDResolver {
private Hashtable _idReferences = null;
private IDResolver _idResolver = null;
IDResolverImpl() {
} //-- IDResolverImpl
void bind(String id, Object obj) {
if (_idReferences == null)
_idReferences = new Hashtable();
_idReferences.put(id, obj);
} //-- bind
/**
* Returns the Object whose id matches the given IDREF,
* or null if no Object was found.
* @param idref the IDREF to resolve.
* @return the Object whose id matches the given IDREF.
**/
public Object resolve(String idref) {
if (_idReferences != null) {
Object obj = _idReferences.get(idref);
if (obj != null) return obj;
}
if (_idResolver != null) {
return _idResolver.resolve(idref);
}
return null;
} //-- resolve
void setResolver(IDResolver idResolver) {
_idResolver = idResolver;
}
} //-- IDResolverImpl
/**
* Internal class used to save state for reference resolving
**/
class ReferenceInfo {
String id = null;
Object target = null;
XMLFieldDescriptor descriptor = null;
ReferenceInfo next = null;
public ReferenceInfo() {
super();
}
public ReferenceInfo
(String id, Object target, XMLFieldDescriptor descriptor)
{
this.id = id;
this.target = target;
this.descriptor = descriptor;
}
}
/**
* Internal class used for passing constructor argument
* information
*/
class Arguments {
Object[] values = null;
Class[] types = null;
public int size() {
if (values == null) return 0;
return values.length;
}
} //-- Arguments
/**
* A class for handling Arrays during unmarshalling.
*
* @author <a href="mailto:[email protected]">[email protected]</a>
*/
public static class ArrayHandler {
Class _componentType = null;
ArrayList _items = null;
/**
* Creates a new ArrayHandler
*
* @param componentType the ComponentType for the array.
*/
ArrayHandler(Class componentType) {
if (componentType == null) {
String err = "The argument 'componentType' may not be null.";
throw new IllegalArgumentException(err);
}
_componentType = componentType;
_items = new ArrayList();
} //-- ArrayHandler
/**
* Adds the given object to the underlying array
*
*/
public void addObject(Object obj) {
if (obj == null) return;
/* disable check for now until we write a
small function to handle primitive and their
associated wrapper classes
if (!_componentType.isAssignableFrom(obj.getClass())) {
String err = obj.getClass().getName() + " is not an instanceof " +
_componentType.getName();
throw new IllegalArgumentException(err);
}
*/
_items.add(obj);
}
public Object getObject() {
int size = _items.size();
Object array = Array.newInstance(_componentType, size);
for (int i = 0; i < size; i++)
Array.set(array, i, _items.get(i));
return array;
}
public Class componentType() {
return _componentType;
}
} //-- ArrayHandler
} //-- Unmarshaller
| true | true | private void startElement
(String name, String namespace, AttributeSet atts)
throws SAXException
{
UnmarshalState state = null;
String xmlSpace = null;
//-- handle special atts
if (atts != null) {
//-- xml:space
xmlSpace = atts.getValue(XML_SPACE, Namespaces.XML_NAMESPACE);
if (xmlSpace == null) {
xmlSpace = atts.getValue(XML_SPACE_WITH_PREFIX, "");
}
}
if (_stateInfo.empty()) {
//-- Initialize since this is the first element
if (_topClass == null) {
if (_topObject != null) {
_topClass = _topObject.getClass();
}
}
if (_cdResolver == null) {
if (_topClass == null) {
String err = "The class for the root element '" +
name + "' could not be found.";
throw new SAXException(err);
}
_cdResolver = new ClassDescriptorResolverImpl(_loader);
}
_topState = getState();
_topState.elementName = name;
_topState.wsPreserve = (xmlSpace != null) ? PRESERVE.equals(xmlSpace) : _wsPreserve;
XMLClassDescriptor classDesc = null;
//-- If _topClass is null, then we need to search
//-- the resolver for one
String instanceClassname = null;
if (_topClass == null) {
//-- check for xsi:type
instanceClassname = getInstanceType(atts, null);
if (instanceClassname != null) {
//-- first try loading class directly
try {
_topClass = loadClass(instanceClassname, null);
}
catch(ClassNotFoundException cnfe) {}
if (_topClass == null) {
classDesc = getClassDescriptor(instanceClassname);
if (classDesc != null) {
_topClass = classDesc.getJavaClass();
}
if (_topClass == null) {
throw new SAXException("Class not found: " +
instanceClassname);
}
}
}
else {
classDesc = resolveByXMLName(name, namespace, null);
if (classDesc == null) {
classDesc = getClassDescriptor(name, _loader);
if (classDesc == null) {
classDesc = getClassDescriptor(JavaNaming.toJavaClassName(name));
}
}
if (classDesc != null) {
_topClass = classDesc.getJavaClass();
}
}
if (_topClass == null) {
String err = "The class for the root element '" +
name + "' could not be found.";
throw new SAXException(err);
}
}
//-- create a "fake" FieldDescriptor for the root element
XMLFieldDescriptorImpl fieldDesc
= new XMLFieldDescriptorImpl(_topClass,
name,
name,
NodeType.Element);
_topState.fieldDesc = fieldDesc;
//-- look for XMLClassDescriptor if null
//-- always check resolver first
if (classDesc == null)
classDesc = getClassDescriptor(_topClass);
//-- check for top-level primitives
if (classDesc == null) {
if (isPrimitive(_topClass)) {
classDesc = new PrimitivesClassDescriptor(_topClass);
fieldDesc.setIncremental(false);
_topState.primitiveOrImmutable = true;
}
}
fieldDesc.setClassDescriptor(classDesc);
if (classDesc == null) {
//-- report error
if ((!isPrimitive(_topClass)) &&
(!Serializable.class.isAssignableFrom( _topClass )))
throw new SAXException(MarshalException.NON_SERIALIZABLE_ERR);
String err = "unable to create XMLClassDescriptor " +
"for class: " + _topClass.getName();
throw new SAXException(err);
}
_topState.classDesc = classDesc;
_topState.type = _topClass;
if ((_topObject == null) && (!_topState.primitiveOrImmutable)) {
// Retrieving the xsi:type attribute, if present
String topPackage = getJavaPackage(_topClass);
if (instanceClassname == null)
instanceClassname = getInstanceType(atts, topPackage);
else {
//-- instance type already processed above, reset
//-- to null to prevent entering next block
instanceClassname = null;
}
if (instanceClassname != null) {
Class instanceClass = null;
Object instance = null;
try {
XMLClassDescriptor xcd =
getClassDescriptor(instanceClassname);
boolean loadClass = true;
if (xcd != null) {
instanceClass = xcd.getJavaClass();
if (instanceClass != null) {
loadClass = (!instanceClassname.equals(instanceClass.getName()));
}
}
if (loadClass) {
try {
instanceClass = loadClass(instanceClassname, null);
}
catch(ClassNotFoundException cnfe) {
//-- revert back to ClassDescriptor's associated
//-- class
if (xcd != null)
instanceClass = xcd.getJavaClass();
}
}
if (instanceClass == null) {
throw new SAXException("Class not found: " +
instanceClassname);
}
if (!_topClass.isAssignableFrom(instanceClass)) {
String err = instanceClass + " is not a subclass of "
+ _topClass;
throw new SAXException(err);
}
}
catch(Exception ex) {
String msg = "unable to instantiate " +
instanceClassname + "; ";
throw new SAXException(msg + ex);
}
//-- try to create instance of the given Class
Arguments args = processConstructorArgs(atts, classDesc);
_topState.object = createInstance(instanceClass, args);
}
//-- no xsi type information present
else {
//-- try to create instance of the given Class
Arguments args = processConstructorArgs(atts, classDesc);
_topState.object = createInstance(_topClass, args);
}
}
//-- otherwise use _topObject
else {
_topState.object = _topObject;
}
_stateInfo.push(_topState);
if (!_topState.primitiveOrImmutable) {
//--The top object has just been initialized
//--notify the listener
if ( _unmarshalListener != null )
_unmarshalListener.initialized(_topState.object);
processAttributes(atts, classDesc);
if ( _unmarshalListener != null )
_unmarshalListener.attributesProcessed(_topState.object);
processNamespaces(classDesc);
}
String pkg = getJavaPackage(_topClass);
if (getMappedPackage(namespace) == null)
{
addNamespaceToPackageMapping(namespace, pkg);
}
return;
} //--rootElement
//-- get MarshalDescriptor for the given element
UnmarshalState parentState = (UnmarshalState)_stateInfo.peek();
//Test if we can accept the field in the parentState
//in case the parentState fieldDesc is a container
//-- This following logic tests to see if we are in a
//-- container and we need to close out the container
//-- before proceeding:
boolean canAccept = false;
while ((parentState.fieldDesc != null) &&
(parentState.fieldDesc.isContainer() && !canAccept) )
{
XMLClassDescriptor tempClassDesc = parentState.classDesc;
//-- Find ClassDescriptor for Parent
if (tempClassDesc == null) {
tempClassDesc = (XMLClassDescriptor)parentState.fieldDesc.getClassDescriptor();
if (tempClassDesc == null)
tempClassDesc = getClassDescriptor(parentState.object.getClass());
}
canAccept = tempClassDesc.canAccept(name, namespace, parentState.object);
if (!canAccept) {
//-- Does container class even handle this field?
if (tempClassDesc.getFieldDescriptor(name, namespace, NodeType.Element) != null) {
if (!parentState.fieldDesc.isMultivalued()) {
String error = "The container object (" + tempClassDesc.getJavaClass().getName();
error += ") cannot accept the child object associated with the element '" + name + "'";
error += " because the container is already full!";
ValidationException vx = new ValidationException(error);
throw new SAXException(vx);
}
}
endElement(parentState.elementName);
parentState = (UnmarshalState)_stateInfo.peek();
}
tempClassDesc = null;
}
//-- create new state object
state = getState();
state.elementName = name;
state.parent = parentState;
if (xmlSpace != null)
state.wsPreserve = PRESERVE.equals(xmlSpace);
else
state.wsPreserve = parentState.wsPreserve;
_stateInfo.push(state);
//-- make sure we should proceed
if (parentState.object == null) {
if (!parentState.wrapper) return;
}
Class _class = null;
//-- Find ClassDescriptor for Parent
XMLClassDescriptor classDesc = parentState.classDesc;
if (classDesc == null) {
classDesc = (XMLClassDescriptor)parentState.fieldDesc.getClassDescriptor();
if (classDesc == null)
classDesc = getClassDescriptor(parentState.object.getClass());
}
//----------------------------------------------------/
//- Find FieldDescriptor associated with the element -/
//----------------------------------------------------/
//-- A reference to the FieldDescriptor associated
//-- the the "current" element
XMLFieldDescriptor descriptor = null;
//-- inherited class descriptor
//-- (only needed if descriptor cannot be found directly)
XMLClassDescriptor cdInherited = null;
//-- loop through stack and find correct descriptor
//int pIdx = _stateInfo.size() - 2; //-- index of parentState
UnmarshalState targetState = parentState;
String path = "";
StringBuffer pathBuf = null;
int count = 0;
boolean isWrapper = false;
XMLClassDescriptor oldClassDesc = classDesc;
while (descriptor == null) {
//-- NOTE (kv 20050228):
//-- we need to clean this code up, I made this
//-- fix to make sure the correct descriptor which
//-- matches the location path is used
if (path.length() > 0) {
String tmpName = path + "/" + name;
descriptor = classDesc.getFieldDescriptor(tmpName, namespace, NodeType.Element);
}
//-- End Patch
if (descriptor == null) {
descriptor = classDesc.getFieldDescriptor(name, namespace, NodeType.Element);
}
//-- Namespace patch, should be moved to XMLClassDescriptor, but
//-- this is the least intrusive patch at the moment. kv - 20030423
if ((descriptor != null) && (!descriptor.isContainer())) {
if ((namespace != null) && (namespace.length() > 0)) {
if (!namespaceEquals(namespace, descriptor.getNameSpaceURI())) {
//-- if descriptor namespace is not null, then we must
//-- have a namespace match, so set descriptor to null,
//-- or if descriptor is not a wildcard we can also
//-- set to null.
if ((descriptor.getNameSpaceURI() != null) || (!descriptor.matches("*"))) {
descriptor = null;
}
}
}
}
//-- end namespace patch
/*
If descriptor is null, we need to handle possible inheritence,
which might not be described in the current ClassDescriptor.
This can be a slow process...for speed use the match attribute
of the xml element in the mapping file. This logic might
not be completely necessary, and perhaps we should remove it.
*/
// handle multiple level locations (where count > 0) (CASTOR-1039)
// if ((descriptor == null) && (count == 0) && (!targetState.wrapper)) {
if ((descriptor == null) && (!targetState.wrapper)) {
MarshalFramework.InheritanceMatch[] matches = null;
try {
matches = searchInheritance(name, namespace, classDesc, _cdResolver);
}
catch(MarshalException rx) {
//-- TODO:
}
if (matches.length != 0) {
InheritanceMatch match = matches[0];
descriptor = match.parentFieldDesc;
cdInherited = match.inheritedClassDesc;
break; //-- found
}
/* */
// handle multiple level locations (where count > 0) (CASTOR-1039)
// isWrapper = (isWrapper || hasFieldsAtLocation(name, classDesc));
String tmpLocation = name;
if (count > 0) { tmpLocation = path + "/" + name; }
isWrapper = (isWrapper || hasFieldsAtLocation(tmpLocation, classDesc));
}
else if (descriptor != null) {
String tmpPath = descriptor.getLocationPath();
if (tmpPath == null) tmpPath = "";
if (path.equals(tmpPath))break; //-- found
descriptor = null; //-- not found, try again
}
else {
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(path);
pathBuf.append('/');
pathBuf.append(name);
isWrapper = (isWrapper || hasFieldsAtLocation(pathBuf.toString(), classDesc));
}
//-- Make sure there are more parent classes on stack
//-- otherwise break, since there is nothing to do
//if (pIdx == 0) break;
if (targetState == _topState) break;
//-- adjust name and try parent
if (count == 0)
path = targetState.elementName;
else {
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(targetState.elementName);
pathBuf.append('/');
pathBuf.append(path);
path = pathBuf.toString();
}
//-- get
//--pIdx;
//targetState = (UnmarshalState)_stateInfo.elementAt(pIdx);
targetState = targetState.parent;
classDesc = targetState.classDesc;
count++;
}
//-- The field descriptor is still null, we face a problem
if (descriptor == null) {
//-- reset classDesc
classDesc = oldClassDesc;
//-- isWrapper?
if (isWrapper) {
state.classDesc = new XMLClassDescriptorImpl(ContainerElement.class, name);
state.wrapper = true;
if (debug) {
message("wrapper-element: " + name);
}
//-- process attributes
processWrapperAttributes(atts);
return;
}
String mesg = "unable to find FieldDescriptor for '" + name;
mesg += "' in ClassDescriptor of " + classDesc.getXMLName();
//-- unwrap classDesc, if necessary, for the check
//-- Introspector.introspected done below
if (classDesc instanceof InternalXMLClassDescriptor) {
classDesc = ((InternalXMLClassDescriptor)classDesc).getClassDescriptor();
}
//-- If we are skipping elements that have appeared in the XML but for
//-- which we have no mapping, increase the ignore depth counter and return
if (! _strictElements) {
++_ignoreElementDepth;
//-- remove the StateInfo we just added
_stateInfo.pop();
if (debug) {
message(mesg + " - ignoring extra element.");
}
return;
}
//if we have no field descriptor and
//the class descriptor was introspected
//just log it
else if (Introspector.introspected(classDesc)) {
//if (warn)
message(mesg);
return;
}
//-- otherwise report error since we cannot find a suitable
//-- descriptor
else {
throw new SAXException(mesg);
}
} //-- end null descriptor
/// DEBUG: System.out.println("path: " + path);
//-- Save targetState (used in endElement)
if (targetState != parentState) {
state.targetState = targetState;
parentState = targetState; //-- reassign
}
Object object = parentState.object;
//--container support
if (descriptor.isContainer()) {
//create a new state to set the container as the object
//don't save the current state, it will be recreated later
if (debug) {
message("#container: " + descriptor.getFieldName());
}
//-- clear current state and re-use for the container
state.clear();
//-- inherit whitespace preserving from the parentState
state.wsPreserve = parentState.wsPreserve;
state.parent = parentState;
//here we can hard-code a name or take the field name
state.elementName = descriptor.getFieldName();
state.fieldDesc = descriptor;
state.classDesc = (XMLClassDescriptor)descriptor.getClassDescriptor();
Object containerObject = null;
//1-- the container is not multivalued (not a collection)
if (!descriptor.isMultivalued()) {
// Check if the container object has already been instantiated
FieldHandler handler = descriptor.getHandler();
containerObject = handler.getValue(object);
if (containerObject != null){
if (state.classDesc != null) {
if (state.classDesc.canAccept(name, namespace, containerObject)) {
//remove the descriptor from the used list
parentState.markAsNotUsed(descriptor);
}
}
else {
//remove the descriptor from the used list
parentState.markAsNotUsed(descriptor);
}
}
else {
containerObject = handler.newInstance(object);
}
}
//2-- the container is multivalued
else {
Class containerClass = descriptor.getFieldType();
try {
containerObject = containerClass.newInstance();
}
catch(Exception ex) {
throw new SAXException(ex);
}
}
state.object = containerObject;
state.type = containerObject.getClass();
//we need to recall startElement()
//so that we can find a more appropriate descriptor in for the given name
_namespaces = _namespaces.createNamespaces();
startElement(name, namespace, atts);
return;
}
//--End of the container support
//-- Find object type and create new Object of that type
state.fieldDesc = descriptor;
/* <update>
* we need to add this code back in, to make sure
* we have proper access rights.
*
if (!descriptor.getAccessRights().isWritable()) {
if (debug) {
buf.setLength(0);
buf.append("The field for element '");
buf.append(name);
buf.append("' is read-only.");
message(buf.toString());
}
return;
}
*/
//-- Find class to instantiate
//-- check xml names to see if we should look for a more specific
//-- ClassDescriptor, otherwise just use the one found in the
//-- descriptor
classDesc = null;
if (cdInherited != null) classDesc = cdInherited;
else if (!name.equals(descriptor.getXMLName()))
classDesc = resolveByXMLName(name, namespace, null);
if (classDesc == null)
classDesc = (XMLClassDescriptor)descriptor.getClassDescriptor();
FieldHandler handler = descriptor.getHandler();
boolean useHandler = true;
try {
//-- Get Class type...first use ClassDescriptor,
//-- since it could be more specific than
//-- the FieldDescriptor
if (classDesc != null) {
_class = classDesc.getJavaClass();
//-- XXXX This is a hack I know...but we
//-- XXXX can't use the handler if the field
//-- XXXX types are different
if (descriptor.getFieldType() != _class) {
state.derived = true;
}
}
else {
_class = descriptor.getFieldType();
}
//-- This *shouldn't* happen, but a custom implementation
//-- could return null in the XMLClassDesctiptor#getJavaClass
//-- or XMLFieldDescriptor#getFieldType. If so, just replace
//-- with java.lang.Object.class (basically "anyType").
if (_class == null) {
_class = java.lang.Object.class;
}
// Retrieving the xsi:type attribute, if present
String currentPackage = getJavaPackage(parentState.type);
String instanceType = getInstanceType(atts, currentPackage);
if (instanceType != null) {
Class instanceClass = null;
try {
XMLClassDescriptor instanceDesc
= getClassDescriptor(instanceType, _loader);
boolean loadClass = true;
if (instanceDesc != null) {
instanceClass = instanceDesc.getJavaClass();
classDesc = instanceDesc;
if (instanceClass != null) {
loadClass = (!instanceClass.getName().equals(instanceType));
}
}
if (loadClass) {
instanceClass = loadClass(instanceType, null);
//the FieldHandler can be either an XMLFieldHandler
//or a FieldHandlerImpl
FieldHandler tempHandler = descriptor.getHandler();
boolean collection = false;
if (tempHandler instanceof FieldHandlerImpl) {
collection = ((FieldHandlerImpl)tempHandler).isCollection();
}
else {
collection = Introspector.isCollection(instanceClass);
}
if ( (! collection ) &&
! _class.isAssignableFrom(instanceClass))
{
if (!isPrimitive(_class)) {
String err = instanceClass.getName()
+ " is not a subclass of " + _class.getName();
throw new SAXException(err);
}
}
}
_class = instanceClass;
useHandler = false;
}
catch(Exception ex) {
String msg = "unable to instantiate " + instanceType;
throw new SAXException(msg + "; " + ex);
}
}
//-- Handle ArrayHandler
if (_class == Object.class) {
if (parentState.object instanceof ArrayHandler)
_class = ((ArrayHandler)parentState.object).componentType();
}
//-- Handle support for "Any" type
if (_class == Object.class) {
Class pClass = parentState.type;
ClassLoader loader = pClass.getClassLoader();
//-- first look for a descriptor based
//-- on the XML name
classDesc = resolveByXMLName(name, namespace, loader);
//-- if null, create classname, and try resolving
String cname = null;
if (classDesc == null) {
//-- create class name
cname = JavaNaming.toJavaClassName(name);
classDesc = getClassDescriptor(cname, loader);
}
//-- if still null, try using parents package
if (classDesc == null) {
//-- use parent to get package information
String pkg = pClass.getName();
int idx = pkg.lastIndexOf('.');
if (idx > 0) {
pkg = pkg.substring(0,idx+1);
cname = pkg + cname;
classDesc = getClassDescriptor(cname, loader);
}
}
if (classDesc != null) {
_class = classDesc.getJavaClass();
useHandler = false;
}
else {
//we are dealing with an AnyNode
//1- creates a new SAX2ANY handler
_anyUnmarshaller = new SAX2ANY(_namespaces);
//2- delegates the element handling
if (_elemInfo.attributeList != null) {
//-- SAX 1
_anyUnmarshaller.startElement(_elemInfo.qName,
_elemInfo.attributeList);
}
else {
//-- SAX 2
_anyUnmarshaller.startElement(namespace, name, _elemInfo.qName,
_elemInfo.attributes);
}
//first element so depth can only be one at this point
_depth = 1;
state.object = _anyUnmarshaller.getStartingNode();
state.type = _class;
//don't need to continue
return;
}
}
boolean byteArray = false;
if (_class.isArray())
byteArray = (_class.getComponentType() == Byte.TYPE);
//-- check for immutable
if (isPrimitive(_class) ||
descriptor.isImmutable() ||
byteArray)
{
state.object = null;
state.primitiveOrImmutable = true;
//-- handle immutable types, such as java.util.Locale
if (descriptor.isImmutable()) {
if (classDesc == null)
classDesc = getClassDescriptor(_class);
state.classDesc = classDesc;
Arguments args = processConstructorArgs(atts, classDesc);
if ((args != null) && (args.size() > 0)) {
state.args = args;
}
}
}
else {
if (classDesc == null)
classDesc = getClassDescriptor(_class);
//-- XXXX should remove this test once we can
//-- XXXX come up with a better solution
if ((!state.derived) && useHandler) {
boolean create = true;
if (_reuseObjects) {
state.object = handler.getValue(parentState.object);
create = (state.object == null);
}
if (create) {
Arguments args = processConstructorArgs(atts, classDesc);
if ((args.values != null) && (args.values.length > 0)) {
if (handler instanceof ExtendedFieldHandler) {
ExtendedFieldHandler efh =
(ExtendedFieldHandler)handler;
state.object = efh.newInstance(parentState.object, args.values);
}
else {
String err = "constructor arguments can only be " +
"used with an ExtendedFieldHandler.";
throw new SAXException(err);
}
}
else {
state.object = handler.newInstance(parentState.object);
}
}
}
//-- reassign class in case there is a conflict
//-- between descriptor#getFieldType and
//-- handler#newInstance...I should hope not, but
//-- who knows
if (state.object != null) {
_class = state.object.getClass();
if (classDesc != null) {
if (classDesc.getJavaClass() != _class) {
classDesc = null;
}
}
}
else {
try {
if (_class.isArray()) {
state.object = new ArrayHandler(_class.getComponentType());
_class = ArrayHandler.class;
}
else {
Arguments args = processConstructorArgs(atts, classDesc);
state.object = createInstance(_class, args);
//state.object = _class.newInstance();
}
}
catch(java.lang.Exception ex) {
String err = "unable to instantiate a new type of: ";
err += className(_class);
err += "; " + ex.getMessage();
//storing causal exception using SAX non-standard method...
SAXException sx = new SAXException(err, ex);
//...and also using Java 1.4 method
sx.initCause(ex);
throw sx;
}
}
}
state.type = _class;
}
catch (java.lang.IllegalStateException ise) {
message(ise.toString());
throw new SAXException(ise);
}
//-- At this point we should have a new object, unless
//-- we are dealing with a primitive type, or a special
//-- case such as byte[]
if (classDesc == null) {
classDesc = getClassDescriptor(_class);
}
state.classDesc = classDesc;
if ((state.object == null) && (!state.primitiveOrImmutable))
{
String err = "unable to unmarshal: " + name + "\n";
err += " - unable to instantiate: " + className(_class);
throw new SAXException(err);
}
//-- assign object, if incremental
if (descriptor.isIncremental()) {
if (debug) {
message("debug: Processing incrementally for element: " + name);
}
try {
handler.setValue(parentState.object, state.object);
}
catch(java.lang.IllegalStateException ise) {
String err = "unable to add \"" + name + "\" to ";
err += parentState.fieldDesc.getXMLName();
err += " due to the following error: " + ise;
throw new SAXException(err);
}
}
if (state.object != null) {
//--The object has just been initialized
//--notify the listener
if ( _unmarshalListener != null )
_unmarshalListener.initialized(state.object);
processAttributes(atts, classDesc);
if ( _unmarshalListener != null )
_unmarshalListener.attributesProcessed(state.object);
processNamespaces(classDesc);
}
else if ((state.type != null) && (!state.primitiveOrImmutable)) {
if (atts != null) {
processWrapperAttributes(atts);
StringBuffer buffer = new StringBuffer();
buffer.append("The current object for element '");
buffer.append(name);
buffer.append("\' is null. Processing attributes as location");
buffer.append("/wrapper only and ignoring all other attribtes.");
message(buffer.toString());
}
}
else {
//-- check for special attributes, such as xsi:nil
if (atts != null) {
String nil = atts.getValue(NIL_ATTR, XSI_NAMESPACE);
state.nil = "true".equals(nil);
processWrapperAttributes(atts);
}
}
} //-- void startElement(String, AttributeList)
| private void startElement
(String name, String namespace, AttributeSet atts)
throws SAXException
{
UnmarshalState state = null;
String xmlSpace = null;
//-- handle special atts
if (atts != null) {
//-- xml:space
xmlSpace = atts.getValue(XML_SPACE, Namespaces.XML_NAMESPACE);
if (xmlSpace == null) {
xmlSpace = atts.getValue(XML_SPACE_WITH_PREFIX, "");
}
}
if (_stateInfo.empty()) {
//-- Initialize since this is the first element
if (_topClass == null) {
if (_topObject != null) {
_topClass = _topObject.getClass();
}
}
if (_cdResolver == null) {
if (_topClass == null) {
String err = "The class for the root element '" +
name + "' could not be found.";
throw new SAXException(err);
}
_cdResolver = new ClassDescriptorResolverImpl(_loader);
}
_topState = getState();
_topState.elementName = name;
_topState.wsPreserve = (xmlSpace != null) ? PRESERVE.equals(xmlSpace) : _wsPreserve;
XMLClassDescriptor classDesc = null;
//-- If _topClass is null, then we need to search
//-- the resolver for one
String instanceClassname = null;
if (_topClass == null) {
//-- check for xsi:type
instanceClassname = getInstanceType(atts, null);
if (instanceClassname != null) {
//-- first try loading class directly
try {
_topClass = loadClass(instanceClassname, null);
}
catch(ClassNotFoundException cnfe) {}
if (_topClass == null) {
classDesc = getClassDescriptor(instanceClassname);
if (classDesc != null) {
_topClass = classDesc.getJavaClass();
}
if (_topClass == null) {
throw new SAXException("Class not found: " +
instanceClassname);
}
}
}
else {
classDesc = resolveByXMLName(name, namespace, null);
if (classDesc == null) {
classDesc = getClassDescriptor(name, _loader);
if (classDesc == null) {
classDesc = getClassDescriptor(JavaNaming.toJavaClassName(name));
}
}
if (classDesc != null) {
_topClass = classDesc.getJavaClass();
}
}
if (_topClass == null) {
String err = "The class for the root element '" +
name + "' could not be found.";
throw new SAXException(err);
}
}
//-- create a "fake" FieldDescriptor for the root element
XMLFieldDescriptorImpl fieldDesc
= new XMLFieldDescriptorImpl(_topClass,
name,
name,
NodeType.Element);
_topState.fieldDesc = fieldDesc;
//-- look for XMLClassDescriptor if null
//-- always check resolver first
if (classDesc == null)
classDesc = getClassDescriptor(_topClass);
//-- check for top-level primitives
if (classDesc == null) {
if (isPrimitive(_topClass)) {
classDesc = new PrimitivesClassDescriptor(_topClass);
fieldDesc.setIncremental(false);
_topState.primitiveOrImmutable = true;
}
}
fieldDesc.setClassDescriptor(classDesc);
if (classDesc == null) {
//-- report error
if ((!isPrimitive(_topClass)) &&
(!Serializable.class.isAssignableFrom( _topClass )))
throw new SAXException(MarshalException.NON_SERIALIZABLE_ERR);
String err = "unable to create XMLClassDescriptor " +
"for class: " + _topClass.getName();
throw new SAXException(err);
}
_topState.classDesc = classDesc;
_topState.type = _topClass;
if ((_topObject == null) && (!_topState.primitiveOrImmutable)) {
// Retrieving the xsi:type attribute, if present
String topPackage = getJavaPackage(_topClass);
if (instanceClassname == null)
instanceClassname = getInstanceType(atts, topPackage);
else {
//-- instance type already processed above, reset
//-- to null to prevent entering next block
instanceClassname = null;
}
if (instanceClassname != null) {
Class instanceClass = null;
Object instance = null;
try {
XMLClassDescriptor xcd =
getClassDescriptor(instanceClassname);
boolean loadClass = true;
if (xcd != null) {
instanceClass = xcd.getJavaClass();
if (instanceClass != null) {
loadClass = (!instanceClassname.equals(instanceClass.getName()));
}
}
if (loadClass) {
try {
instanceClass = loadClass(instanceClassname, null);
}
catch(ClassNotFoundException cnfe) {
//-- revert back to ClassDescriptor's associated
//-- class
if (xcd != null)
instanceClass = xcd.getJavaClass();
}
}
if (instanceClass == null) {
throw new SAXException("Class not found: " +
instanceClassname);
}
if (!_topClass.isAssignableFrom(instanceClass)) {
String err = instanceClass + " is not a subclass of "
+ _topClass;
throw new SAXException(err);
}
}
catch(Exception ex) {
String msg = "unable to instantiate " +
instanceClassname + "; ";
throw new SAXException(msg + ex);
}
//-- try to create instance of the given Class
Arguments args = processConstructorArgs(atts, classDesc);
_topState.object = createInstance(instanceClass, args);
}
//-- no xsi type information present
else {
//-- try to create instance of the given Class
Arguments args = processConstructorArgs(atts, classDesc);
_topState.object = createInstance(_topClass, args);
}
}
//-- otherwise use _topObject
else {
_topState.object = _topObject;
}
_stateInfo.push(_topState);
if (!_topState.primitiveOrImmutable) {
//--The top object has just been initialized
//--notify the listener
if ( _unmarshalListener != null )
_unmarshalListener.initialized(_topState.object);
processAttributes(atts, classDesc);
if ( _unmarshalListener != null )
_unmarshalListener.attributesProcessed(_topState.object);
processNamespaces(classDesc);
}
String pkg = getJavaPackage(_topClass);
if (getMappedPackage(namespace) == null)
{
addNamespaceToPackageMapping(namespace, pkg);
}
return;
} //--rootElement
//-- get MarshalDescriptor for the given element
UnmarshalState parentState = (UnmarshalState)_stateInfo.peek();
//Test if we can accept the field in the parentState
//in case the parentState fieldDesc is a container
//-- This following logic tests to see if we are in a
//-- container and we need to close out the container
//-- before proceeding:
boolean canAccept = false;
while ((parentState.fieldDesc != null) &&
(parentState.fieldDesc.isContainer() && !canAccept) )
{
XMLClassDescriptor tempClassDesc = parentState.classDesc;
//-- Find ClassDescriptor for Parent
if (tempClassDesc == null) {
tempClassDesc = (XMLClassDescriptor)parentState.fieldDesc.getClassDescriptor();
if (tempClassDesc == null)
tempClassDesc = getClassDescriptor(parentState.object.getClass());
}
canAccept = tempClassDesc.canAccept(name, namespace, parentState.object);
if (!canAccept) {
//-- Does container class even handle this field?
if (tempClassDesc.getFieldDescriptor(name, namespace, NodeType.Element) != null) {
if (!parentState.fieldDesc.isMultivalued()) {
String error = "The container object (" + tempClassDesc.getJavaClass().getName();
error += ") cannot accept the child object associated with the element '" + name + "'";
error += " because the container is already full!";
ValidationException vx = new ValidationException(error);
throw new SAXException(vx);
}
}
endElement(parentState.elementName);
parentState = (UnmarshalState)_stateInfo.peek();
}
tempClassDesc = null;
}
//-- create new state object
state = getState();
state.elementName = name;
state.parent = parentState;
if (xmlSpace != null)
state.wsPreserve = PRESERVE.equals(xmlSpace);
else
state.wsPreserve = parentState.wsPreserve;
_stateInfo.push(state);
//-- make sure we should proceed
if (parentState.object == null) {
if (!parentState.wrapper) return;
}
Class _class = null;
//-- Find ClassDescriptor for Parent
XMLClassDescriptor classDesc = parentState.classDesc;
if (classDesc == null) {
classDesc = (XMLClassDescriptor)parentState.fieldDesc.getClassDescriptor();
if (classDesc == null)
classDesc = getClassDescriptor(parentState.object.getClass());
}
//----------------------------------------------------/
//- Find FieldDescriptor associated with the element -/
//----------------------------------------------------/
//-- A reference to the FieldDescriptor associated
//-- the the "current" element
XMLFieldDescriptor descriptor = null;
//-- inherited class descriptor
//-- (only needed if descriptor cannot be found directly)
XMLClassDescriptor cdInherited = null;
//-- loop through stack and find correct descriptor
//int pIdx = _stateInfo.size() - 2; //-- index of parentState
UnmarshalState targetState = parentState;
String path = "";
StringBuffer pathBuf = null;
int count = 0;
boolean isWrapper = false;
XMLClassDescriptor oldClassDesc = classDesc;
while (descriptor == null) {
//-- NOTE (kv 20050228):
//-- we need to clean this code up, I made this
//-- fix to make sure the correct descriptor which
//-- matches the location path is used
if (path.length() > 0) {
String tmpName = path + "/" + name;
descriptor = classDesc.getFieldDescriptor(tmpName, namespace, NodeType.Element);
}
//-- End Patch
if (descriptor == null) {
descriptor = classDesc.getFieldDescriptor(name, namespace, NodeType.Element);
}
//-- Namespace patch, should be moved to XMLClassDescriptor, but
//-- this is the least intrusive patch at the moment. kv - 20030423
if ((descriptor != null) && (!descriptor.isContainer())) {
if ((namespace != null) && (namespace.length() > 0)) {
if (!namespaceEquals(namespace, descriptor.getNameSpaceURI())) {
//-- if descriptor namespace is not null, then we must
//-- have a namespace match, so set descriptor to null,
//-- or if descriptor is not a wildcard we can also
//-- set to null.
if ((descriptor.getNameSpaceURI() != null) || (!descriptor.matches("*"))) {
descriptor = null;
}
}
}
}
//-- end namespace patch
/*
If descriptor is null, we need to handle possible inheritence,
which might not be described in the current ClassDescriptor.
This can be a slow process...for speed use the match attribute
of the xml element in the mapping file. This logic might
not be completely necessary, and perhaps we should remove it.
*/
// handle multiple level locations (where count > 0) (CASTOR-1039)
// if ((descriptor == null) && (count == 0) && (!targetState.wrapper)) {
if ((descriptor == null) && (!targetState.wrapper)) {
MarshalFramework.InheritanceMatch[] matches = null;
try {
matches = searchInheritance(name, namespace, classDesc, _cdResolver);
}
catch(MarshalException rx) {
//-- TODO:
}
if (matches.length != 0) {
InheritanceMatch match = null;
// It may be the case that this class descriptor can
// appear under multiple parent field descriptors. Look
// for the first match whose parent file descriptor XML
// name matches the name of the element we are under
for(int i = 0; i < matches.length; i++) {
if(parentState.elementName.equals(matches[i].parentFieldDesc.getLocationPath())) {
match = matches[i];
break;
}
}
if(match == null) match = matches[0];
descriptor = match.parentFieldDesc;
cdInherited = match.inheritedClassDesc;
break; //-- found
}
/* */
// handle multiple level locations (where count > 0) (CASTOR-1039)
// isWrapper = (isWrapper || hasFieldsAtLocation(name, classDesc));
String tmpLocation = name;
if (count > 0) { tmpLocation = path + "/" + name; }
isWrapper = (isWrapper || hasFieldsAtLocation(tmpLocation, classDesc));
}
else if (descriptor != null) {
String tmpPath = descriptor.getLocationPath();
if (tmpPath == null) tmpPath = "";
if (path.equals(tmpPath))break; //-- found
descriptor = null; //-- not found, try again
}
else {
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(path);
pathBuf.append('/');
pathBuf.append(name);
isWrapper = (isWrapper || hasFieldsAtLocation(pathBuf.toString(), classDesc));
}
//-- Make sure there are more parent classes on stack
//-- otherwise break, since there is nothing to do
//if (pIdx == 0) break;
if (targetState == _topState) break;
//-- adjust name and try parent
if (count == 0)
path = targetState.elementName;
else {
if (pathBuf == null)
pathBuf = new StringBuffer();
else
pathBuf.setLength(0);
pathBuf.append(targetState.elementName);
pathBuf.append('/');
pathBuf.append(path);
path = pathBuf.toString();
}
//-- get
//--pIdx;
//targetState = (UnmarshalState)_stateInfo.elementAt(pIdx);
targetState = targetState.parent;
classDesc = targetState.classDesc;
count++;
}
//-- The field descriptor is still null, we face a problem
if (descriptor == null) {
//-- reset classDesc
classDesc = oldClassDesc;
//-- isWrapper?
if (isWrapper) {
state.classDesc = new XMLClassDescriptorImpl(ContainerElement.class, name);
state.wrapper = true;
if (debug) {
message("wrapper-element: " + name);
}
//-- process attributes
processWrapperAttributes(atts);
return;
}
String mesg = "unable to find FieldDescriptor for '" + name;
mesg += "' in ClassDescriptor of " + classDesc.getXMLName();
//-- unwrap classDesc, if necessary, for the check
//-- Introspector.introspected done below
if (classDesc instanceof InternalXMLClassDescriptor) {
classDesc = ((InternalXMLClassDescriptor)classDesc).getClassDescriptor();
}
//-- If we are skipping elements that have appeared in the XML but for
//-- which we have no mapping, increase the ignore depth counter and return
if (! _strictElements) {
++_ignoreElementDepth;
//-- remove the StateInfo we just added
_stateInfo.pop();
if (debug) {
message(mesg + " - ignoring extra element.");
}
return;
}
//if we have no field descriptor and
//the class descriptor was introspected
//just log it
else if (Introspector.introspected(classDesc)) {
//if (warn)
message(mesg);
return;
}
//-- otherwise report error since we cannot find a suitable
//-- descriptor
else {
throw new SAXException(mesg);
}
} //-- end null descriptor
/// DEBUG: System.out.println("path: " + path);
//-- Save targetState (used in endElement)
if (targetState != parentState) {
state.targetState = targetState;
parentState = targetState; //-- reassign
}
Object object = parentState.object;
//--container support
if (descriptor.isContainer()) {
//create a new state to set the container as the object
//don't save the current state, it will be recreated later
if (debug) {
message("#container: " + descriptor.getFieldName());
}
//-- clear current state and re-use for the container
state.clear();
//-- inherit whitespace preserving from the parentState
state.wsPreserve = parentState.wsPreserve;
state.parent = parentState;
//here we can hard-code a name or take the field name
state.elementName = descriptor.getFieldName();
state.fieldDesc = descriptor;
state.classDesc = (XMLClassDescriptor)descriptor.getClassDescriptor();
Object containerObject = null;
//1-- the container is not multivalued (not a collection)
if (!descriptor.isMultivalued()) {
// Check if the container object has already been instantiated
FieldHandler handler = descriptor.getHandler();
containerObject = handler.getValue(object);
if (containerObject != null){
if (state.classDesc != null) {
if (state.classDesc.canAccept(name, namespace, containerObject)) {
//remove the descriptor from the used list
parentState.markAsNotUsed(descriptor);
}
}
else {
//remove the descriptor from the used list
parentState.markAsNotUsed(descriptor);
}
}
else {
containerObject = handler.newInstance(object);
}
}
//2-- the container is multivalued
else {
Class containerClass = descriptor.getFieldType();
try {
containerObject = containerClass.newInstance();
}
catch(Exception ex) {
throw new SAXException(ex);
}
}
state.object = containerObject;
state.type = containerObject.getClass();
//we need to recall startElement()
//so that we can find a more appropriate descriptor in for the given name
_namespaces = _namespaces.createNamespaces();
startElement(name, namespace, atts);
return;
}
//--End of the container support
//-- Find object type and create new Object of that type
state.fieldDesc = descriptor;
/* <update>
* we need to add this code back in, to make sure
* we have proper access rights.
*
if (!descriptor.getAccessRights().isWritable()) {
if (debug) {
buf.setLength(0);
buf.append("The field for element '");
buf.append(name);
buf.append("' is read-only.");
message(buf.toString());
}
return;
}
*/
//-- Find class to instantiate
//-- check xml names to see if we should look for a more specific
//-- ClassDescriptor, otherwise just use the one found in the
//-- descriptor
classDesc = null;
if (cdInherited != null) classDesc = cdInherited;
else if (!name.equals(descriptor.getXMLName()))
classDesc = resolveByXMLName(name, namespace, null);
if (classDesc == null)
classDesc = (XMLClassDescriptor)descriptor.getClassDescriptor();
FieldHandler handler = descriptor.getHandler();
boolean useHandler = true;
try {
//-- Get Class type...first use ClassDescriptor,
//-- since it could be more specific than
//-- the FieldDescriptor
if (classDesc != null) {
_class = classDesc.getJavaClass();
//-- XXXX This is a hack I know...but we
//-- XXXX can't use the handler if the field
//-- XXXX types are different
if (descriptor.getFieldType() != _class) {
state.derived = true;
}
}
else {
_class = descriptor.getFieldType();
}
//-- This *shouldn't* happen, but a custom implementation
//-- could return null in the XMLClassDesctiptor#getJavaClass
//-- or XMLFieldDescriptor#getFieldType. If so, just replace
//-- with java.lang.Object.class (basically "anyType").
if (_class == null) {
_class = java.lang.Object.class;
}
// Retrieving the xsi:type attribute, if present
String currentPackage = getJavaPackage(parentState.type);
String instanceType = getInstanceType(atts, currentPackage);
if (instanceType != null) {
Class instanceClass = null;
try {
XMLClassDescriptor instanceDesc
= getClassDescriptor(instanceType, _loader);
boolean loadClass = true;
if (instanceDesc != null) {
instanceClass = instanceDesc.getJavaClass();
classDesc = instanceDesc;
if (instanceClass != null) {
loadClass = (!instanceClass.getName().equals(instanceType));
}
}
if (loadClass) {
instanceClass = loadClass(instanceType, null);
//the FieldHandler can be either an XMLFieldHandler
//or a FieldHandlerImpl
FieldHandler tempHandler = descriptor.getHandler();
boolean collection = false;
if (tempHandler instanceof FieldHandlerImpl) {
collection = ((FieldHandlerImpl)tempHandler).isCollection();
}
else {
collection = Introspector.isCollection(instanceClass);
}
if ( (! collection ) &&
! _class.isAssignableFrom(instanceClass))
{
if (!isPrimitive(_class)) {
String err = instanceClass.getName()
+ " is not a subclass of " + _class.getName();
throw new SAXException(err);
}
}
}
_class = instanceClass;
useHandler = false;
}
catch(Exception ex) {
String msg = "unable to instantiate " + instanceType;
throw new SAXException(msg + "; " + ex);
}
}
//-- Handle ArrayHandler
if (_class == Object.class) {
if (parentState.object instanceof ArrayHandler)
_class = ((ArrayHandler)parentState.object).componentType();
}
//-- Handle support for "Any" type
if (_class == Object.class) {
Class pClass = parentState.type;
ClassLoader loader = pClass.getClassLoader();
//-- first look for a descriptor based
//-- on the XML name
classDesc = resolveByXMLName(name, namespace, loader);
//-- if null, create classname, and try resolving
String cname = null;
if (classDesc == null) {
//-- create class name
cname = JavaNaming.toJavaClassName(name);
classDesc = getClassDescriptor(cname, loader);
}
//-- if still null, try using parents package
if (classDesc == null) {
//-- use parent to get package information
String pkg = pClass.getName();
int idx = pkg.lastIndexOf('.');
if (idx > 0) {
pkg = pkg.substring(0,idx+1);
cname = pkg + cname;
classDesc = getClassDescriptor(cname, loader);
}
}
if (classDesc != null) {
_class = classDesc.getJavaClass();
useHandler = false;
}
else {
//we are dealing with an AnyNode
//1- creates a new SAX2ANY handler
_anyUnmarshaller = new SAX2ANY(_namespaces);
//2- delegates the element handling
if (_elemInfo.attributeList != null) {
//-- SAX 1
_anyUnmarshaller.startElement(_elemInfo.qName,
_elemInfo.attributeList);
}
else {
//-- SAX 2
_anyUnmarshaller.startElement(namespace, name, _elemInfo.qName,
_elemInfo.attributes);
}
//first element so depth can only be one at this point
_depth = 1;
state.object = _anyUnmarshaller.getStartingNode();
state.type = _class;
//don't need to continue
return;
}
}
boolean byteArray = false;
if (_class.isArray())
byteArray = (_class.getComponentType() == Byte.TYPE);
//-- check for immutable
if (isPrimitive(_class) ||
descriptor.isImmutable() ||
byteArray)
{
state.object = null;
state.primitiveOrImmutable = true;
//-- handle immutable types, such as java.util.Locale
if (descriptor.isImmutable()) {
if (classDesc == null)
classDesc = getClassDescriptor(_class);
state.classDesc = classDesc;
Arguments args = processConstructorArgs(atts, classDesc);
if ((args != null) && (args.size() > 0)) {
state.args = args;
}
}
}
else {
if (classDesc == null)
classDesc = getClassDescriptor(_class);
//-- XXXX should remove this test once we can
//-- XXXX come up with a better solution
if ((!state.derived) && useHandler) {
boolean create = true;
if (_reuseObjects) {
state.object = handler.getValue(parentState.object);
create = (state.object == null);
}
if (create) {
Arguments args = processConstructorArgs(atts, classDesc);
if ((args.values != null) && (args.values.length > 0)) {
if (handler instanceof ExtendedFieldHandler) {
ExtendedFieldHandler efh =
(ExtendedFieldHandler)handler;
state.object = efh.newInstance(parentState.object, args.values);
}
else {
String err = "constructor arguments can only be " +
"used with an ExtendedFieldHandler.";
throw new SAXException(err);
}
}
else {
state.object = handler.newInstance(parentState.object);
}
}
}
//-- reassign class in case there is a conflict
//-- between descriptor#getFieldType and
//-- handler#newInstance...I should hope not, but
//-- who knows
if (state.object != null) {
_class = state.object.getClass();
if (classDesc != null) {
if (classDesc.getJavaClass() != _class) {
classDesc = null;
}
}
}
else {
try {
if (_class.isArray()) {
state.object = new ArrayHandler(_class.getComponentType());
_class = ArrayHandler.class;
}
else {
Arguments args = processConstructorArgs(atts, classDesc);
state.object = createInstance(_class, args);
//state.object = _class.newInstance();
}
}
catch(java.lang.Exception ex) {
String err = "unable to instantiate a new type of: ";
err += className(_class);
err += "; " + ex.getMessage();
//storing causal exception using SAX non-standard method...
SAXException sx = new SAXException(err, ex);
//...and also using Java 1.4 method
sx.initCause(ex);
throw sx;
}
}
}
state.type = _class;
}
catch (java.lang.IllegalStateException ise) {
message(ise.toString());
throw new SAXException(ise);
}
//-- At this point we should have a new object, unless
//-- we are dealing with a primitive type, or a special
//-- case such as byte[]
if (classDesc == null) {
classDesc = getClassDescriptor(_class);
}
state.classDesc = classDesc;
if ((state.object == null) && (!state.primitiveOrImmutable))
{
String err = "unable to unmarshal: " + name + "\n";
err += " - unable to instantiate: " + className(_class);
throw new SAXException(err);
}
//-- assign object, if incremental
if (descriptor.isIncremental()) {
if (debug) {
message("debug: Processing incrementally for element: " + name);
}
try {
handler.setValue(parentState.object, state.object);
}
catch(java.lang.IllegalStateException ise) {
String err = "unable to add \"" + name + "\" to ";
err += parentState.fieldDesc.getXMLName();
err += " due to the following error: " + ise;
throw new SAXException(err);
}
}
if (state.object != null) {
//--The object has just been initialized
//--notify the listener
if ( _unmarshalListener != null )
_unmarshalListener.initialized(state.object);
processAttributes(atts, classDesc);
if ( _unmarshalListener != null )
_unmarshalListener.attributesProcessed(state.object);
processNamespaces(classDesc);
}
else if ((state.type != null) && (!state.primitiveOrImmutable)) {
if (atts != null) {
processWrapperAttributes(atts);
StringBuffer buffer = new StringBuffer();
buffer.append("The current object for element '");
buffer.append(name);
buffer.append("\' is null. Processing attributes as location");
buffer.append("/wrapper only and ignoring all other attribtes.");
message(buffer.toString());
}
}
else {
//-- check for special attributes, such as xsi:nil
if (atts != null) {
String nil = atts.getValue(NIL_ATTR, XSI_NAMESPACE);
state.nil = "true".equals(nil);
processWrapperAttributes(atts);
}
}
} //-- void startElement(String, AttributeList)
|
diff --git a/src/net/grinder/engine/process/GrinderProcess.java b/src/net/grinder/engine/process/GrinderProcess.java
index 63bf600b..593f6cd4 100755
--- a/src/net/grinder/engine/process/GrinderProcess.java
+++ b/src/net/grinder/engine/process/GrinderProcess.java
@@ -1,515 +1,518 @@
// The Grinder
// Copyright (C) 2000, 2001 Paco Gomez
// Copyright (C) 2000, 2001 Philip Aston
// 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 net.grinder.engine.process;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import net.grinder.common.GrinderException;
import net.grinder.common.GrinderProperties;
import net.grinder.common.Logger;
import net.grinder.common.Test;
import net.grinder.communication.CommunicationDefaults;
import net.grinder.communication.CommunicationException;
import net.grinder.communication.Message;
import net.grinder.communication.Receiver;
import net.grinder.communication.RegisterTestsMessage;
import net.grinder.communication.ReportStatisticsMessage;
import net.grinder.communication.ResetGrinderMessage;
import net.grinder.communication.Sender;
import net.grinder.communication.StartGrinderMessage;
import net.grinder.communication.StopGrinderMessage;
import net.grinder.engine.EngineException;
import net.grinder.plugininterface.GrinderPlugin;
import net.grinder.plugininterface.PluginProcessContext;
import net.grinder.plugininterface.ThreadCallbacks;
import net.grinder.statistics.StatisticsImplementation;
import net.grinder.statistics.StatisticsTable;
import net.grinder.statistics.TestStatisticsMap;
import net.grinder.util.PropertiesHelper;
/**
* The class executed by the main thread of each JVM.
* The total number of JVM is specified in the property "grinder.jvms".
* This class is responsible for creating as many threads as configured in the
* property "grinder.threads". Each thread is an object of class "CycleRunnable".
* It is responsible for storing the statistical information from the threads
* and also for send it to the console and print it at the end.
*
* @author Paco Gomez
* @author Philip Aston
* @version $Revision$
* @see net.grinder.engine.process.GrinderThread
*/
public class GrinderProcess
{
// Return values used to indicate to the parent process the
// last console signal that has been received.
public static int EXIT_NATURAL_DEATH = 0;
public static int EXIT_RESET_SIGNAL = 16;
public static int EXIT_START_SIGNAL = 17;
public static int EXIT_STOP_SIGNAL = 18;
/** Hack extra information from parent process in system properties **/
public static String DONT_WAIT_FOR_SIGNAL_PROPERTY_NAME =
"grinder.dontWaitForSignal";
/**
* The application's entry point.
*
*/
public static void main(String args[])
{
if (args.length < 1 || args.length > 2) {
System.err.println("Usage: java " +
GrinderProcess.class.getName() +
" <grinderID> [ propertiesFile ]");
System.exit(-1);
}
try {
final PropertiesHelper propertiesHelper =
args.length == 2 ?
new PropertiesHelper(args[1]) : new PropertiesHelper();
final GrinderProcess grinderProcess =
new GrinderProcess(args[0], propertiesHelper);
final int status = grinderProcess.run();
System.exit(status);
}
catch (GrinderException e) {
System.err.println("Error initialising grinder process: " + e);
e.printStackTrace();
System.exit(-2);
}
}
private final ProcessContextImplementation m_context;
private final int m_numberOfThreads;
private final boolean m_recordTime;
private final Listener m_listener;
private final Sender m_consoleSender;
private int m_reportToConsoleInterval = 0;
private final GrinderPlugin m_plugin;
/** A map of Tests to TestData. (TestData is the class this
* package uses to store information about Tests). */
private final Map m_testSet;
/** A map of Tests to Statistics for passing elsewhere. */
private final TestStatisticsMap m_testStatisticsMap;
public GrinderProcess(String grinderID, PropertiesHelper propertiesHelper)
throws GrinderException
{
final GrinderProperties properties = propertiesHelper.getProperties();
m_context = new ProcessContextImplementation(grinderID, properties);
m_numberOfThreads = properties.getInt("grinder.threads", 1);
m_recordTime = properties.getBoolean("grinder.recordTime", true);
// Parse plugin class.
m_plugin = propertiesHelper.instantiatePlugin(m_context);
// Get defined tests.
final Set tests = m_plugin.getTests();
// Parse console configuration.
final String multicastAddress =
properties.getProperty("grinder.multicastAddress",
CommunicationDefaults.MULTICAST_ADDRESS);
if (properties.getBoolean("grinder.receiveConsoleSignals", false)) {
final int grinderPort =
properties.getInt("grinder.multicastPort",
CommunicationDefaults.GRINDER_PORT);
if (multicastAddress != null && grinderPort > 0) {
final ConsoleListener listener =
new ConsoleListener(m_context, multicastAddress,
grinderPort);
final Thread t = new Thread(listener, "Console Listener");
t.setDaemon(true);
t.start();
m_listener = listener;
}
else {
throw new EngineException(
"Unable to receive console signals: " +
"multicast address or port not specified");
}
}
else {
m_listener =
new Listener() {
public boolean shouldWait() { return false; }
public void reset() {}
public boolean messageReceived(int mask) { return false; }
};
}
if (properties.getBoolean("grinder.reportToConsole", false)) {
final int consolePort =
properties.getInt("grinder.console.multicastPort",
CommunicationDefaults.CONSOLE_PORT);
if (multicastAddress != null && consolePort > 0) {
m_consoleSender = new Sender(m_context.getGrinderID(),
multicastAddress, consolePort);
m_reportToConsoleInterval =
properties.getInt("grinder.reportToConsole.interval", 500);
m_consoleSender.send(new RegisterTestsMessage(tests));
}
else {
throw new EngineException(
"Unable to report to console: " +
"multicast address or console port not specified");
}
}
else {
m_consoleSender = null;
}
// Wrap tests with our information.
m_testSet = new TreeMap();
m_testStatisticsMap = new TestStatisticsMap();
final Iterator testSetIterator = tests.iterator();
while (testSetIterator.hasNext())
{
final Test test = (Test)testSetIterator.next();
final String sleepTimePropertyName =
propertiesHelper.getTestPropertyName(test.getNumber(),
"sleepTime");
final long sleepTime =
properties.getInt(sleepTimePropertyName, -1);
final StatisticsImplementation statistics =
new StatisticsImplementation();
m_testSet.put(test, new TestData(test, sleepTime, statistics));
m_testStatisticsMap.put(test, statistics);
}
}
/**
* The application's main loop. This is split from the constructor
* as theoretically it might be called multiple times. The
* constructor sets up the static configuration, this does a
* single execution.
*
* @returns exit status to be indicated to parent process.
*/
protected int run() throws GrinderException
{
m_context.logMessage(System.getProperty("java.vm.vendor") + " " +
System.getProperty("java.vm.name") + " " +
System.getProperty("java.vm.version"));
m_context.logMessage(System.getProperty("os.name") + " " +
System.getProperty("os.arch") + " " +
System.getProperty("os.version"));
final String dataFilename =
m_context.getFilenameFactory().createFilename("data");
final PrintWriter dataPrintWriter;
try {
final boolean appendToLog = m_context.getAppendToLog();
dataPrintWriter =
new PrintWriter(
new BufferedWriter(
new FileWriter(dataFilename, appendToLog)));
if (!appendToLog) {
if (m_recordTime) {
dataPrintWriter.println("Thread, Cycle, Method, Time");
}
else {
dataPrintWriter.println("Thread, Cycle, Method");
}
}
}
catch(Exception e){
throw new EngineException("Cannot open process data file '" +
dataFilename + "'", e);
}
final GrinderThread runnable[] = new GrinderThread[m_numberOfThreads];
for (int i=0; i<m_numberOfThreads; i++) {
final ThreadContextImplementation pluginThreadContext =
new ThreadContextImplementation(m_context, i);
final ThreadCallbacks threadCallbackHandler =
m_plugin.createThreadCallbackHandler();
runnable[i] = new GrinderThread(this, threadCallbackHandler,
pluginThreadContext,
dataPrintWriter, m_recordTime,
m_testSet);
}
if (m_listener.shouldWait() &&
!Boolean.getBoolean(DONT_WAIT_FOR_SIGNAL_PROPERTY_NAME)) {
m_context.logMessage("waiting for console signal",
Logger.LOG | Logger.TERMINAL);
waitForMessage();
}
if (!m_listener.messageReceived(Listener.STOP | Listener.RESET)) {
m_context.logMessage("starting threads",
Logger.LOG | Logger.TERMINAL);
// Start the threads
for (int i=0; i<m_numberOfThreads; i++) {
final Thread t = new Thread(runnable[i],
"Grinder thread " + i);
t.setDaemon(true);
t.start();
}
do { // We want at least one report.
waitForMessage(m_reportToConsoleInterval,
Listener.RESET | Listener.STOP);
if (m_consoleSender != null) {
m_consoleSender.send(
new ReportStatisticsMessage(
m_testStatisticsMap.getDelta(true)));
}
}
while (GrinderThread.numberOfUncompletedThreads() > 0 &&
!m_listener.messageReceived(Listener.RESET |
Listener.STOP));
if (GrinderThread.numberOfUncompletedThreads() > 0) {
m_context.logMessage("waiting for threads to terminate",
Logger.LOG | Logger.TERMINAL);
GrinderThread.shutdown();
final long time = System.currentTimeMillis();
+ final long maxShutdownTime = 10000;
while (GrinderThread.numberOfUncompletedThreads() > 0) {
synchronized (this) {
try {
- if (System.currentTimeMillis() - time > 10000) {
+ if (System.currentTimeMillis() - time >
+ maxShutdownTime) {
m_context.logMessage(
"threads not terminating, " +
- "continuing anyway");
+ "continuing anyway",
+ Logger.LOG | Logger.TERMINAL);
break;
}
- wait();
+ wait(maxShutdownTime);
}
catch (InterruptedException e) {
}
}
}
}
}
if (dataPrintWriter != null) {
dataPrintWriter.close();
}
m_context.logMessage("Final statistics for this process:");
final StatisticsTable statisticsTable =
new StatisticsTable(m_testStatisticsMap);
statisticsTable.print(m_context.getOutputLogWriter());
if (m_listener.shouldWait() &&
!m_listener.messageReceived(Listener.ANY)) {
// We've got here naturally, without a console signal.
m_context.logMessage("finished, waiting for console signal",
Logger.LOG | Logger.TERMINAL);
waitForMessage();
}
if (m_listener.messageReceived(Listener.START)) {
m_context.logMessage("requesting reset and start");
return EXIT_START_SIGNAL;
}
else if (m_listener.messageReceived(Listener.RESET)) {
m_context.logMessage("requesting reset");
return EXIT_RESET_SIGNAL;
}
else if (m_listener.messageReceived(Listener.STOP)) {
m_context.logMessage("requesting stop");
return EXIT_STOP_SIGNAL;
}
else {
m_context.logMessage("finished", Logger.LOG | Logger.TERMINAL);
return EXIT_NATURAL_DEATH;
}
}
/**
* Wait for the given time, or until a console message arrives.
*
* @param period How long to wait. 0 => forever.
* @throws IllegalArgumentException if period is negative.
**/
private void waitForMessage(long period, int mask)
{
m_listener.reset();
long currentTime = System.currentTimeMillis();
final long wakeUpTime = currentTime + period;
final boolean forever = period == 0;
while (forever || currentTime < wakeUpTime) {
try {
synchronized(this) {
wait(forever ? 0 : wakeUpTime - currentTime);
}
break;
}
catch (InterruptedException e) {
if (m_listener.messageReceived(mask)) {
break;
}
else {
currentTime = System.currentTimeMillis();
}
}
}
}
/**
* Equivalent to waitForMessage(0, 0);
**/
private void waitForMessage()
{
waitForMessage(0, 0);
}
private interface Listener
{
public final static int START = 1 << 0;
public final static int RESET = 1 << 1;
public final static int STOP = 1 << 2;
public final static int ANY = START | RESET | STOP;
boolean shouldWait();
void reset();
boolean messageReceived(int mask);
}
/**
* Runnable that receives event messages from the Console.
* Currently no point in synchronising access.
*/
private class ConsoleListener implements Runnable, Listener
{
private final PluginProcessContext m_context;
private final Receiver m_receiver;
private int m_message = 0;
public ConsoleListener(PluginProcessContext context, String address,
int port)
throws CommunicationException
{
m_context = context;
m_receiver = new Receiver(address, port);
}
public void run()
{
while (true) {
final Message message;
try {
message = m_receiver.waitForMessage();
}
catch (CommunicationException e) {
m_context.logError("error receiving console signal: " + e,
Logger.LOG | Logger.TERMINAL);
continue;
}
if (message instanceof StartGrinderMessage) {
m_context.logMessage("got a start message from console");
m_message |= START;
}
else if (message instanceof StopGrinderMessage) {
m_context.logMessage("got a stop message from console");
m_message |= STOP;
}
else if (message instanceof ResetGrinderMessage) {
m_context.logMessage("got a reset message from console");
m_message |= RESET;
}
else {
m_context.logMessage(
"got an unknown message from console");
}
synchronized(GrinderProcess.this) {
GrinderProcess.this.notifyAll();
}
}
}
public boolean shouldWait()
{
return true;
}
public boolean messageReceived(int mask)
{
return (m_message & mask) != 0;
}
public void reset()
{
m_message = 0;
}
}
}
| false | true | protected int run() throws GrinderException
{
m_context.logMessage(System.getProperty("java.vm.vendor") + " " +
System.getProperty("java.vm.name") + " " +
System.getProperty("java.vm.version"));
m_context.logMessage(System.getProperty("os.name") + " " +
System.getProperty("os.arch") + " " +
System.getProperty("os.version"));
final String dataFilename =
m_context.getFilenameFactory().createFilename("data");
final PrintWriter dataPrintWriter;
try {
final boolean appendToLog = m_context.getAppendToLog();
dataPrintWriter =
new PrintWriter(
new BufferedWriter(
new FileWriter(dataFilename, appendToLog)));
if (!appendToLog) {
if (m_recordTime) {
dataPrintWriter.println("Thread, Cycle, Method, Time");
}
else {
dataPrintWriter.println("Thread, Cycle, Method");
}
}
}
catch(Exception e){
throw new EngineException("Cannot open process data file '" +
dataFilename + "'", e);
}
final GrinderThread runnable[] = new GrinderThread[m_numberOfThreads];
for (int i=0; i<m_numberOfThreads; i++) {
final ThreadContextImplementation pluginThreadContext =
new ThreadContextImplementation(m_context, i);
final ThreadCallbacks threadCallbackHandler =
m_plugin.createThreadCallbackHandler();
runnable[i] = new GrinderThread(this, threadCallbackHandler,
pluginThreadContext,
dataPrintWriter, m_recordTime,
m_testSet);
}
if (m_listener.shouldWait() &&
!Boolean.getBoolean(DONT_WAIT_FOR_SIGNAL_PROPERTY_NAME)) {
m_context.logMessage("waiting for console signal",
Logger.LOG | Logger.TERMINAL);
waitForMessage();
}
if (!m_listener.messageReceived(Listener.STOP | Listener.RESET)) {
m_context.logMessage("starting threads",
Logger.LOG | Logger.TERMINAL);
// Start the threads
for (int i=0; i<m_numberOfThreads; i++) {
final Thread t = new Thread(runnable[i],
"Grinder thread " + i);
t.setDaemon(true);
t.start();
}
do { // We want at least one report.
waitForMessage(m_reportToConsoleInterval,
Listener.RESET | Listener.STOP);
if (m_consoleSender != null) {
m_consoleSender.send(
new ReportStatisticsMessage(
m_testStatisticsMap.getDelta(true)));
}
}
while (GrinderThread.numberOfUncompletedThreads() > 0 &&
!m_listener.messageReceived(Listener.RESET |
Listener.STOP));
if (GrinderThread.numberOfUncompletedThreads() > 0) {
m_context.logMessage("waiting for threads to terminate",
Logger.LOG | Logger.TERMINAL);
GrinderThread.shutdown();
final long time = System.currentTimeMillis();
while (GrinderThread.numberOfUncompletedThreads() > 0) {
synchronized (this) {
try {
if (System.currentTimeMillis() - time > 10000) {
m_context.logMessage(
"threads not terminating, " +
"continuing anyway");
break;
}
wait();
}
catch (InterruptedException e) {
}
}
}
}
}
if (dataPrintWriter != null) {
dataPrintWriter.close();
}
m_context.logMessage("Final statistics for this process:");
final StatisticsTable statisticsTable =
new StatisticsTable(m_testStatisticsMap);
statisticsTable.print(m_context.getOutputLogWriter());
if (m_listener.shouldWait() &&
!m_listener.messageReceived(Listener.ANY)) {
// We've got here naturally, without a console signal.
m_context.logMessage("finished, waiting for console signal",
Logger.LOG | Logger.TERMINAL);
waitForMessage();
}
if (m_listener.messageReceived(Listener.START)) {
m_context.logMessage("requesting reset and start");
return EXIT_START_SIGNAL;
}
else if (m_listener.messageReceived(Listener.RESET)) {
m_context.logMessage("requesting reset");
return EXIT_RESET_SIGNAL;
}
else if (m_listener.messageReceived(Listener.STOP)) {
m_context.logMessage("requesting stop");
return EXIT_STOP_SIGNAL;
}
else {
m_context.logMessage("finished", Logger.LOG | Logger.TERMINAL);
return EXIT_NATURAL_DEATH;
}
}
| protected int run() throws GrinderException
{
m_context.logMessage(System.getProperty("java.vm.vendor") + " " +
System.getProperty("java.vm.name") + " " +
System.getProperty("java.vm.version"));
m_context.logMessage(System.getProperty("os.name") + " " +
System.getProperty("os.arch") + " " +
System.getProperty("os.version"));
final String dataFilename =
m_context.getFilenameFactory().createFilename("data");
final PrintWriter dataPrintWriter;
try {
final boolean appendToLog = m_context.getAppendToLog();
dataPrintWriter =
new PrintWriter(
new BufferedWriter(
new FileWriter(dataFilename, appendToLog)));
if (!appendToLog) {
if (m_recordTime) {
dataPrintWriter.println("Thread, Cycle, Method, Time");
}
else {
dataPrintWriter.println("Thread, Cycle, Method");
}
}
}
catch(Exception e){
throw new EngineException("Cannot open process data file '" +
dataFilename + "'", e);
}
final GrinderThread runnable[] = new GrinderThread[m_numberOfThreads];
for (int i=0; i<m_numberOfThreads; i++) {
final ThreadContextImplementation pluginThreadContext =
new ThreadContextImplementation(m_context, i);
final ThreadCallbacks threadCallbackHandler =
m_plugin.createThreadCallbackHandler();
runnable[i] = new GrinderThread(this, threadCallbackHandler,
pluginThreadContext,
dataPrintWriter, m_recordTime,
m_testSet);
}
if (m_listener.shouldWait() &&
!Boolean.getBoolean(DONT_WAIT_FOR_SIGNAL_PROPERTY_NAME)) {
m_context.logMessage("waiting for console signal",
Logger.LOG | Logger.TERMINAL);
waitForMessage();
}
if (!m_listener.messageReceived(Listener.STOP | Listener.RESET)) {
m_context.logMessage("starting threads",
Logger.LOG | Logger.TERMINAL);
// Start the threads
for (int i=0; i<m_numberOfThreads; i++) {
final Thread t = new Thread(runnable[i],
"Grinder thread " + i);
t.setDaemon(true);
t.start();
}
do { // We want at least one report.
waitForMessage(m_reportToConsoleInterval,
Listener.RESET | Listener.STOP);
if (m_consoleSender != null) {
m_consoleSender.send(
new ReportStatisticsMessage(
m_testStatisticsMap.getDelta(true)));
}
}
while (GrinderThread.numberOfUncompletedThreads() > 0 &&
!m_listener.messageReceived(Listener.RESET |
Listener.STOP));
if (GrinderThread.numberOfUncompletedThreads() > 0) {
m_context.logMessage("waiting for threads to terminate",
Logger.LOG | Logger.TERMINAL);
GrinderThread.shutdown();
final long time = System.currentTimeMillis();
final long maxShutdownTime = 10000;
while (GrinderThread.numberOfUncompletedThreads() > 0) {
synchronized (this) {
try {
if (System.currentTimeMillis() - time >
maxShutdownTime) {
m_context.logMessage(
"threads not terminating, " +
"continuing anyway",
Logger.LOG | Logger.TERMINAL);
break;
}
wait(maxShutdownTime);
}
catch (InterruptedException e) {
}
}
}
}
}
if (dataPrintWriter != null) {
dataPrintWriter.close();
}
m_context.logMessage("Final statistics for this process:");
final StatisticsTable statisticsTable =
new StatisticsTable(m_testStatisticsMap);
statisticsTable.print(m_context.getOutputLogWriter());
if (m_listener.shouldWait() &&
!m_listener.messageReceived(Listener.ANY)) {
// We've got here naturally, without a console signal.
m_context.logMessage("finished, waiting for console signal",
Logger.LOG | Logger.TERMINAL);
waitForMessage();
}
if (m_listener.messageReceived(Listener.START)) {
m_context.logMessage("requesting reset and start");
return EXIT_START_SIGNAL;
}
else if (m_listener.messageReceived(Listener.RESET)) {
m_context.logMessage("requesting reset");
return EXIT_RESET_SIGNAL;
}
else if (m_listener.messageReceived(Listener.STOP)) {
m_context.logMessage("requesting stop");
return EXIT_STOP_SIGNAL;
}
else {
m_context.logMessage("finished", Logger.LOG | Logger.TERMINAL);
return EXIT_NATURAL_DEATH;
}
}
|
diff --git a/framework/src/play/mvc/Router.java b/framework/src/play/mvc/Router.java
index 76d3b862..6fe2d1cc 100644
--- a/framework/src/play/mvc/Router.java
+++ b/framework/src/play/mvc/Router.java
@@ -1,303 +1,305 @@
package play.mvc;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jregex.Matcher;
import jregex.Pattern;
import play.Logger;
import play.Play;
import play.Play.Mode;
import play.exceptions.EmptyAppException;
import play.vfs.VirtualFile;
import play.exceptions.NoRouteFoundException;
import play.mvc.results.NotFound;
import play.mvc.results.RenderStatic;
public class Router {
static Pattern routePattern = new Pattern("^({method}[A-Za-z\\*]+)?\\s+({path}/[^\\s]*)\\s+({action}[^\\s(]+)({params}.+)?$");
/**
* Pattern used to locate a method override instruction in request.querystring
*/
static Pattern methodOverride = new Pattern("^.*x-http-method-override=({method}GET|PUT|POST|DELETE).*$");
static long lastLoading;
static boolean empty = true;
public static void load() {
empty = true;
routes.clear();
String config = "";
for (VirtualFile file : Play.routes) {
config += file.contentAsString() + "\n";
}
String[] lines = config.split("\n");
for (String line : lines) {
line = line.trim().replaceAll("\\s+", " ");
if (line.length() == 0 || line.startsWith("#")) {
continue;
}
Matcher matcher = routePattern.matcher(line);
if (matcher.matches()) {
Route route = new Route();
route.method = matcher.group("method");
route.path = matcher.group("path");
route.action = matcher.group("action");
route.addParams(matcher.group("params"));
route.compute();
routes.add(route);
} else {
Logger.warn("Invalid route definition : %s", line);
}
}
lastLoading = System.currentTimeMillis();
}
public static void detectChanges() {
if (Play.mode==Mode.PROD)
return;
for (VirtualFile file : Play.routes) {
if (file.lastModified() > lastLoading) {
load();
return;
}
}
}
static List<Route> routes = new ArrayList<Route>();
public static void route(Http.Request request) {
if (empty) {
throw new EmptyAppException();
}
// request method may be overriden if a x-http-method-override parameter is given
if( request.querystring != null && methodOverride.matches(request.querystring)) {
Matcher matcher = methodOverride.matcher(request.querystring);
if (matcher.matches()) {
Logger.info("request method %s overriden to %s ", request.method, matcher.group("method") );
request.method = matcher.group("method");
}
}
for (Route route : routes) {
Map<String, String> args = route.matches(request.method, request.path);
if (args != null) {
request.routeArgs = args;
request.action = route.action;
return;
}
}
throw new NotFound(request.method, request.path);
}
public static Map<String, String> route(String method, String path) {
if (routes.isEmpty()) {
throw new EmptyAppException();
}
for (Route route : routes) {
Map<String, String> args = route.matches(method, path);
if (args != null) {
args.put("action", route.action);
return args;
}
}
return new HashMap<String, String>();
}
public static ActionDefinition reverse(String action) {
return reverse(action, new HashMap<String, Object>());
}
public static ActionDefinition reverseForTemplate(String action, Map<String, Object> r) {
ActionDefinition actionDef = reverse(action, r);
if ( !("GET".equals(actionDef.method) || "POST".equals(actionDef.method))) {
String separator = actionDef.url.indexOf('?') != -1 ? "&" : "?";
actionDef.url += separator +"x-http-method-override=" + actionDef.method;
}
return actionDef;
}
public static String getFullUrl(String action, Map<String, Object> args) {
return Http.Request.current().getBase() + reverse(action, args);
}
public static String getFullUrl(String action) {
return getFullUrl(action, new HashMap<String, Object>());
}
public static ActionDefinition reverse(String action, Map<String, Object> args) {
if (action.startsWith("controllers.")) {
action = action.substring(12);
}
for (Route route : routes) {
if (route.action.equals(action)) {
List<String> inPathArgs = new ArrayList<String>();
boolean allRequiredArgsAreHere = true;
// les noms de parametres matchent ils ?
for (Route.Arg arg : route.args) {
inPathArgs.add(arg.name);
- String value=null;
- if (List.class.isAssignableFrom(args.get(arg.name).getClass())) {
- Object o = ((List<Object>) args.get(arg.name)).get(0);
- value = o == null ? null : o.toString();
- } else
- value = args.get(arg.name) == null ? null : args.get(arg.name) + "";
- if (value == null || !arg.constraint.matches(value)) {
- allRequiredArgsAreHere = false;
+ Object value = args.get(arg.name);
+ if (value==null) {
+ allRequiredArgsAreHere = false;
break;
+ } else {
+ if (value instanceof List)
+ value = ((List<Object>) value).get(0);
+ if (!arg.constraint.matches((String)value)) {
+ allRequiredArgsAreHere = false;
+ break;
+ }
}
}
// les parametres codes en dur dans la route matchent-ils ?
for (String staticKey : route.staticArgs.keySet()) {
if (!args.containsKey(staticKey) || !args.get(staticKey).equals(route.staticArgs.get(staticKey))) {
allRequiredArgsAreHere = false;
break;
}
}
if (allRequiredArgsAreHere) {
StringBuilder queryString = new StringBuilder();
String path = route.path;
for (String key : args.keySet()) {
if (inPathArgs.contains(key) && args.get(key) != null) {
if (List.class.isAssignableFrom(args.get(key).getClass())) {
List<Object> vals = (List<Object>) args.get(key);
path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", vals.get(0) + "");
} else
path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", args.get(key) + "");
} else if (route.staticArgs.containsKey(key)) {
// Do nothing -> The key is static
} else if (args.get(key) != null) {
if (List.class.isAssignableFrom(args.get(key).getClass())) {
List<Object> vals = (List<Object>) args.get(key);
for (Object object : vals) {
try {
queryString.append(URLEncoder.encode(key, "utf-8"));
queryString.append("=");
queryString.append(URLEncoder.encode(object.toString() + "", "utf-8"));
queryString.append("&");
} catch (UnsupportedEncodingException ex) {}
}
} else {
try {
queryString.append(URLEncoder.encode(key, "utf-8"));
queryString.append("=");
queryString.append(URLEncoder.encode(args.get(key) + "", "utf-8"));
queryString.append("&");
} catch (UnsupportedEncodingException ex) {}
}
}
}
String qs = queryString.toString();
if (qs.endsWith("&")) {
qs = qs.substring(0, qs.length() - 1);
}
ActionDefinition actionDefinition = new ActionDefinition();
actionDefinition.url = qs.length() == 0 ? path : path + "?" + qs;
actionDefinition.method = route.method == null || route.method.equals("*") ? "GET" : route.method.toUpperCase();
return actionDefinition;
}
}
}
throw new NoRouteFoundException(action, args);
}
public static class ActionDefinition {
public String method;
public String url;
@Override
public String toString() {
return url;
}
}
static class Route {
String method;
String path;
String action;
String staticDir;
Pattern pattern;
List<Arg> args = new ArrayList<Arg>();
Map<String, String> staticArgs = new HashMap<String, String>();
static Pattern customRegexPattern = new Pattern("\\{([a-zA-Z_0-9]+)\\}");
static Pattern argsPattern = new Pattern("\\{<([^>]+)>([a-zA-Z_0-9]+)\\}");
static Pattern paramPattern = new Pattern("([a-zA-Z_0-9]+):'(.*)'");
public void compute() {
// staticDir
if(action.startsWith("staticDir:")) {
if(!method.equalsIgnoreCase("*") && !method.equalsIgnoreCase("GET")) {
Logger.warn("Static route only support GET method");
return;
}
if(!this.path.endsWith("/") && !this.path.equals("/")) {
this.path += "/";
}
this.pattern = new Pattern(path+"({resource}.*)");
this.staticDir = action.substring("staticDir:".length());
} else {
String patternString = path;
patternString = customRegexPattern.replacer("\\{<[^/]+>$1\\}").replace(patternString);
Matcher matcher = argsPattern.matcher(patternString);
while (matcher.find()) {
Arg arg = new Arg();
arg.name = matcher.group(2);
arg.constraint = new Pattern(matcher.group(1));
args.add(arg);
}
patternString = argsPattern.replacer("({$2}$1)").replace(patternString);
this.pattern = new Pattern(patternString);
Router.empty = false;
}
}
public void addParams(String params) {
if (params == null) {
return;
}
params = params.substring(1, params.length() - 1);
for (String param : params.split(",")) {
Matcher matcher = paramPattern.matcher(param);
if (matcher.matches()) {
staticArgs.put(matcher.group(1), matcher.group(2));
}
}
}
public Map<String, String> matches(String method, String path) {
if (method == null || this.method.equals("*") || method.equalsIgnoreCase(this.method)) {
Matcher matcher = pattern.matcher(path);
if (matcher.matches()) {
// Static dir
if(staticDir != null) {
throw new RenderStatic(staticDir + "/" + matcher.group("resource"));
} else {
Map<String, String> localArgs = new HashMap<String, String>();
for (Arg arg : args) {
localArgs.put(arg.name, matcher.group(arg.name));
}
localArgs.putAll(staticArgs);
return localArgs;
}
}
}
return null;
}
static class Arg {
String name;
Pattern constraint;
String defaultValue;
Boolean optional = false;
}
@Override
public String toString() {
return method + " " + path + " -> " + action;
}
}
}
| false | true | public static ActionDefinition reverse(String action, Map<String, Object> args) {
if (action.startsWith("controllers.")) {
action = action.substring(12);
}
for (Route route : routes) {
if (route.action.equals(action)) {
List<String> inPathArgs = new ArrayList<String>();
boolean allRequiredArgsAreHere = true;
// les noms de parametres matchent ils ?
for (Route.Arg arg : route.args) {
inPathArgs.add(arg.name);
String value=null;
if (List.class.isAssignableFrom(args.get(arg.name).getClass())) {
Object o = ((List<Object>) args.get(arg.name)).get(0);
value = o == null ? null : o.toString();
} else
value = args.get(arg.name) == null ? null : args.get(arg.name) + "";
if (value == null || !arg.constraint.matches(value)) {
allRequiredArgsAreHere = false;
break;
}
}
// les parametres codes en dur dans la route matchent-ils ?
for (String staticKey : route.staticArgs.keySet()) {
if (!args.containsKey(staticKey) || !args.get(staticKey).equals(route.staticArgs.get(staticKey))) {
allRequiredArgsAreHere = false;
break;
}
}
if (allRequiredArgsAreHere) {
StringBuilder queryString = new StringBuilder();
String path = route.path;
for (String key : args.keySet()) {
if (inPathArgs.contains(key) && args.get(key) != null) {
if (List.class.isAssignableFrom(args.get(key).getClass())) {
List<Object> vals = (List<Object>) args.get(key);
path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", vals.get(0) + "");
} else
path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", args.get(key) + "");
} else if (route.staticArgs.containsKey(key)) {
// Do nothing -> The key is static
} else if (args.get(key) != null) {
if (List.class.isAssignableFrom(args.get(key).getClass())) {
List<Object> vals = (List<Object>) args.get(key);
for (Object object : vals) {
try {
queryString.append(URLEncoder.encode(key, "utf-8"));
queryString.append("=");
queryString.append(URLEncoder.encode(object.toString() + "", "utf-8"));
queryString.append("&");
} catch (UnsupportedEncodingException ex) {}
}
} else {
try {
queryString.append(URLEncoder.encode(key, "utf-8"));
queryString.append("=");
queryString.append(URLEncoder.encode(args.get(key) + "", "utf-8"));
queryString.append("&");
} catch (UnsupportedEncodingException ex) {}
}
}
}
String qs = queryString.toString();
if (qs.endsWith("&")) {
qs = qs.substring(0, qs.length() - 1);
}
ActionDefinition actionDefinition = new ActionDefinition();
actionDefinition.url = qs.length() == 0 ? path : path + "?" + qs;
actionDefinition.method = route.method == null || route.method.equals("*") ? "GET" : route.method.toUpperCase();
return actionDefinition;
}
}
}
throw new NoRouteFoundException(action, args);
}
| public static ActionDefinition reverse(String action, Map<String, Object> args) {
if (action.startsWith("controllers.")) {
action = action.substring(12);
}
for (Route route : routes) {
if (route.action.equals(action)) {
List<String> inPathArgs = new ArrayList<String>();
boolean allRequiredArgsAreHere = true;
// les noms de parametres matchent ils ?
for (Route.Arg arg : route.args) {
inPathArgs.add(arg.name);
Object value = args.get(arg.name);
if (value==null) {
allRequiredArgsAreHere = false;
break;
} else {
if (value instanceof List)
value = ((List<Object>) value).get(0);
if (!arg.constraint.matches((String)value)) {
allRequiredArgsAreHere = false;
break;
}
}
}
// les parametres codes en dur dans la route matchent-ils ?
for (String staticKey : route.staticArgs.keySet()) {
if (!args.containsKey(staticKey) || !args.get(staticKey).equals(route.staticArgs.get(staticKey))) {
allRequiredArgsAreHere = false;
break;
}
}
if (allRequiredArgsAreHere) {
StringBuilder queryString = new StringBuilder();
String path = route.path;
for (String key : args.keySet()) {
if (inPathArgs.contains(key) && args.get(key) != null) {
if (List.class.isAssignableFrom(args.get(key).getClass())) {
List<Object> vals = (List<Object>) args.get(key);
path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", vals.get(0) + "");
} else
path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", args.get(key) + "");
} else if (route.staticArgs.containsKey(key)) {
// Do nothing -> The key is static
} else if (args.get(key) != null) {
if (List.class.isAssignableFrom(args.get(key).getClass())) {
List<Object> vals = (List<Object>) args.get(key);
for (Object object : vals) {
try {
queryString.append(URLEncoder.encode(key, "utf-8"));
queryString.append("=");
queryString.append(URLEncoder.encode(object.toString() + "", "utf-8"));
queryString.append("&");
} catch (UnsupportedEncodingException ex) {}
}
} else {
try {
queryString.append(URLEncoder.encode(key, "utf-8"));
queryString.append("=");
queryString.append(URLEncoder.encode(args.get(key) + "", "utf-8"));
queryString.append("&");
} catch (UnsupportedEncodingException ex) {}
}
}
}
String qs = queryString.toString();
if (qs.endsWith("&")) {
qs = qs.substring(0, qs.length() - 1);
}
ActionDefinition actionDefinition = new ActionDefinition();
actionDefinition.url = qs.length() == 0 ? path : path + "?" + qs;
actionDefinition.method = route.method == null || route.method.equals("*") ? "GET" : route.method.toUpperCase();
return actionDefinition;
}
}
}
throw new NoRouteFoundException(action, args);
}
|
diff --git a/java/tools/src/com/jopdesign/wcet/frontend/WcetAppInfo.java b/java/tools/src/com/jopdesign/wcet/frontend/WcetAppInfo.java
index 4f0b95c8..0c44744e 100644
--- a/java/tools/src/com/jopdesign/wcet/frontend/WcetAppInfo.java
+++ b/java/tools/src/com/jopdesign/wcet/frontend/WcetAppInfo.java
@@ -1,314 +1,314 @@
/*
This file is part of JOP, the Java Optimized Processor
see <http://www.jopdesign.com/>
Copyright (C) 2008, Benedikt Huber ([email protected])
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jopdesign.wcet.frontend;
import java.io.IOException;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.Vector;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.log4j.Logger;
import com.jopdesign.build.AppInfo;
import com.jopdesign.build.ClassInfo;
import com.jopdesign.build.MethodInfo;
import com.jopdesign.dfa.framework.ContextMap;
import com.jopdesign.wcet.ProcessorModel;
import com.jopdesign.wcet.Project;
import com.jopdesign.wcet.Project.AnalysisError;
import com.jopdesign.wcet.frontend.SourceAnnotations.BadAnnotationException;
import com.jopdesign.wcet.frontend.SourceAnnotations.LoopBound;
import com.jopdesign.wcet.graphutils.TopOrder.BadGraphException;
/**
* AppInfo subclass for the WCET analysis.
* Provides a TypeGraph.
*
* @author Benedikt Huber, [email protected]
*/
public class WcetAppInfo {
private static final long serialVersionUID = 3L;
/* package logger */
public static final Logger logger = Logger.getLogger(WcetAppInfo.class.getPackage().toString());
/**
* Raised when we cannot find / fail to load a referenced method.
*/
public class MethodNotFoundException extends Exception {
private static final long serialVersionUID = 1L;
public MethodNotFoundException(String message) {
super(message);
}
}
private TypeGraph typeGraph;
private AppInfo ai;
private Map<MethodInfo, ControlFlowGraph> cfgs;
private List<ControlFlowGraph> cfgsByIndex;
private Map<InstructionHandle, ContextMap<String, String>> receiverAnalysis = null;
private ProcessorModel processor;
private Project project;
public WcetAppInfo(Project p, com.jopdesign.build.AppInfo ai, ProcessorModel processor) {
this.project = p;
this.ai = ai;
this.processor = processor;
this.typeGraph = new TypeGraph(this);
cfgsByIndex = new Vector<ControlFlowGraph>();
cfgs = new Hashtable<MethodInfo, ControlFlowGraph>();
}
/**
* @return A mapping from the name of a loaded class to {@link ClassInfo}.
*/
public Map<String, ? extends ClassInfo> getCliMap() {
return ai.cliMap;
}
public Project getProject() {
return project;
}
/**
* @return The typegraph of all loaded classes
*/
public TypeGraph getTypeGraph() {
return typeGraph;
}
/**
* @param className Name of the class to lookup
* @return the class info, or null if the class could'nt be found
*/
public ClassInfo getClassInfo(String className) {
return getCliMap().get(className);
}
/**
* Find the given method
* @param className The fully qualified name of the class the method is located in
* @param methodName The name of the method to be searched.
* Note that the signature is optional if the method name is unique.
* @return The method searched for, or null if it couldn't be found
* @throws MethodNotFoundException if the method couldn't be found or is ambiguous
*/
public MethodInfo searchMethod(String className, String methodName) throws MethodNotFoundException {
ClassInfo cli = getCliMap().get(className);
if(cli == null) throw new MethodNotFoundException("The class "+className+" couldn't be found");
return searchMethod(cli,methodName);
}
public MethodInfo searchMethod(ClassInfo cli, String methodName) throws MethodNotFoundException {
MethodInfo mi = null;
if(methodName.indexOf("(") > 0) {
mi = cli.getMethodInfo(methodName);
if(mi == null) {
throw new MethodNotFoundException("The fully qualified method '"+methodName+"' could not be found in "+
cli.getMethodInfoMap().keySet());
}
} else {
for(MethodInfo candidate : cli.getMethods()) {
if(methodName.equals(candidate.getMethod().getName())) {
if(mi == null) {
mi = candidate;
} else {
throw new MethodNotFoundException("The method name "+methodName+" is ambiguous."+
"Both "+mi.methodId+" and "+candidate.methodId+" match");
}
}
}
if(mi == null) {
Vector<String> candidates = new Vector<String>();
for(MethodInfo candidate : cli.getMethods()) {
candidates.add(candidate.getMethod().getName());
}
- throw new MethodNotFoundException("The method "+methodName+"could not be found in "+cli.toString()+". "+
+ throw new MethodNotFoundException("The method "+methodName+" could not be found in "+cli.toString()+". "+
"Candidates: "+candidates);
}
}
return mi;
}
/**
* Return the receiver name and method name of a
* method referenced by the given invoke instruction
* @param invokerCi the classinfo of the method which contains the {@link InvokeInstruciton}
* @param instr the invoke instruction
* @return A pair of class info and method name
*/
public MethodRef getReferenced(ClassInfo invokerCi, InvokeInstruction instr) {
ClassInfo refCi;
ConstantPoolGen cpg = new ConstantPoolGen(invokerCi.clazz.getConstantPool());
String classname = instr.getClassName(cpg );
String methodname = instr.getMethodName(cpg) + instr.getSignature(cpg);
refCi = getClassInfo(classname);
if(refCi == null) throw new AssertionError("Failed class lookup (invoke target): "+classname);
return new MethodRef(refCi,methodname);
}
public MethodRef getReferenced(MethodInfo method, InvokeInstruction instr) {
return getReferenced(method.getCli(),instr);
}
public MethodInfo findStaticImplementation(MethodRef ref) {
ClassInfo receiver = ref.getReceiver();
String methodId = ref.getMethodId();
MethodInfo staticImpl = ref.getReceiver().getMethodInfo(methodId);
if(staticImpl == null) {
ClassInfo superRec = receiver;
while(staticImpl == null && superRec != null) {
staticImpl = superRec.getMethodInfo(methodId);
try {
if(superRec.clazz.getSuperClass() == null) superRec = null;
else superRec = superRec.superClass;
} catch (ClassNotFoundException e) {
e.printStackTrace();
throw new Error();
}
}
}
return staticImpl;
}
/**
* Find possible implementations of the given method in the given class
* <p>
* For all candidates, check whether they implement the method.
* All subclasses of the receiver class are candidates. If the method isn't implemented
* in the receiver, the lowest superclass implementing the method is a candidate too.
* </p>
* @param receiver The class info of the receiver
* @param methodname The method name
* @return list of method infos that might be invoked
*/
public List<MethodInfo> findImplementations(MethodRef methodRef) {
Vector<MethodInfo> impls = new Vector<MethodInfo>(3);
tryAddImpl(impls,findStaticImplementation(methodRef));
for(ClassInfo subty : this.typeGraph.getStrictSubtypes(methodRef.getReceiver())) {
MethodInfo subtyImpl = subty.getMethodInfo(methodRef.getMethodId());
tryAddImpl(impls,subtyImpl);
}
return impls;
}
/**
* Variant operating on an instruction handle and therefore capable of
* using DFA analysis results.
* @param invInstr
* @return
*/
public List<MethodInfo> findImplementations(MethodInfo invokerM, InstructionHandle ih) {
MethodRef ref = this.getReferenced(invokerM, (InvokeInstruction) ih.getInstruction());
List<MethodInfo> staticImpls = findImplementations(ref);
staticImpls = dfaReceivers(ih, staticImpls);
return staticImpls;
}
// TODO: rather slow, for debugging purposes
private List<MethodInfo> dfaReceivers(InstructionHandle ih, List<MethodInfo> staticImpls) {
if(this.receiverAnalysis != null && receiverAnalysis.containsKey(ih)) {
ContextMap<String, String> receivers = receiverAnalysis.get(ih);
List<MethodInfo> dynImpls = new Vector<MethodInfo>();
Set<String> dynReceivers = receivers.keySet();
for(MethodInfo impl : staticImpls) {
if(dynReceivers.contains(impl.getFQMethodName())) {
dynReceivers.remove(impl.getFQMethodName());
dynImpls.add(impl);
} else {
logger.info("Static but not dynamic receiver: "+impl);
}
}
if(! dynReceivers.isEmpty()) {
throw new AssertionError("Bad receiver analysis ? Dynamic but not static receivers: "+dynReceivers);
}
return dynImpls;
} else {
return staticImpls;
}
}
/* helper to avoid code dupl */
private void tryAddImpl(List<MethodInfo> ms, MethodInfo m) {
if(m != null) {
if(! m.getMethod().isAbstract() && ! m.getMethod().isInterface()) {
ms.add(m);
}
}
}
public AppInfo getAppInfo() {
return this.ai;
}
public ControlFlowGraph getFlowGraph(int id) {
return cfgsByIndex.get(id);
}
public ControlFlowGraph getFlowGraph(MethodInfo m) {
if(cfgs.get(m) == null) {
try {
loadFlowGraph(m);
} catch (BadAnnotationException e) {
throw new AnalysisError("Bad Flow Fact Annotation: "+e.getMessage(),e);
} catch (IOException e) {
throw new AnalysisError("IO Exception",e);
} catch (BadGraphException e) {
throw new AnalysisError("Bad Flow Graph: "+e.getMessage(),e);
}
}
return cfgs.get(m);
}
private ControlFlowGraph loadFlowGraph(MethodInfo method) throws BadAnnotationException, IOException, BadGraphException {
SortedMap<Integer,LoopBound> wcaMap = project.getAnnotations(method.getCli());
assert(wcaMap != null);
if(method.getCode() == null) {
throw new BadGraphException("No implementation of "+method.getFQMethodName()+" available for the target processor");
}
ControlFlowGraph fg;
try {
fg = new ControlFlowGraph(cfgsByIndex.size(),project,method);
fg.loadAnnotations(project);
fg.resolveVirtualInvokes();
// fg.insertSplitNodes();
// fg.insertSummaryNodes();
fg.insertReturnNodes();
fg.insertContinueLoopNodes();
cfgsByIndex.add(fg);
cfgs.put(method,fg);
return fg;
} catch(BadGraphException e) {
logger.error("Bad flow graph: "+e);
throw e;
}
}
public void setReceivers(
Map<InstructionHandle, ContextMap<String, String>> receiverResults) {
this.receiverAnalysis = receiverResults;
}
public ProcessorModel getProcessorModel() {
return this.processor;
}
public MethodInfo getJavaImplementation(MethodInfo ctx, Instruction lastInstr) {
return this.processor.getJavaImplementation(this, ctx, lastInstr);
}
}
| true | true | public MethodInfo searchMethod(ClassInfo cli, String methodName) throws MethodNotFoundException {
MethodInfo mi = null;
if(methodName.indexOf("(") > 0) {
mi = cli.getMethodInfo(methodName);
if(mi == null) {
throw new MethodNotFoundException("The fully qualified method '"+methodName+"' could not be found in "+
cli.getMethodInfoMap().keySet());
}
} else {
for(MethodInfo candidate : cli.getMethods()) {
if(methodName.equals(candidate.getMethod().getName())) {
if(mi == null) {
mi = candidate;
} else {
throw new MethodNotFoundException("The method name "+methodName+" is ambiguous."+
"Both "+mi.methodId+" and "+candidate.methodId+" match");
}
}
}
if(mi == null) {
Vector<String> candidates = new Vector<String>();
for(MethodInfo candidate : cli.getMethods()) {
candidates.add(candidate.getMethod().getName());
}
throw new MethodNotFoundException("The method "+methodName+"could not be found in "+cli.toString()+". "+
"Candidates: "+candidates);
}
}
return mi;
}
| public MethodInfo searchMethod(ClassInfo cli, String methodName) throws MethodNotFoundException {
MethodInfo mi = null;
if(methodName.indexOf("(") > 0) {
mi = cli.getMethodInfo(methodName);
if(mi == null) {
throw new MethodNotFoundException("The fully qualified method '"+methodName+"' could not be found in "+
cli.getMethodInfoMap().keySet());
}
} else {
for(MethodInfo candidate : cli.getMethods()) {
if(methodName.equals(candidate.getMethod().getName())) {
if(mi == null) {
mi = candidate;
} else {
throw new MethodNotFoundException("The method name "+methodName+" is ambiguous."+
"Both "+mi.methodId+" and "+candidate.methodId+" match");
}
}
}
if(mi == null) {
Vector<String> candidates = new Vector<String>();
for(MethodInfo candidate : cli.getMethods()) {
candidates.add(candidate.getMethod().getName());
}
throw new MethodNotFoundException("The method "+methodName+" could not be found in "+cli.toString()+". "+
"Candidates: "+candidates);
}
}
return mi;
}
|
diff --git a/src/de/_13ducks/cor/game/server/movement/SubSectorPathfinder.java b/src/de/_13ducks/cor/game/server/movement/SubSectorPathfinder.java
index 5326b28..afbe6a8 100644
--- a/src/de/_13ducks/cor/game/server/movement/SubSectorPathfinder.java
+++ b/src/de/_13ducks/cor/game/server/movement/SubSectorPathfinder.java
@@ -1,293 +1,296 @@
/*
* Copyright 2008, 2009, 2010, 2011:
* Tobias Fleig (tfg[AT]online[DOT]de),
* Michael Haas (mekhar[AT]gmx[DOT]de),
* Johannes Kattinger (johanneskattinger[AT]gmx[DOT]de)
*
* - All rights reserved -
*
*
* This file is part of Centuries of Rage.
*
* Centuries of Rage 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.
*
* Centuries of Rage 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 Centuries of Rage. If not, see <http://www.gnu.org/licenses/>.
*
*/
package de._13ducks.cor.game.server.movement;
import de._13ducks.cor.game.Moveable;
import de._13ducks.cor.game.SimplePosition;
import de._13ducks.cor.game.server.Server;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.collections.buffer.PriorityBuffer;
/**
* Dieser Pathfinder sucht Wege innerhalb von freien Flächen um (bewegliche)
* Hindernisse herum.
*/
public class SubSectorPathfinder {
/**
* Sucht einen Weg auf Freiflächen (FreePolygon) um ein Hindernis herum.
* Beachtet weitere Hindernisse auf der "Umleitung".
* Sucht die Route nur bis zum nächsten Ziel.
* Der Mover darf sich nicht bereits auf einer Umleitung befinden,
* diese muss ggf vorher gelöscht worden sein.
* @param mover
* @param obstacle
* @return
*/
static List<SubSectorEdge> searchDiversion(Moveable mover, Moveable obstacle, SimplePosition target) {
/**
* Wegsuche in 2 Schritten:
* 1. Aufbauen eines geeigneten Graphen, der das gesamte Problem enthält.
* 2. Suchen einer Route in diesem Graphen mittels A* (A-Star).
*/
// Aufbauen des Graphen:
ArrayList<SubSectorObstacle> graph = new ArrayList<SubSectorObstacle>(); // Der Graph selber
LinkedList<Moveable> openObstacles = new LinkedList<Moveable>(); // Die Liste mit noch zu untersuchenden Knoten
ArrayList<Moveable> closedObstacles = new ArrayList<Moveable>(); // Bearbeitete Knoten
openObstacles.add(obstacle); // Startpunkt des Graphen.
closedObstacles.add(mover); // Wird im Graphen nicht mitberücksichtigt.
double radius = mover.getRadius() + ServerBehaviourMove.MIN_DISTANCE;
while (!openObstacles.isEmpty()) {
// Neues Element aus der Liste holen und als bearbeitet markieren.
Moveable work = openObstacles.poll();
closedObstacles.add(work);
SubSectorObstacle next = new SubSectorObstacle(work.getPrecisePosition().x(), work.getPrecisePosition().y(), work.getRadius());
// Zuerst alle Punkte des Graphen löschen, die jetzt nichtmehr erreichbar sind:
for (SubSectorObstacle obst : graph) {
obst.removeNearNodes(next, radius);
}
// Mit Graph vernetzen
for (SubSectorObstacle node : graph) {
if (node.inColRange(next, radius)) {
// Schnittpunkte suchen
SubSectorNode[] intersections = node.calcIntersections(next, radius);
for (SubSectorNode n2 : intersections) {
boolean reachable = true;
for (SubSectorObstacle o : graph) {
+ if (o.equals(node)) {
+ continue; // Um den gehts jetzt ja gerade, natürlich liegen wir auf diesem Kreis
+ }
if (o.moveCircleContains(n2, radius)) {
reachable = false;
break;
}
}
if (reachable) {
// Schnittpunkt einbauen
next.addNode(n2);
node.addNode(n2);
}
}
}
}
// Bearbeitetes selbst in Graph einfügen
graph.add(next);
// Weitere Hindernisse suchen, die jetzt relevant sind.
List<Moveable> moversAround = Server.getInnerServer().moveMan.moveMap.moversAround(work, (work.getRadius() + radius) * 2);
for (Moveable pmove : moversAround) {
if (!closedObstacles.contains(pmove) && !openObstacles.contains(pmove)) {
openObstacles.add(pmove);
}
}
}
// Jetzt drüber laufen und Graph aufbauen:
for (SubSectorObstacle obst : graph) {
// Vorgensweise:
// In jedem Hinderniss die Linie entlanglaufen und Knoten mit Kanten verbinden.
// Ein Knoten darf auf einem Kreis immer nur in eine Richtung gehen.
// (das sollte mithilfe seiner beiden, bekannten hindernisse recht einfach sein)
// Die Länge des Kreissegments lässt sich einfach mithilfe des winkels ausrechnen (Math.atan2(y,x)
// Dann darf der A*. Bzw. Dijkstra, A* ist hier schon fast Overkill.
// Alle Knoten ihrem Bogenmaß nach sortieren.
obst.sortNodes();
obst.interConnectNodes(radius);
}
// Start- und Zielknoten einbauen und mit dem Graph vernetzten.
SubSectorNode startNode = new SubSectorNode(mover.getPrecisePosition().x(), mover.getPrecisePosition().y());
SubSectorNode targetNode = new SubSectorNode(target.x(), target.y());
double min = Double.POSITIVE_INFINITY;
SubSectorObstacle minObstacle = null;
for (SubSectorObstacle obst : graph) {
double newdist = Math.sqrt((obst.getX() - startNode.getX()) * (obst.getX() - startNode.getX()) + (obst.getY() - startNode.getY()) * (obst.getY() - startNode.getY()));
newdist -= obst.getRadius() + radius; // Es interessiert uns der nächstmögliche Kreis, nicht das nächste Hinderniss
if (newdist < min) {
min = newdist;
minObstacle = obst;
}
}
// Punkt auf Laufkreis finden
Vector direct = new Vector(startNode.getX() - minObstacle.getX(), startNode.getY() - minObstacle.getY());
direct = direct.normalize().multiply(minObstacle.getRadius() + radius);
SubSectorNode minNode = new SubSectorNode(minObstacle.getX() + direct.getX(), minObstacle.getY() + direct.getY(), minObstacle);
// In das Hinderniss integrieren:
minObstacle.lateIntegrateNode(minNode);
SubSectorEdge startEdge = new SubSectorEdge(startNode, minNode, min);
if (!startNode.equals(minNode)) {
startNode.addEdge(startEdge);
minNode.addEdge(startEdge);
} else {
// Wir stehen schon auf dem minNode.
// Die Einsprungkante ist nicht notwendig.
startNode = minNode;
}
double min2 = Double.POSITIVE_INFINITY;
SubSectorObstacle minObstacle2 = null;
for (SubSectorObstacle obst : graph) {
double newdist = Math.sqrt((obst.getX() - targetNode.getX()) * (obst.getX() - targetNode.getX()) + (obst.getY() - targetNode.getY()) * (obst.getY() - targetNode.getY()));
newdist -= obst.getRadius() + radius; // Es interessiert uns der nächstmögliche Kreis, nicht das nächste Hinderniss
if (newdist < min2) {
min2 = newdist;
minObstacle2 = obst;
}
}
// Punkt auf Laufkreis finden
Vector direct2 = new Vector(targetNode.getX() - minObstacle2.getX(), targetNode.getY() - minObstacle2.getY());
direct2 = direct2.normalize().multiply(minObstacle2.getRadius() + radius);
SubSectorNode minNode2 = new SubSectorNode(minObstacle2.getX() + direct2.getX(), minObstacle2.getY() + direct2.getY(), minObstacle2);
// In das Hinderniss integrieren:
minObstacle2.lateIntegrateNode(minNode2);
SubSectorEdge targetEdge = new SubSectorEdge(minNode2, targetNode, min2);
if (!targetNode.equals(minNode2)) {
targetNode.addEdge(targetEdge);
minNode2.addEdge(targetEdge);
} else {
// Das Ziel ist schon auf dem Laufkreis.
// Die Aussprungkante ist nicht nötig.
System.out.println("RREF");
targetNode = minNode2;
}
/**
* Hier jetzt einen Weg suchen von startNode nach targetNode.
* Die Kanten sind in node.myEdges
* Die Ziele bekommt man mit edge.getOther(startNode)
* Die Länge (Wegkosten) stehen in edge.length (vorsicht: double-Wert!)
*/
PriorityBuffer open = new PriorityBuffer(); // Liste für entdeckte Knoten
LinkedHashSet<SubSectorNode> containopen = new LinkedHashSet<SubSectorNode>(); // Auch für entdeckte Knoten, hiermit kann viel schneller festgestellt werden, ob ein bestimmter Knoten schon enthalten ist.
LinkedHashSet<SubSectorNode> closed = new LinkedHashSet<SubSectorNode>(); // Liste für fertig bearbeitete Knoten
double cost_t = 0; //Movement Kosten (gerade 5, diagonal 7, wird später festgelegt)
open.add(startNode);
while (open.size() > 0) {
SubSectorNode current = (SubSectorNode) open.remove();
containopen.remove(current);
if (current.equals(targetNode)) { //Abbruch, weil Weg von Start nach Ziel gefunden wurde
//targetNode.setParent(current.getParent()); //"Vorgängerfeld" von Ziel bekannt
break;
}
// Aus der open wurde current bereits gelöscht, jetzt in die closed verschieben
closed.add(current);
ArrayList<SubSectorEdge> neighbors = current.getMyEdges();
for (SubSectorEdge edge : neighbors) {
SubSectorNode node = edge.getOther(current);
if (closed.contains(node)) {
continue;
}
// Kosten dort hin berechnen
cost_t = edge.getLength();
if (containopen.contains(node)) { //Wenn sich der Knoten in der openlist befindet, muss berechnet werden, ob es einen kürzeren Weg gibt
if (current.getCost() + cost_t < node.getCost()) { //kürzerer Weg gefunden?
node.setCost(current.getCost() + cost_t); //-> Wegkosten neu berechnen
//node.setValF(node.cost + node.getHeuristic()); //F-Wert, besteht aus Wegkosten vom Start + Luftlinie zum Ziel
node.setParent(current); //aktuelles Feld wird zum Vorgängerfeld
}
} else {
node.setCost(current.getCost() + cost_t);
//node.setHeuristic(Math.sqrt(Math.pow(Math.abs((targetNode.getX() - node.getX())), 2) + Math.pow(Math.abs((targetNode.getY() - node.getY())), 2))); // geschätzte Distanz zum Ziel
//Die Zahl am Ende der Berechnung ist der Aufwand der Wegsuche
//5 ist schnell, 4 normal, 3 dauert lange
node.setParent(current); // Parent ist die RogPosition, von dem der aktuelle entdeckt wurde
//node.setValF(node.cost + node.getHeuristic()); //F-Wert, besteht aus Wegkosten vom Start aus + Luftlinie zum Ziel
open.add(node); // in openlist hinzufügen
containopen.add(node);
}
}
}
if (targetNode.getParent() == null) { //kein Weg gefunden
return null;
}
ArrayList<SubSectorNode> pathrev = new ArrayList<SubSectorNode>(); //Pfad aus parents erstellen, von Ziel nach Start
while (!targetNode.equals(startNode)) {
pathrev.add(targetNode);
targetNode = targetNode.getParent();
}
pathrev.add(startNode);
ArrayList<SubSectorNode> path = new ArrayList<SubSectorNode>(); //Pfad umkehren, sodass er von Start nach Ziel ist
for (int k = pathrev.size() - 1; k >= 0; k--) {
path.add(pathrev.get(k));
}
// Nachbearbeitung:
// Wir brauchen eine Kanten-Liste mit arc/direct Informationen
ArrayList<SubSectorEdge> finalPath = new ArrayList<SubSectorEdge>();
for (int i = 0; i < path.size() - 1; i++) {
SubSectorNode from = path.get(i);
SubSectorNode to = path.get(i + 1);
finalPath.add(shortestCommonEdge(from, to));
}
return finalPath; //Pfad zurückgeben
}
private static SubSectorEdge shortestCommonEdge(SubSectorNode from, SubSectorNode to) {
ArrayList<SubSectorEdge> toEdges = to.getMyEdges();
SubSectorEdge shortesCommon = null;
double minLength = Double.POSITIVE_INFINITY;
for (SubSectorEdge edge : from.getMyEdges()) {
if (toEdges.contains(edge)) {
if (edge.getLength() < minLength) {
shortesCommon = edge;
minLength = edge.getLength();
}
}
}
return shortesCommon;
}
}
| true | true | static List<SubSectorEdge> searchDiversion(Moveable mover, Moveable obstacle, SimplePosition target) {
/**
* Wegsuche in 2 Schritten:
* 1. Aufbauen eines geeigneten Graphen, der das gesamte Problem enthält.
* 2. Suchen einer Route in diesem Graphen mittels A* (A-Star).
*/
// Aufbauen des Graphen:
ArrayList<SubSectorObstacle> graph = new ArrayList<SubSectorObstacle>(); // Der Graph selber
LinkedList<Moveable> openObstacles = new LinkedList<Moveable>(); // Die Liste mit noch zu untersuchenden Knoten
ArrayList<Moveable> closedObstacles = new ArrayList<Moveable>(); // Bearbeitete Knoten
openObstacles.add(obstacle); // Startpunkt des Graphen.
closedObstacles.add(mover); // Wird im Graphen nicht mitberücksichtigt.
double radius = mover.getRadius() + ServerBehaviourMove.MIN_DISTANCE;
while (!openObstacles.isEmpty()) {
// Neues Element aus der Liste holen und als bearbeitet markieren.
Moveable work = openObstacles.poll();
closedObstacles.add(work);
SubSectorObstacle next = new SubSectorObstacle(work.getPrecisePosition().x(), work.getPrecisePosition().y(), work.getRadius());
// Zuerst alle Punkte des Graphen löschen, die jetzt nichtmehr erreichbar sind:
for (SubSectorObstacle obst : graph) {
obst.removeNearNodes(next, radius);
}
// Mit Graph vernetzen
for (SubSectorObstacle node : graph) {
if (node.inColRange(next, radius)) {
// Schnittpunkte suchen
SubSectorNode[] intersections = node.calcIntersections(next, radius);
for (SubSectorNode n2 : intersections) {
boolean reachable = true;
for (SubSectorObstacle o : graph) {
if (o.moveCircleContains(n2, radius)) {
reachable = false;
break;
}
}
if (reachable) {
// Schnittpunkt einbauen
next.addNode(n2);
node.addNode(n2);
}
}
}
}
// Bearbeitetes selbst in Graph einfügen
graph.add(next);
// Weitere Hindernisse suchen, die jetzt relevant sind.
List<Moveable> moversAround = Server.getInnerServer().moveMan.moveMap.moversAround(work, (work.getRadius() + radius) * 2);
for (Moveable pmove : moversAround) {
if (!closedObstacles.contains(pmove) && !openObstacles.contains(pmove)) {
openObstacles.add(pmove);
}
}
}
// Jetzt drüber laufen und Graph aufbauen:
for (SubSectorObstacle obst : graph) {
// Vorgensweise:
// In jedem Hinderniss die Linie entlanglaufen und Knoten mit Kanten verbinden.
// Ein Knoten darf auf einem Kreis immer nur in eine Richtung gehen.
// (das sollte mithilfe seiner beiden, bekannten hindernisse recht einfach sein)
// Die Länge des Kreissegments lässt sich einfach mithilfe des winkels ausrechnen (Math.atan2(y,x)
// Dann darf der A*. Bzw. Dijkstra, A* ist hier schon fast Overkill.
// Alle Knoten ihrem Bogenmaß nach sortieren.
obst.sortNodes();
obst.interConnectNodes(radius);
}
// Start- und Zielknoten einbauen und mit dem Graph vernetzten.
SubSectorNode startNode = new SubSectorNode(mover.getPrecisePosition().x(), mover.getPrecisePosition().y());
SubSectorNode targetNode = new SubSectorNode(target.x(), target.y());
double min = Double.POSITIVE_INFINITY;
SubSectorObstacle minObstacle = null;
for (SubSectorObstacle obst : graph) {
double newdist = Math.sqrt((obst.getX() - startNode.getX()) * (obst.getX() - startNode.getX()) + (obst.getY() - startNode.getY()) * (obst.getY() - startNode.getY()));
newdist -= obst.getRadius() + radius; // Es interessiert uns der nächstmögliche Kreis, nicht das nächste Hinderniss
if (newdist < min) {
min = newdist;
minObstacle = obst;
}
}
// Punkt auf Laufkreis finden
Vector direct = new Vector(startNode.getX() - minObstacle.getX(), startNode.getY() - minObstacle.getY());
direct = direct.normalize().multiply(minObstacle.getRadius() + radius);
SubSectorNode minNode = new SubSectorNode(minObstacle.getX() + direct.getX(), minObstacle.getY() + direct.getY(), minObstacle);
// In das Hinderniss integrieren:
minObstacle.lateIntegrateNode(minNode);
SubSectorEdge startEdge = new SubSectorEdge(startNode, minNode, min);
if (!startNode.equals(minNode)) {
startNode.addEdge(startEdge);
minNode.addEdge(startEdge);
} else {
// Wir stehen schon auf dem minNode.
// Die Einsprungkante ist nicht notwendig.
startNode = minNode;
}
double min2 = Double.POSITIVE_INFINITY;
SubSectorObstacle minObstacle2 = null;
for (SubSectorObstacle obst : graph) {
double newdist = Math.sqrt((obst.getX() - targetNode.getX()) * (obst.getX() - targetNode.getX()) + (obst.getY() - targetNode.getY()) * (obst.getY() - targetNode.getY()));
newdist -= obst.getRadius() + radius; // Es interessiert uns der nächstmögliche Kreis, nicht das nächste Hinderniss
if (newdist < min2) {
min2 = newdist;
minObstacle2 = obst;
}
}
// Punkt auf Laufkreis finden
Vector direct2 = new Vector(targetNode.getX() - minObstacle2.getX(), targetNode.getY() - minObstacle2.getY());
direct2 = direct2.normalize().multiply(minObstacle2.getRadius() + radius);
SubSectorNode minNode2 = new SubSectorNode(minObstacle2.getX() + direct2.getX(), minObstacle2.getY() + direct2.getY(), minObstacle2);
// In das Hinderniss integrieren:
minObstacle2.lateIntegrateNode(minNode2);
SubSectorEdge targetEdge = new SubSectorEdge(minNode2, targetNode, min2);
if (!targetNode.equals(minNode2)) {
targetNode.addEdge(targetEdge);
minNode2.addEdge(targetEdge);
} else {
// Das Ziel ist schon auf dem Laufkreis.
// Die Aussprungkante ist nicht nötig.
System.out.println("RREF");
targetNode = minNode2;
}
/**
* Hier jetzt einen Weg suchen von startNode nach targetNode.
* Die Kanten sind in node.myEdges
* Die Ziele bekommt man mit edge.getOther(startNode)
* Die Länge (Wegkosten) stehen in edge.length (vorsicht: double-Wert!)
*/
PriorityBuffer open = new PriorityBuffer(); // Liste für entdeckte Knoten
LinkedHashSet<SubSectorNode> containopen = new LinkedHashSet<SubSectorNode>(); // Auch für entdeckte Knoten, hiermit kann viel schneller festgestellt werden, ob ein bestimmter Knoten schon enthalten ist.
LinkedHashSet<SubSectorNode> closed = new LinkedHashSet<SubSectorNode>(); // Liste für fertig bearbeitete Knoten
double cost_t = 0; //Movement Kosten (gerade 5, diagonal 7, wird später festgelegt)
open.add(startNode);
while (open.size() > 0) {
SubSectorNode current = (SubSectorNode) open.remove();
containopen.remove(current);
if (current.equals(targetNode)) { //Abbruch, weil Weg von Start nach Ziel gefunden wurde
//targetNode.setParent(current.getParent()); //"Vorgängerfeld" von Ziel bekannt
break;
}
// Aus der open wurde current bereits gelöscht, jetzt in die closed verschieben
closed.add(current);
ArrayList<SubSectorEdge> neighbors = current.getMyEdges();
for (SubSectorEdge edge : neighbors) {
SubSectorNode node = edge.getOther(current);
if (closed.contains(node)) {
continue;
}
// Kosten dort hin berechnen
cost_t = edge.getLength();
if (containopen.contains(node)) { //Wenn sich der Knoten in der openlist befindet, muss berechnet werden, ob es einen kürzeren Weg gibt
if (current.getCost() + cost_t < node.getCost()) { //kürzerer Weg gefunden?
node.setCost(current.getCost() + cost_t); //-> Wegkosten neu berechnen
//node.setValF(node.cost + node.getHeuristic()); //F-Wert, besteht aus Wegkosten vom Start + Luftlinie zum Ziel
node.setParent(current); //aktuelles Feld wird zum Vorgängerfeld
}
} else {
node.setCost(current.getCost() + cost_t);
//node.setHeuristic(Math.sqrt(Math.pow(Math.abs((targetNode.getX() - node.getX())), 2) + Math.pow(Math.abs((targetNode.getY() - node.getY())), 2))); // geschätzte Distanz zum Ziel
//Die Zahl am Ende der Berechnung ist der Aufwand der Wegsuche
//5 ist schnell, 4 normal, 3 dauert lange
node.setParent(current); // Parent ist die RogPosition, von dem der aktuelle entdeckt wurde
//node.setValF(node.cost + node.getHeuristic()); //F-Wert, besteht aus Wegkosten vom Start aus + Luftlinie zum Ziel
open.add(node); // in openlist hinzufügen
containopen.add(node);
}
}
}
if (targetNode.getParent() == null) { //kein Weg gefunden
return null;
}
ArrayList<SubSectorNode> pathrev = new ArrayList<SubSectorNode>(); //Pfad aus parents erstellen, von Ziel nach Start
while (!targetNode.equals(startNode)) {
pathrev.add(targetNode);
targetNode = targetNode.getParent();
}
pathrev.add(startNode);
ArrayList<SubSectorNode> path = new ArrayList<SubSectorNode>(); //Pfad umkehren, sodass er von Start nach Ziel ist
for (int k = pathrev.size() - 1; k >= 0; k--) {
path.add(pathrev.get(k));
}
// Nachbearbeitung:
// Wir brauchen eine Kanten-Liste mit arc/direct Informationen
ArrayList<SubSectorEdge> finalPath = new ArrayList<SubSectorEdge>();
for (int i = 0; i < path.size() - 1; i++) {
SubSectorNode from = path.get(i);
SubSectorNode to = path.get(i + 1);
finalPath.add(shortestCommonEdge(from, to));
}
return finalPath; //Pfad zurückgeben
}
| static List<SubSectorEdge> searchDiversion(Moveable mover, Moveable obstacle, SimplePosition target) {
/**
* Wegsuche in 2 Schritten:
* 1. Aufbauen eines geeigneten Graphen, der das gesamte Problem enthält.
* 2. Suchen einer Route in diesem Graphen mittels A* (A-Star).
*/
// Aufbauen des Graphen:
ArrayList<SubSectorObstacle> graph = new ArrayList<SubSectorObstacle>(); // Der Graph selber
LinkedList<Moveable> openObstacles = new LinkedList<Moveable>(); // Die Liste mit noch zu untersuchenden Knoten
ArrayList<Moveable> closedObstacles = new ArrayList<Moveable>(); // Bearbeitete Knoten
openObstacles.add(obstacle); // Startpunkt des Graphen.
closedObstacles.add(mover); // Wird im Graphen nicht mitberücksichtigt.
double radius = mover.getRadius() + ServerBehaviourMove.MIN_DISTANCE;
while (!openObstacles.isEmpty()) {
// Neues Element aus der Liste holen und als bearbeitet markieren.
Moveable work = openObstacles.poll();
closedObstacles.add(work);
SubSectorObstacle next = new SubSectorObstacle(work.getPrecisePosition().x(), work.getPrecisePosition().y(), work.getRadius());
// Zuerst alle Punkte des Graphen löschen, die jetzt nichtmehr erreichbar sind:
for (SubSectorObstacle obst : graph) {
obst.removeNearNodes(next, radius);
}
// Mit Graph vernetzen
for (SubSectorObstacle node : graph) {
if (node.inColRange(next, radius)) {
// Schnittpunkte suchen
SubSectorNode[] intersections = node.calcIntersections(next, radius);
for (SubSectorNode n2 : intersections) {
boolean reachable = true;
for (SubSectorObstacle o : graph) {
if (o.equals(node)) {
continue; // Um den gehts jetzt ja gerade, natürlich liegen wir auf diesem Kreis
}
if (o.moveCircleContains(n2, radius)) {
reachable = false;
break;
}
}
if (reachable) {
// Schnittpunkt einbauen
next.addNode(n2);
node.addNode(n2);
}
}
}
}
// Bearbeitetes selbst in Graph einfügen
graph.add(next);
// Weitere Hindernisse suchen, die jetzt relevant sind.
List<Moveable> moversAround = Server.getInnerServer().moveMan.moveMap.moversAround(work, (work.getRadius() + radius) * 2);
for (Moveable pmove : moversAround) {
if (!closedObstacles.contains(pmove) && !openObstacles.contains(pmove)) {
openObstacles.add(pmove);
}
}
}
// Jetzt drüber laufen und Graph aufbauen:
for (SubSectorObstacle obst : graph) {
// Vorgensweise:
// In jedem Hinderniss die Linie entlanglaufen und Knoten mit Kanten verbinden.
// Ein Knoten darf auf einem Kreis immer nur in eine Richtung gehen.
// (das sollte mithilfe seiner beiden, bekannten hindernisse recht einfach sein)
// Die Länge des Kreissegments lässt sich einfach mithilfe des winkels ausrechnen (Math.atan2(y,x)
// Dann darf der A*. Bzw. Dijkstra, A* ist hier schon fast Overkill.
// Alle Knoten ihrem Bogenmaß nach sortieren.
obst.sortNodes();
obst.interConnectNodes(radius);
}
// Start- und Zielknoten einbauen und mit dem Graph vernetzten.
SubSectorNode startNode = new SubSectorNode(mover.getPrecisePosition().x(), mover.getPrecisePosition().y());
SubSectorNode targetNode = new SubSectorNode(target.x(), target.y());
double min = Double.POSITIVE_INFINITY;
SubSectorObstacle minObstacle = null;
for (SubSectorObstacle obst : graph) {
double newdist = Math.sqrt((obst.getX() - startNode.getX()) * (obst.getX() - startNode.getX()) + (obst.getY() - startNode.getY()) * (obst.getY() - startNode.getY()));
newdist -= obst.getRadius() + radius; // Es interessiert uns der nächstmögliche Kreis, nicht das nächste Hinderniss
if (newdist < min) {
min = newdist;
minObstacle = obst;
}
}
// Punkt auf Laufkreis finden
Vector direct = new Vector(startNode.getX() - minObstacle.getX(), startNode.getY() - minObstacle.getY());
direct = direct.normalize().multiply(minObstacle.getRadius() + radius);
SubSectorNode minNode = new SubSectorNode(minObstacle.getX() + direct.getX(), minObstacle.getY() + direct.getY(), minObstacle);
// In das Hinderniss integrieren:
minObstacle.lateIntegrateNode(minNode);
SubSectorEdge startEdge = new SubSectorEdge(startNode, minNode, min);
if (!startNode.equals(minNode)) {
startNode.addEdge(startEdge);
minNode.addEdge(startEdge);
} else {
// Wir stehen schon auf dem minNode.
// Die Einsprungkante ist nicht notwendig.
startNode = minNode;
}
double min2 = Double.POSITIVE_INFINITY;
SubSectorObstacle minObstacle2 = null;
for (SubSectorObstacle obst : graph) {
double newdist = Math.sqrt((obst.getX() - targetNode.getX()) * (obst.getX() - targetNode.getX()) + (obst.getY() - targetNode.getY()) * (obst.getY() - targetNode.getY()));
newdist -= obst.getRadius() + radius; // Es interessiert uns der nächstmögliche Kreis, nicht das nächste Hinderniss
if (newdist < min2) {
min2 = newdist;
minObstacle2 = obst;
}
}
// Punkt auf Laufkreis finden
Vector direct2 = new Vector(targetNode.getX() - minObstacle2.getX(), targetNode.getY() - minObstacle2.getY());
direct2 = direct2.normalize().multiply(minObstacle2.getRadius() + radius);
SubSectorNode minNode2 = new SubSectorNode(minObstacle2.getX() + direct2.getX(), minObstacle2.getY() + direct2.getY(), minObstacle2);
// In das Hinderniss integrieren:
minObstacle2.lateIntegrateNode(minNode2);
SubSectorEdge targetEdge = new SubSectorEdge(minNode2, targetNode, min2);
if (!targetNode.equals(minNode2)) {
targetNode.addEdge(targetEdge);
minNode2.addEdge(targetEdge);
} else {
// Das Ziel ist schon auf dem Laufkreis.
// Die Aussprungkante ist nicht nötig.
System.out.println("RREF");
targetNode = minNode2;
}
/**
* Hier jetzt einen Weg suchen von startNode nach targetNode.
* Die Kanten sind in node.myEdges
* Die Ziele bekommt man mit edge.getOther(startNode)
* Die Länge (Wegkosten) stehen in edge.length (vorsicht: double-Wert!)
*/
PriorityBuffer open = new PriorityBuffer(); // Liste für entdeckte Knoten
LinkedHashSet<SubSectorNode> containopen = new LinkedHashSet<SubSectorNode>(); // Auch für entdeckte Knoten, hiermit kann viel schneller festgestellt werden, ob ein bestimmter Knoten schon enthalten ist.
LinkedHashSet<SubSectorNode> closed = new LinkedHashSet<SubSectorNode>(); // Liste für fertig bearbeitete Knoten
double cost_t = 0; //Movement Kosten (gerade 5, diagonal 7, wird später festgelegt)
open.add(startNode);
while (open.size() > 0) {
SubSectorNode current = (SubSectorNode) open.remove();
containopen.remove(current);
if (current.equals(targetNode)) { //Abbruch, weil Weg von Start nach Ziel gefunden wurde
//targetNode.setParent(current.getParent()); //"Vorgängerfeld" von Ziel bekannt
break;
}
// Aus der open wurde current bereits gelöscht, jetzt in die closed verschieben
closed.add(current);
ArrayList<SubSectorEdge> neighbors = current.getMyEdges();
for (SubSectorEdge edge : neighbors) {
SubSectorNode node = edge.getOther(current);
if (closed.contains(node)) {
continue;
}
// Kosten dort hin berechnen
cost_t = edge.getLength();
if (containopen.contains(node)) { //Wenn sich der Knoten in der openlist befindet, muss berechnet werden, ob es einen kürzeren Weg gibt
if (current.getCost() + cost_t < node.getCost()) { //kürzerer Weg gefunden?
node.setCost(current.getCost() + cost_t); //-> Wegkosten neu berechnen
//node.setValF(node.cost + node.getHeuristic()); //F-Wert, besteht aus Wegkosten vom Start + Luftlinie zum Ziel
node.setParent(current); //aktuelles Feld wird zum Vorgängerfeld
}
} else {
node.setCost(current.getCost() + cost_t);
//node.setHeuristic(Math.sqrt(Math.pow(Math.abs((targetNode.getX() - node.getX())), 2) + Math.pow(Math.abs((targetNode.getY() - node.getY())), 2))); // geschätzte Distanz zum Ziel
//Die Zahl am Ende der Berechnung ist der Aufwand der Wegsuche
//5 ist schnell, 4 normal, 3 dauert lange
node.setParent(current); // Parent ist die RogPosition, von dem der aktuelle entdeckt wurde
//node.setValF(node.cost + node.getHeuristic()); //F-Wert, besteht aus Wegkosten vom Start aus + Luftlinie zum Ziel
open.add(node); // in openlist hinzufügen
containopen.add(node);
}
}
}
if (targetNode.getParent() == null) { //kein Weg gefunden
return null;
}
ArrayList<SubSectorNode> pathrev = new ArrayList<SubSectorNode>(); //Pfad aus parents erstellen, von Ziel nach Start
while (!targetNode.equals(startNode)) {
pathrev.add(targetNode);
targetNode = targetNode.getParent();
}
pathrev.add(startNode);
ArrayList<SubSectorNode> path = new ArrayList<SubSectorNode>(); //Pfad umkehren, sodass er von Start nach Ziel ist
for (int k = pathrev.size() - 1; k >= 0; k--) {
path.add(pathrev.get(k));
}
// Nachbearbeitung:
// Wir brauchen eine Kanten-Liste mit arc/direct Informationen
ArrayList<SubSectorEdge> finalPath = new ArrayList<SubSectorEdge>();
for (int i = 0; i < path.size() - 1; i++) {
SubSectorNode from = path.get(i);
SubSectorNode to = path.get(i + 1);
finalPath.add(shortestCommonEdge(from, to));
}
return finalPath; //Pfad zurückgeben
}
|
diff --git a/src/com/moroze/snapchat/MainActivity.java b/src/com/moroze/snapchat/MainActivity.java
index ce909b3..1855914 100644
--- a/src/com/moroze/snapchat/MainActivity.java
+++ b/src/com/moroze/snapchat/MainActivity.java
@@ -1,111 +1,111 @@
package com.moroze.snapchat;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.xdatv.xdasdk.Shell;
/*
* Snapchat Keeper by Noah Moroze (https://github.com/nmoroze)
* Shell class borrowed from Adam Outler (see class for licensing info)
* You are free to use this code in a non-commercial context and with attribution to the creator
*/
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void keepSnaps(View v) {
//keep track of any errors that may occur
boolean error=false;
String errorText="";
//when button pressed, sends series of shell commands one by one and prints their output to console for debugging
//this could probably be done a lot nicer, but it works
Shell shell = new Shell();
String mkDirCmds[] = {"su","-c","mkdir /sdcard/Kept_Snaps/"}; //makes a directory for the kept Snaps on the root of the internal storage (nothing happens if folder exists)
String out = shell.sendShellCommand(mkDirCmds);
System.out.println(out);
String cmds[] = {"su","-c","cp /data/data/com.snapchat.android/cache/received_image_snaps/* /sdcard/Kept_Snaps/"}; //copies files from cached snaps to the new folder
out = shell.sendShellCommand(cmds);
System.out.println(out);
- if(!out.isEmpty()) {
+ if(!out.equals("")) {
error=true;
errorText=out;
}
String stripFileCmds[] = {"su","-c","for f in /sdcard/Kept_Snaps/*.nomedia; do mv $f /sdcard/Kept_Snaps/`basename $f .nomedia`; done;"}; //strips files of ".nomedia" extension, leaving plain jpegs
out = shell.sendShellCommand(stripFileCmds);
System.out.println(out);
if(out.equals("\nPermission denied")) {
error=true;
errorText="root";
}
- else if(!out.isEmpty()) {
+ else if(!out.equals("")) {
error=true;
errorText=out;
}
if(error&&errorText.equals("root")) {
alert("Error!", "You do not have root access to your phone, so this app is incompatible. Please do not give a poor rating, as the description states this app will not work if you don't have root.");
}
else if(error) {
alert("Error!","An error occurred! For help, please email the developer ([email protected]) with the following error message: \n"+errorText);
}
else {
alert("Success!", "Check in /sdcard/Kept_Snaps to view any snaps you have kept!");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//automatically generated function for menu
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//no need to check the item, there's only one (a little improper, but okay)
//show about dialog
new AlertDialog.Builder(this)
.setTitle("About")
.setMessage("Snapchat Keeper by Noah Moroze (This app requires root to function)\n\n" +
"This app allows you to permanently keep Snapchat images. To use, simply ensure that snaps have been loaded but not opened (it will say 'press and hold to view' below the snap)." +
"Open this app and press the button. Your unopened snaps will automatically be stored as standard jpeg files under /sdcard/Kept_Snaps.\n" +
"As snaps are expected to be erased, please do not violate someone's privacy and warn them ahead of time if you are storing the image they sent you.")
.setPositiveButton("Okay", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
//nothing to do here
}
}).show();
return true;
}
private void alert(String title, String msg) {
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(msg)
.setPositiveButton("Okay", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
//nothing to do here
}
}).show();
}
}
| false | true | public void keepSnaps(View v) {
//keep track of any errors that may occur
boolean error=false;
String errorText="";
//when button pressed, sends series of shell commands one by one and prints their output to console for debugging
//this could probably be done a lot nicer, but it works
Shell shell = new Shell();
String mkDirCmds[] = {"su","-c","mkdir /sdcard/Kept_Snaps/"}; //makes a directory for the kept Snaps on the root of the internal storage (nothing happens if folder exists)
String out = shell.sendShellCommand(mkDirCmds);
System.out.println(out);
String cmds[] = {"su","-c","cp /data/data/com.snapchat.android/cache/received_image_snaps/* /sdcard/Kept_Snaps/"}; //copies files from cached snaps to the new folder
out = shell.sendShellCommand(cmds);
System.out.println(out);
if(!out.isEmpty()) {
error=true;
errorText=out;
}
String stripFileCmds[] = {"su","-c","for f in /sdcard/Kept_Snaps/*.nomedia; do mv $f /sdcard/Kept_Snaps/`basename $f .nomedia`; done;"}; //strips files of ".nomedia" extension, leaving plain jpegs
out = shell.sendShellCommand(stripFileCmds);
System.out.println(out);
if(out.equals("\nPermission denied")) {
error=true;
errorText="root";
}
else if(!out.isEmpty()) {
error=true;
errorText=out;
}
if(error&&errorText.equals("root")) {
alert("Error!", "You do not have root access to your phone, so this app is incompatible. Please do not give a poor rating, as the description states this app will not work if you don't have root.");
}
else if(error) {
alert("Error!","An error occurred! For help, please email the developer ([email protected]) with the following error message: \n"+errorText);
}
else {
alert("Success!", "Check in /sdcard/Kept_Snaps to view any snaps you have kept!");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//automatically generated function for menu
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//no need to check the item, there's only one (a little improper, but okay)
//show about dialog
new AlertDialog.Builder(this)
.setTitle("About")
.setMessage("Snapchat Keeper by Noah Moroze (This app requires root to function)\n\n" +
"This app allows you to permanently keep Snapchat images. To use, simply ensure that snaps have been loaded but not opened (it will say 'press and hold to view' below the snap)." +
"Open this app and press the button. Your unopened snaps will automatically be stored as standard jpeg files under /sdcard/Kept_Snaps.\n" +
"As snaps are expected to be erased, please do not violate someone's privacy and warn them ahead of time if you are storing the image they sent you.")
.setPositiveButton("Okay", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
//nothing to do here
}
}).show();
return true;
}
private void alert(String title, String msg) {
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(msg)
.setPositiveButton("Okay", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
//nothing to do here
}
}).show();
}
}
| public void keepSnaps(View v) {
//keep track of any errors that may occur
boolean error=false;
String errorText="";
//when button pressed, sends series of shell commands one by one and prints their output to console for debugging
//this could probably be done a lot nicer, but it works
Shell shell = new Shell();
String mkDirCmds[] = {"su","-c","mkdir /sdcard/Kept_Snaps/"}; //makes a directory for the kept Snaps on the root of the internal storage (nothing happens if folder exists)
String out = shell.sendShellCommand(mkDirCmds);
System.out.println(out);
String cmds[] = {"su","-c","cp /data/data/com.snapchat.android/cache/received_image_snaps/* /sdcard/Kept_Snaps/"}; //copies files from cached snaps to the new folder
out = shell.sendShellCommand(cmds);
System.out.println(out);
if(!out.equals("")) {
error=true;
errorText=out;
}
String stripFileCmds[] = {"su","-c","for f in /sdcard/Kept_Snaps/*.nomedia; do mv $f /sdcard/Kept_Snaps/`basename $f .nomedia`; done;"}; //strips files of ".nomedia" extension, leaving plain jpegs
out = shell.sendShellCommand(stripFileCmds);
System.out.println(out);
if(out.equals("\nPermission denied")) {
error=true;
errorText="root";
}
else if(!out.equals("")) {
error=true;
errorText=out;
}
if(error&&errorText.equals("root")) {
alert("Error!", "You do not have root access to your phone, so this app is incompatible. Please do not give a poor rating, as the description states this app will not work if you don't have root.");
}
else if(error) {
alert("Error!","An error occurred! For help, please email the developer ([email protected]) with the following error message: \n"+errorText);
}
else {
alert("Success!", "Check in /sdcard/Kept_Snaps to view any snaps you have kept!");
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//automatically generated function for menu
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//no need to check the item, there's only one (a little improper, but okay)
//show about dialog
new AlertDialog.Builder(this)
.setTitle("About")
.setMessage("Snapchat Keeper by Noah Moroze (This app requires root to function)\n\n" +
"This app allows you to permanently keep Snapchat images. To use, simply ensure that snaps have been loaded but not opened (it will say 'press and hold to view' below the snap)." +
"Open this app and press the button. Your unopened snaps will automatically be stored as standard jpeg files under /sdcard/Kept_Snaps.\n" +
"As snaps are expected to be erased, please do not violate someone's privacy and warn them ahead of time if you are storing the image they sent you.")
.setPositiveButton("Okay", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
//nothing to do here
}
}).show();
return true;
}
private void alert(String title, String msg) {
new AlertDialog.Builder(this)
.setTitle(title)
.setMessage(msg)
.setPositiveButton("Okay", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
//nothing to do here
}
}).show();
}
}
|
diff --git a/src/jku/se/tetris/prototype/RegisterDialog.java b/src/jku/se/tetris/prototype/RegisterDialog.java
index 601aea0..8942166 100644
--- a/src/jku/se/tetris/prototype/RegisterDialog.java
+++ b/src/jku/se/tetris/prototype/RegisterDialog.java
@@ -1,127 +1,127 @@
package jku.se.tetris.prototype;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class RegisterDialog extends JDialog {
private static final long serialVersionUID = -5147339756430909616L;
// ---------------------------------------------------------------------------
public RegisterDialog(JFrame parent) {
super(parent);
// --
setTitle("Register...");
createContent();
pack();
// --
setModal(true);
// --
setLocationRelativeTo(parent);
}
// ---------------------------------------------------------------------------
public void open() {
setVisible(true);
}
public void close() {
setVisible(false);
}
// ---------------------------------------------------------------------------
private void createContent() {
final Container cp = getContentPane();
cp.setPreferredSize(new Dimension(350, 350));
cp.setLayout(new GroupLayout(cp));
// --
final JTextField neubenutzerinput = new JTextField();
final JPasswordField neupasswortinput = new JPasswordField();
final JPasswordField neupasswortcorrinput = new JPasswordField();
// --
JLabel reg = new JLabel("Register");
reg.setFont(getParent().getFont().deriveFont(20f));
reg.setBounds(75, 70, 200, 25);
cp.add(reg);
// --
JLabel neubenutzername = new JLabel("Name");
JLabel neupasswort = new JLabel("Enter a password");
JLabel neupasswortcorr = new JLabel("Retype password");
// --
neubenutzerinput.setBounds(75, 125, 200, 25);
cp.add(neubenutzerinput);
neubenutzerinput.setToolTipText("3 to 20 characters");
neupasswortinput.setBounds(75, 175, 200, 25);
neupasswortinput.setToolTipText("8-character minimum; case sensitive");
cp.add(neupasswortinput);
neubenutzername.setBounds(75, 100, 200, 25);
cp.add(neubenutzername);
neupasswort.setBounds(75, 150, 200, 25);
neupasswortcorr.setBounds(75, 200, 200, 25);
cp.add(neupasswortcorr);
cp.add(neupasswort);
neupasswortcorrinput.setBounds(75, 225, 200, 25);
neupasswortcorrinput.setToolTipText("Retype password");
cp.add(neupasswortcorrinput);
// --
JButton reset = new JButton("Reset");
reset.setBounds(175, 255, 100, 25);
cp.add(reset);
JButton registrieren = new JButton("Register");
registrieren.setBounds(75, 255, 100, 25);
cp.add(registrieren);
// --
reset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
neubenutzerinput.setText("");
neupasswortinput.setText("");
neupasswortcorrinput.setText("");
}
});
// --
registrieren.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String benutzername = neubenutzerinput.getText();
String passwort = new String(neupasswortinput.getPassword());
String passwortwieder = new String(neupasswortinput.getPassword());
if (benutzername.equalsIgnoreCase("Max") && passwort.equalsIgnoreCase(passwortwieder) && passwort.equalsIgnoreCase("Mustermann")) {
neubenutzerinput.setText("");
neupasswortinput.setText("");
neupasswortcorrinput.setText("");
// --
JOptionPane.showMessageDialog(cp.getParent(), "You are now registered.", "Successfully registered", JOptionPane.INFORMATION_MESSAGE);
close();
} else {
String errorMessage = "Sorry, this username is already taken.";
// --
- if (passwort.length() < 8) {
+ if (passwort.length() <= 8) {
errorMessage = "The password you entered does not meet the security standards (minimum of 8 characters).";
} else if (!passwort.equalsIgnoreCase(passwortwieder)) {
errorMessage = "The password confirmation does not match.";
}
// --
JOptionPane.showMessageDialog(cp.getParent(), errorMessage, "Failed to register", JOptionPane.ERROR_MESSAGE);
// --
neubenutzerinput.setText("");
neupasswortinput.setText("");
neupasswortcorrinput.setText("");
}
}
});
}
}
| true | true | private void createContent() {
final Container cp = getContentPane();
cp.setPreferredSize(new Dimension(350, 350));
cp.setLayout(new GroupLayout(cp));
// --
final JTextField neubenutzerinput = new JTextField();
final JPasswordField neupasswortinput = new JPasswordField();
final JPasswordField neupasswortcorrinput = new JPasswordField();
// --
JLabel reg = new JLabel("Register");
reg.setFont(getParent().getFont().deriveFont(20f));
reg.setBounds(75, 70, 200, 25);
cp.add(reg);
// --
JLabel neubenutzername = new JLabel("Name");
JLabel neupasswort = new JLabel("Enter a password");
JLabel neupasswortcorr = new JLabel("Retype password");
// --
neubenutzerinput.setBounds(75, 125, 200, 25);
cp.add(neubenutzerinput);
neubenutzerinput.setToolTipText("3 to 20 characters");
neupasswortinput.setBounds(75, 175, 200, 25);
neupasswortinput.setToolTipText("8-character minimum; case sensitive");
cp.add(neupasswortinput);
neubenutzername.setBounds(75, 100, 200, 25);
cp.add(neubenutzername);
neupasswort.setBounds(75, 150, 200, 25);
neupasswortcorr.setBounds(75, 200, 200, 25);
cp.add(neupasswortcorr);
cp.add(neupasswort);
neupasswortcorrinput.setBounds(75, 225, 200, 25);
neupasswortcorrinput.setToolTipText("Retype password");
cp.add(neupasswortcorrinput);
// --
JButton reset = new JButton("Reset");
reset.setBounds(175, 255, 100, 25);
cp.add(reset);
JButton registrieren = new JButton("Register");
registrieren.setBounds(75, 255, 100, 25);
cp.add(registrieren);
// --
reset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
neubenutzerinput.setText("");
neupasswortinput.setText("");
neupasswortcorrinput.setText("");
}
});
// --
registrieren.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String benutzername = neubenutzerinput.getText();
String passwort = new String(neupasswortinput.getPassword());
String passwortwieder = new String(neupasswortinput.getPassword());
if (benutzername.equalsIgnoreCase("Max") && passwort.equalsIgnoreCase(passwortwieder) && passwort.equalsIgnoreCase("Mustermann")) {
neubenutzerinput.setText("");
neupasswortinput.setText("");
neupasswortcorrinput.setText("");
// --
JOptionPane.showMessageDialog(cp.getParent(), "You are now registered.", "Successfully registered", JOptionPane.INFORMATION_MESSAGE);
close();
} else {
String errorMessage = "Sorry, this username is already taken.";
// --
if (passwort.length() < 8) {
errorMessage = "The password you entered does not meet the security standards (minimum of 8 characters).";
} else if (!passwort.equalsIgnoreCase(passwortwieder)) {
errorMessage = "The password confirmation does not match.";
}
// --
JOptionPane.showMessageDialog(cp.getParent(), errorMessage, "Failed to register", JOptionPane.ERROR_MESSAGE);
// --
neubenutzerinput.setText("");
neupasswortinput.setText("");
neupasswortcorrinput.setText("");
}
}
});
}
| private void createContent() {
final Container cp = getContentPane();
cp.setPreferredSize(new Dimension(350, 350));
cp.setLayout(new GroupLayout(cp));
// --
final JTextField neubenutzerinput = new JTextField();
final JPasswordField neupasswortinput = new JPasswordField();
final JPasswordField neupasswortcorrinput = new JPasswordField();
// --
JLabel reg = new JLabel("Register");
reg.setFont(getParent().getFont().deriveFont(20f));
reg.setBounds(75, 70, 200, 25);
cp.add(reg);
// --
JLabel neubenutzername = new JLabel("Name");
JLabel neupasswort = new JLabel("Enter a password");
JLabel neupasswortcorr = new JLabel("Retype password");
// --
neubenutzerinput.setBounds(75, 125, 200, 25);
cp.add(neubenutzerinput);
neubenutzerinput.setToolTipText("3 to 20 characters");
neupasswortinput.setBounds(75, 175, 200, 25);
neupasswortinput.setToolTipText("8-character minimum; case sensitive");
cp.add(neupasswortinput);
neubenutzername.setBounds(75, 100, 200, 25);
cp.add(neubenutzername);
neupasswort.setBounds(75, 150, 200, 25);
neupasswortcorr.setBounds(75, 200, 200, 25);
cp.add(neupasswortcorr);
cp.add(neupasswort);
neupasswortcorrinput.setBounds(75, 225, 200, 25);
neupasswortcorrinput.setToolTipText("Retype password");
cp.add(neupasswortcorrinput);
// --
JButton reset = new JButton("Reset");
reset.setBounds(175, 255, 100, 25);
cp.add(reset);
JButton registrieren = new JButton("Register");
registrieren.setBounds(75, 255, 100, 25);
cp.add(registrieren);
// --
reset.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
neubenutzerinput.setText("");
neupasswortinput.setText("");
neupasswortcorrinput.setText("");
}
});
// --
registrieren.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String benutzername = neubenutzerinput.getText();
String passwort = new String(neupasswortinput.getPassword());
String passwortwieder = new String(neupasswortinput.getPassword());
if (benutzername.equalsIgnoreCase("Max") && passwort.equalsIgnoreCase(passwortwieder) && passwort.equalsIgnoreCase("Mustermann")) {
neubenutzerinput.setText("");
neupasswortinput.setText("");
neupasswortcorrinput.setText("");
// --
JOptionPane.showMessageDialog(cp.getParent(), "You are now registered.", "Successfully registered", JOptionPane.INFORMATION_MESSAGE);
close();
} else {
String errorMessage = "Sorry, this username is already taken.";
// --
if (passwort.length() <= 8) {
errorMessage = "The password you entered does not meet the security standards (minimum of 8 characters).";
} else if (!passwort.equalsIgnoreCase(passwortwieder)) {
errorMessage = "The password confirmation does not match.";
}
// --
JOptionPane.showMessageDialog(cp.getParent(), errorMessage, "Failed to register", JOptionPane.ERROR_MESSAGE);
// --
neubenutzerinput.setText("");
neupasswortinput.setText("");
neupasswortcorrinput.setText("");
}
}
});
}
|
diff --git a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/RepositoryConfiguration.java b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/RepositoryConfiguration.java
index 56268097a..4393519e0 100644
--- a/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/RepositoryConfiguration.java
+++ b/org.eclipse.mylyn.bugzilla.core/src/org/eclipse/mylyn/internal/bugzilla/core/RepositoryConfiguration.java
@@ -1,696 +1,699 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.bugzilla.core;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.eclipse.mylyn.internal.bugzilla.core.IBugzillaConstants.BUGZILLA_REPORT_STATUS;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskOperation;
/**
* Class describing the configuration of products and components for a given Bugzilla installation.
*
* @author Rob Elves
*/
public class RepositoryConfiguration implements Serializable {
private static final long serialVersionUID = -3600257926613730005L;
private String repositoryUrl = "<unknown>"; //$NON-NLS-1$
private final Map<String, ProductEntry> products = new HashMap<String, ProductEntry>();
private final List<String> platforms = new ArrayList<String>();
private final List<String> operatingSystems = new ArrayList<String>();
private final List<String> priorities = new ArrayList<String>();
private final List<String> severities = new ArrayList<String>();
private final List<String> bugStatus = new ArrayList<String>();
private final List<String> openStatusValues = new ArrayList<String>();
private final List<String> resolutionValues = new ArrayList<String>();
private final List<String> keywords = new ArrayList<String>();
// master lists
private final List<String> versions = new ArrayList<String>();
private final List<String> components = new ArrayList<String>();
private final List<String> milestones = new ArrayList<String>();
private final List<BugzillaCustomField> customFields = new ArrayList<BugzillaCustomField>();
private final List<BugzillaFlag> flags = new ArrayList<BugzillaFlag>();
private BugzillaVersion version = BugzillaVersion.MIN_VERSION;
public RepositoryConfiguration() {
super();
}
public void addStatus(String status) {
bugStatus.add(status);
}
public List<String> getStatusValues() {
return bugStatus;
}
public void addResolution(String res) {
resolutionValues.add(res);
}
public List<String> getResolutions() {
return resolutionValues;
}
/**
* Adds a product to the configuration.
*/
public void addProduct(String name) {
if (!products.containsKey(name)) {
ProductEntry product = new ProductEntry(name);
products.put(name, product);
}
}
/**
* Returns an array of names of current products.
*/
public List<String> getProducts() {
ArrayList<String> productList = new ArrayList<String>(products.keySet());
Collections.sort(productList);
return productList;
}
/**
* Returns an array of names of component that exist for a given product or <code>null</code> if the product does
* not exist.
*/
public List<String> getComponents(String product) {
ProductEntry entry = products.get(product);
if (entry != null) {
return entry.getComponents();
} else {
return Collections.emptyList();
}
}
/**
* Returns an array of names of versions that exist for a given product or <code>null</code> if the product does not
* exist.
*/
public List<String> getVersions(String product) {
ProductEntry entry = products.get(product);
if (entry != null) {
return entry.getVersions();
} else {
return Collections.emptyList();
}
}
/**
* Returns an array of names of valid severity values.
*/
public List<String> getSeverities() {
return severities;
}
/**
* Returns an array of names of valid OS values.
*/
public List<String> getOSs() {
return operatingSystems;
}
public void addOS(String os) {
operatingSystems.add(os);
}
/**
* Returns an array of names of valid platform values.
*/
public List<String> getPlatforms() {
return platforms;
}
/**
* Returns an array of names of valid platform values.
*/
public List<String> getPriorities() {
return priorities;
}
/**
* Adds a component to the given product.
*/
public void addComponent(String product, String component) {
if (!components.contains(component)) {
components.add(component);
}
ProductEntry entry = products.get(product);
if (entry == null) {
entry = new ProductEntry(product);
products.put(product, entry);
}
entry.addComponent(component);
}
public void addVersion(String product, String version) {
if (!versions.contains(version)) {
versions.add(version);
}
ProductEntry entry = products.get(product);
if (entry == null) {
entry = new ProductEntry(product);
products.put(product, entry);
}
entry.addVersion(version);
}
public void addKeyword(String keyword) {
keywords.add(keyword);
}
public List<String> getKeywords() {
return keywords;
}
public void addPlatform(String platform) {
platforms.add(platform);
}
public void addPriority(String priority) {
priorities.add(priority);
}
public void addSeverity(String severity) {
severities.add(severity);
}
public void setInstallVersion(String version) {
this.version = new BugzillaVersion(version);
}
public BugzillaVersion getInstallVersion() {
return version;
}
public void addTargetMilestone(String product, String target) {
if (!milestones.contains(target)) {
milestones.add(target);
}
ProductEntry entry = products.get(product);
if (entry == null) {
entry = new ProductEntry(product);
products.put(product, entry);
}
entry.addTargetMilestone(target);
}
public List<String> getTargetMilestones(String product) {
ProductEntry entry = products.get(product);
if (entry != null) {
return entry.getTargetMilestones();
} else {
return Collections.emptyList();
}
}
/**
* Container for product information: name, components.
*/
private static class ProductEntry implements Serializable {
private static final long serialVersionUID = 4120139521246741120L;
String productName;
List<String> components = new ArrayList<String>();
List<String> versions = new ArrayList<String>();
List<String> milestones = new ArrayList<String>();
ProductEntry(String name) {
this.productName = name;
}
List<String> getComponents() {
return components;
}
void addComponent(String componentName) {
if (!components.contains(componentName)) {
components.add(componentName);
}
}
List<String> getVersions() {
return versions;
}
void addVersion(String name) {
if (!versions.contains(name)) {
versions.add(name);
}
}
List<String> getTargetMilestones() {
return milestones;
}
void addTargetMilestone(String target) {
milestones.add(target);
}
}
public List<String> getOpenStatusValues() {
return openStatusValues;
}
public void addOpenStatusValue(String value) {
openStatusValues.add(value);
}
public List<String> getComponents() {
return components;
}
public List<String> getTargetMilestones() {
return milestones;
}
public List<String> getVersions() {
return versions;
}
public String getRepositoryUrl() {
return repositoryUrl;
}
public void setRepositoryUrl(String repositoryUrl) {
this.repositoryUrl = repositoryUrl;
}
/*
* Intermediate step until configuration is made generic.
*/
public List<String> getOptionValues(BugzillaAttribute element, String product) {
switch (element) {
case PRODUCT:
return getProducts();
case TARGET_MILESTONE:
return getTargetMilestones(product);
case BUG_STATUS:
return getStatusValues();
case VERSION:
return getVersions(product);
case COMPONENT:
return getComponents(product);
case REP_PLATFORM:
return getPlatforms();
case OP_SYS:
return getOSs();
case PRIORITY:
return getPriorities();
case BUG_SEVERITY:
return getSeverities();
case KEYWORDS:
return getKeywords();
case RESOLUTION:
return getResolutions();
default:
return Collections.emptyList();
}
}
/**
* Adds a field to the configuration.
*/
public void addCustomField(BugzillaCustomField newField) {
customFields.add(newField);
}
public List<BugzillaCustomField> getCustomFields() {
return customFields;
}
public void configureTaskData(TaskData taskData) {
if (taskData != null) {
addMissingFlags(taskData);
updateAttributeOptions(taskData);
addValidOperations(taskData);
}
}
private void addMissingFlags(TaskData taskData) {
List<String> existingFlags = new ArrayList<String>();
List<BugzillaFlag> flags = getFlags();
for (TaskAttribute attribute : new HashSet<TaskAttribute>(taskData.getRoot().getAttributes().values())) {
if (attribute.getId().startsWith("task.common.kind.flag")) { //$NON-NLS-1$
TaskAttribute state = attribute.getAttribute("state"); //$NON-NLS-1$
if (state != null) {
String nameValue = state.getMetaData().getLabel();
if (!existingFlags.contains(nameValue)) {
existingFlags.add(nameValue);
}
String desc = attribute.getMetaData().getLabel();
if (desc == null || desc.equals("")) { //$NON-NLS-1$
for (BugzillaFlag bugzillaFlag : flags) {
if (bugzillaFlag.getType().equals("attachment")) { //$NON-NLS-1$
continue;
}
if (bugzillaFlag.getName().equals(nameValue)) {
attribute.getMetaData().setLabel(bugzillaFlag.getDescription());
}
}
}
}
}
}
TaskAttribute productAttribute = taskData.getRoot().getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
TaskAttribute componentAttribute = taskData.getRoot().getMappedAttribute(BugzillaAttribute.COMPONENT.getKey());
for (BugzillaFlag bugzillaFlag : flags) {
if (bugzillaFlag.getType().equals("attachment")) { //$NON-NLS-1$
continue;
}
if (!bugzillaFlag.isUsedIn(productAttribute.getValue(), componentAttribute.getValue())) {
continue;
}
if (existingFlags.contains(bugzillaFlag.getName()) && !bugzillaFlag.isMultiplicable()) {
continue;
}
BugzillaFlagMapper mapper = new BugzillaFlagMapper();
mapper.setRequestee(""); //$NON-NLS-1$
mapper.setSetter(""); //$NON-NLS-1$
mapper.setState(" "); //$NON-NLS-1$
mapper.setFlagId(bugzillaFlag.getName());
mapper.setNumber(0);
mapper.setDescription(bugzillaFlag.getDescription());
TaskAttribute attribute = taskData.getRoot().createAttribute(
"task.common.kind.flag_type" + bugzillaFlag.getFlagId()); //$NON-NLS-1$
mapper.applyTo(attribute);
}
setFlagsRequestee(taskData);
}
private void setFlagsRequestee(TaskData taskData) {
for (TaskAttribute attribute : new HashSet<TaskAttribute>(taskData.getRoot().getAttributes().values())) {
if (attribute.getId().startsWith("task.common.kind.flag")) { //$NON-NLS-1$
TaskAttribute state = attribute.getAttribute("state"); //$NON-NLS-1$
if (state != null) {
String nameValue = state.getMetaData().getLabel();
for (BugzillaFlag bugzillaFlag : flags) {
if (nameValue.equals(bugzillaFlag.getName())) {
TaskAttribute requestee = attribute.getAttribute("requestee"); //$NON-NLS-1$
if (requestee == null) {
requestee = attribute.createMappedAttribute("requestee"); //$NON-NLS-1$
requestee.getMetaData().defaults().setType(TaskAttribute.TYPE_SHORT_TEXT);
requestee.setValue(""); //$NON-NLS-1$
}
requestee.getMetaData().setReadOnly(!bugzillaFlag.isSpecifically_requestable());
}
}
}
}
}
}
public void updateAttributeOptions(TaskData existingReport) {
TaskAttribute attributeProduct = existingReport.getRoot()
.getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
if (attributeProduct == null) {
return;
}
String product = attributeProduct.getValue();
for (TaskAttribute attribute : new HashSet<TaskAttribute>(existingReport.getRoot().getAttributes().values())) {
List<String> optionValues = getAttributeOptions(product, attribute);
if (attribute.getId().equals(BugzillaAttribute.TARGET_MILESTONE.getKey()) && optionValues.isEmpty()) {
existingReport.getRoot().removeAttribute(BugzillaAttribute.TARGET_MILESTONE.getKey());
continue;
}
if (attribute.getId().startsWith("task.common.kind.flag")) { //$NON-NLS-1$
attribute = attribute.getAttribute("state"); //$NON-NLS-1$
}
attribute.clearOptions();
for (String option : optionValues) {
attribute.putOption(option, option);
}
}
}
public List<String> getAttributeOptions(String product, TaskAttribute attribute) {
List<String> options = new ArrayList<String>();
if (attribute.getId().startsWith(BugzillaCustomField.CUSTOM_FIELD_PREFIX)) {
for (BugzillaCustomField bugzillaCustomField : customFields) {
if (bugzillaCustomField.getName().equals(attribute.getId())) {
options = bugzillaCustomField.getOptions();
break;
}
}
} else if (attribute.getId().startsWith("task.common.kind.flag")) { //$NON-NLS-1$
TaskAttribute state = attribute.getAttribute("state"); //$NON-NLS-1$
if (state != null) {
String nameValue = state.getMetaData().getLabel();
options.add(""); //$NON-NLS-1$
for (BugzillaFlag bugzillaFlag : flags) {
if (nameValue.equals(bugzillaFlag.getName())) {
if (nameValue.equals(bugzillaFlag.getName())) {
if (bugzillaFlag.isRequestable()) {
options.add("?"); //$NON-NLS-1$
}
break;
}
}
}
options.add("+"); //$NON-NLS-1$
options.add("-"); //$NON-NLS-1$
}
}
else {
String type = attribute.getMetaData().getType();
if (type != null && type.equals(IBugzillaConstants.EDITOR_TYPE_FLAG)) {
options.add(""); //$NON-NLS-1$
options.add("?"); //$NON-NLS-1$
options.add("+"); //$NON-NLS-1$
options.add("-"); //$NON-NLS-1$
} else {
BugzillaAttribute element;
try {
element = BugzillaAttribute.valueOf(attribute.getId().trim().toUpperCase(Locale.ENGLISH));
} catch (RuntimeException e) {
if (e instanceof IllegalArgumentException) {
// ignore unrecognized tags
return options;
}
throw e;
}
options = getOptionValues(element, product);
if (element != BugzillaAttribute.RESOLUTION && element != BugzillaAttribute.OP_SYS
&& element != BugzillaAttribute.BUG_SEVERITY && element != BugzillaAttribute.PRIORITY
&& element != BugzillaAttribute.BUG_STATUS) {
Collections.sort(options);
}
}
}
return options;
}
public void addValidOperations(TaskData bugReport) {
TaskAttribute attributeStatus = bugReport.getRoot().getMappedAttribute(TaskAttribute.STATUS);
BUGZILLA_REPORT_STATUS status = BUGZILLA_REPORT_STATUS.NEW;
if (attributeStatus != null) {
try {
status = BUGZILLA_REPORT_STATUS.valueOf(attributeStatus.getValue());
} catch (RuntimeException e) {
// StatusHandler.log(new Status(IStatus.INFO, BugzillaCorePlugin.PLUGIN_ID, "Unrecognized status: "
// + attributeStatus.getValue(), e));
status = BUGZILLA_REPORT_STATUS.NEW;
}
}
BugzillaVersion bugzillaVersion = getInstallVersion();
if (bugzillaVersion == null) {
bugzillaVersion = BugzillaVersion.MIN_VERSION;
}
switch (status) {
case UNCONFIRMED:
case REOPENED:
case NEW:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.accept);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case ASSIGNED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case RESOLVED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.verify);
addOperation(bugReport, BugzillaOperation.close);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
+ addOperation(bugReport, BugzillaOperation.resolve);
}
break;
case CLOSED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
+ addOperation(bugReport, BugzillaOperation.resolve);
}
break;
case VERIFIED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.close);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
+ addOperation(bugReport, BugzillaOperation.resolve);
}
}
if (bugzillaVersion.compareTo(BugzillaVersion.BUGZILLA_3_0) < 0) {
// Product change is only supported for Versions >= 3.0 without verify html page
TaskAttribute productAttribute = bugReport.getRoot().getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
productAttribute.getMetaData().setReadOnly(true);
}
if (status == BUGZILLA_REPORT_STATUS.NEW || status == BUGZILLA_REPORT_STATUS.ASSIGNED
|| status == BUGZILLA_REPORT_STATUS.REOPENED || status == BUGZILLA_REPORT_STATUS.UNCONFIRMED) {
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) <= 0) {
// old bugzilla workflow is used
addOperation(bugReport, BugzillaOperation.reassign);
addOperation(bugReport, BugzillaOperation.reassignbycomponent);
} else {
BugzillaAttribute key = BugzillaAttribute.SET_DEFAULT_ASSIGNEE;
TaskAttribute operationAttribute = bugReport.getRoot().getAttribute(key.getKey());
if (operationAttribute == null) {
operationAttribute = bugReport.getRoot().createAttribute(key.getKey());
operationAttribute.getMetaData()
.defaults()
.setReadOnly(key.isReadOnly())
.setKind(key.getKind())
.setLabel(key.toString())
.setType(key.getType());
operationAttribute.setValue("0"); //$NON-NLS-1$
}
operationAttribute = bugReport.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED);
if (operationAttribute != null) {
operationAttribute.getMetaData().setReadOnly(false);
}
}
}
}
public void addOperation(TaskData bugReport, BugzillaOperation opcode) {
TaskAttribute attribute;
TaskAttribute operationAttribute = bugReport.getRoot().getAttribute(TaskAttribute.OPERATION);
if (operationAttribute == null) {
operationAttribute = bugReport.getRoot().createAttribute(TaskAttribute.OPERATION);
}
switch (opcode) {
case none:
attribute = bugReport.getRoot().createAttribute(TaskAttribute.PREFIX_OPERATION + opcode.toString());
String label = "Leave"; //$NON-NLS-1$
TaskAttribute attributeStatus = bugReport.getRoot().getMappedAttribute(TaskAttribute.STATUS);
TaskAttribute attributeResolution = bugReport.getRoot().getMappedAttribute(TaskAttribute.RESOLUTION);
if (attributeStatus != null && attributeResolution != null) {
label = String.format(opcode.getLabel(), attributeStatus.getValue(), attributeResolution.getValue());
}
TaskOperation.applyTo(attribute, opcode.toString(), label);
// set as default
TaskOperation.applyTo(operationAttribute, opcode.toString(), label);
break;
case resolve:
attribute = bugReport.getRoot().createAttribute(TaskAttribute.PREFIX_OPERATION + opcode.toString());
TaskOperation.applyTo(attribute, opcode.toString(), opcode.getLabel());
TaskAttribute attrResolvedInput = attribute.getTaskData().getRoot().createAttribute(opcode.getInputId());
attrResolvedInput.getMetaData().setType(opcode.getInputType());
attribute.getMetaData().putValue(TaskAttribute.META_ASSOCIATED_ATTRIBUTE_ID, opcode.getInputId());
for (String resolution : getResolutions()) {
// DUPLICATE and MOVED have special meanings so do not show as resolution
if (resolution.compareTo("DUPLICATE") != 0 && resolution.compareTo("MOVED") != 0) { //$NON-NLS-1$ //$NON-NLS-2$
attrResolvedInput.putOption(resolution, resolution);
}
}
if (getResolutions().size() > 0) {
attrResolvedInput.setValue(getResolutions().get(0));
}
break;
default:
attribute = bugReport.getRoot().createAttribute(TaskAttribute.PREFIX_OPERATION + opcode.toString());
TaskOperation.applyTo(attribute, opcode.toString(), opcode.getLabel());
if (opcode.getInputId() != null) {
TaskAttribute attrInput = bugReport.getRoot().createAttribute(opcode.getInputId());
attrInput.getMetaData().defaults().setReadOnly(false).setType(opcode.getInputType());
attribute.getMetaData().putValue(TaskAttribute.META_ASSOCIATED_ATTRIBUTE_ID, opcode.getInputId());
}
break;
}
}
/**
* Adds a flag to the configuration.
*/
public void addFlag(BugzillaFlag newFlag) {
flags.add(newFlag);
}
public List<BugzillaFlag> getFlags() {
return flags;
}
public BugzillaFlag getFlagWithId(Integer id) {
for (BugzillaFlag bugzillaFlag : flags) {
if (bugzillaFlag.getFlagId() == id) {
return bugzillaFlag;
}
}
return null;
}
}
| false | true | public void addValidOperations(TaskData bugReport) {
TaskAttribute attributeStatus = bugReport.getRoot().getMappedAttribute(TaskAttribute.STATUS);
BUGZILLA_REPORT_STATUS status = BUGZILLA_REPORT_STATUS.NEW;
if (attributeStatus != null) {
try {
status = BUGZILLA_REPORT_STATUS.valueOf(attributeStatus.getValue());
} catch (RuntimeException e) {
// StatusHandler.log(new Status(IStatus.INFO, BugzillaCorePlugin.PLUGIN_ID, "Unrecognized status: "
// + attributeStatus.getValue(), e));
status = BUGZILLA_REPORT_STATUS.NEW;
}
}
BugzillaVersion bugzillaVersion = getInstallVersion();
if (bugzillaVersion == null) {
bugzillaVersion = BugzillaVersion.MIN_VERSION;
}
switch (status) {
case UNCONFIRMED:
case REOPENED:
case NEW:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.accept);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case ASSIGNED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case RESOLVED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.verify);
addOperation(bugReport, BugzillaOperation.close);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
}
break;
case CLOSED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
}
break;
case VERIFIED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.close);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
}
}
if (bugzillaVersion.compareTo(BugzillaVersion.BUGZILLA_3_0) < 0) {
// Product change is only supported for Versions >= 3.0 without verify html page
TaskAttribute productAttribute = bugReport.getRoot().getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
productAttribute.getMetaData().setReadOnly(true);
}
if (status == BUGZILLA_REPORT_STATUS.NEW || status == BUGZILLA_REPORT_STATUS.ASSIGNED
|| status == BUGZILLA_REPORT_STATUS.REOPENED || status == BUGZILLA_REPORT_STATUS.UNCONFIRMED) {
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) <= 0) {
// old bugzilla workflow is used
addOperation(bugReport, BugzillaOperation.reassign);
addOperation(bugReport, BugzillaOperation.reassignbycomponent);
} else {
BugzillaAttribute key = BugzillaAttribute.SET_DEFAULT_ASSIGNEE;
TaskAttribute operationAttribute = bugReport.getRoot().getAttribute(key.getKey());
if (operationAttribute == null) {
operationAttribute = bugReport.getRoot().createAttribute(key.getKey());
operationAttribute.getMetaData()
.defaults()
.setReadOnly(key.isReadOnly())
.setKind(key.getKind())
.setLabel(key.toString())
.setType(key.getType());
operationAttribute.setValue("0"); //$NON-NLS-1$
}
operationAttribute = bugReport.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED);
if (operationAttribute != null) {
operationAttribute.getMetaData().setReadOnly(false);
}
}
}
}
| public void addValidOperations(TaskData bugReport) {
TaskAttribute attributeStatus = bugReport.getRoot().getMappedAttribute(TaskAttribute.STATUS);
BUGZILLA_REPORT_STATUS status = BUGZILLA_REPORT_STATUS.NEW;
if (attributeStatus != null) {
try {
status = BUGZILLA_REPORT_STATUS.valueOf(attributeStatus.getValue());
} catch (RuntimeException e) {
// StatusHandler.log(new Status(IStatus.INFO, BugzillaCorePlugin.PLUGIN_ID, "Unrecognized status: "
// + attributeStatus.getValue(), e));
status = BUGZILLA_REPORT_STATUS.NEW;
}
}
BugzillaVersion bugzillaVersion = getInstallVersion();
if (bugzillaVersion == null) {
bugzillaVersion = BugzillaVersion.MIN_VERSION;
}
switch (status) {
case UNCONFIRMED:
case REOPENED:
case NEW:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.accept);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case ASSIGNED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.resolve);
addOperation(bugReport, BugzillaOperation.duplicate);
break;
case RESOLVED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.verify);
addOperation(bugReport, BugzillaOperation.close);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
addOperation(bugReport, BugzillaOperation.resolve);
}
break;
case CLOSED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
addOperation(bugReport, BugzillaOperation.resolve);
}
break;
case VERIFIED:
addOperation(bugReport, BugzillaOperation.none);
addOperation(bugReport, BugzillaOperation.reopen);
addOperation(bugReport, BugzillaOperation.close);
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) >= 0) {
addOperation(bugReport, BugzillaOperation.duplicate);
addOperation(bugReport, BugzillaOperation.resolve);
}
}
if (bugzillaVersion.compareTo(BugzillaVersion.BUGZILLA_3_0) < 0) {
// Product change is only supported for Versions >= 3.0 without verify html page
TaskAttribute productAttribute = bugReport.getRoot().getMappedAttribute(BugzillaAttribute.PRODUCT.getKey());
productAttribute.getMetaData().setReadOnly(true);
}
if (status == BUGZILLA_REPORT_STATUS.NEW || status == BUGZILLA_REPORT_STATUS.ASSIGNED
|| status == BUGZILLA_REPORT_STATUS.REOPENED || status == BUGZILLA_REPORT_STATUS.UNCONFIRMED) {
if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_3_0) <= 0) {
// old bugzilla workflow is used
addOperation(bugReport, BugzillaOperation.reassign);
addOperation(bugReport, BugzillaOperation.reassignbycomponent);
} else {
BugzillaAttribute key = BugzillaAttribute.SET_DEFAULT_ASSIGNEE;
TaskAttribute operationAttribute = bugReport.getRoot().getAttribute(key.getKey());
if (operationAttribute == null) {
operationAttribute = bugReport.getRoot().createAttribute(key.getKey());
operationAttribute.getMetaData()
.defaults()
.setReadOnly(key.isReadOnly())
.setKind(key.getKind())
.setLabel(key.toString())
.setType(key.getType());
operationAttribute.setValue("0"); //$NON-NLS-1$
}
operationAttribute = bugReport.getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED);
if (operationAttribute != null) {
operationAttribute.getMetaData().setReadOnly(false);
}
}
}
}
|
diff --git a/src/repository/DiagramDAO.java b/src/repository/DiagramDAO.java
index 211d13a..4198ff0 100644
--- a/src/repository/DiagramDAO.java
+++ b/src/repository/DiagramDAO.java
@@ -1,249 +1,250 @@
package repository;
/**
* @author Yidu Liang
* @author yangchen
*/
import domain.Diagram;
import domain.DiagramType;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DiagramDAO {
/**
* Add Diagram into DB (diagram name, created time, in edition, owner Id, file path)
*
* @param Diagram object
* diagramName, inEdition, ownerId, ecoreFilePath
* @return true if success; false if fail
*/
public static boolean addDiagram(Diagram diagram) {
ResultSet rs;
try {
Connection conn = DbManager.getConnection();
//String sql = "INSERT INTO diagram (diagramName , createdTime , inEdition , owner_Id , filePath) VALUES (?,NOW(),?,?,?);";
//add by Yidu Liang Mar 20 2013
String sql = "insert into diagram (projectId, userId, diagramType, diagramName ,filePath, fileType, merged, notationFileName, notationFilePath, diFlieName, diFilePath)"+
"VALUES (?, ?, ?, ?, ? ,?, ?, ?, ?, ?,? )";
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
//pstmt.setString(1, diagram.getDiagramName());
//pstmt.setBoolean(2, diagram.isInEdition());
//pstmt.setInt(3, diagram.getOwnerId());
//pstmt.setString(4, diagram.getEcoreFilePath());
//System.out.println("diagram upload SQL test");
//System.out.println(diagram.getProjectId());
//System.out.println(diagram.getUserId());
//System.out.println(diagram.getDiagramType());
//System.out.println(diagram.getMerged());
pstmt.setInt(1,diagram.getProjectId()); // this need to be implementing
pstmt.setInt(2,diagram.getUserId());
- pstmt.setString(3,diagram.getDiagramType().toString()); // this need to be implementing
+ pstmt.setString(3,Integer.toString(1)); //Temporary hack to get code to work. Please replace when
+ //diagramType comes into effect @AniketHajirnis
pstmt.setString(4,diagram.getDiagramName()); // this need to be implementing
pstmt.setString(5,diagram.getFilePath()); // this need to be implementing
pstmt.setString(6,diagram.getFileType()); // this need to be implementing
pstmt.setInt(7,diagram.getMerged());
pstmt.setString(8,diagram.getNotationFileName()); // this need to be implementing
pstmt.setString(9,diagram.getNotationFilePath()); // this need to be implementing
pstmt.setString(10,diagram.getDiFileName()); // this need to be implementing
pstmt.setString(11,diagram.getDiFilepath()); // this need to be implementing
pstmt.executeUpdate();
//Get and set the auto-generated PK
rs = pstmt.getGeneratedKeys();
if (rs.next()) {
int newId = rs.getInt(1);
diagram.setDiagramId(newId);
}
rs.close();
pstmt.close();
conn.close();
return true;
} catch (SQLException ex) {
System.out.println("Exception"+ex.getMessage());
Logger.getLogger(DiagramDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
/**
* Get Diagram ArrayList from DB
*
* @param projectId
* The ID of the project
* @return Diagram ArrayList
*/
public static ArrayList<Diagram> getDiagramList(int projectId) {
ArrayList<Diagram> searchResult = new ArrayList<>();
try {
Connection conn = DbManager.getConnection();
String sql = "SELECT * FROM diagram where projectId = ?;";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, projectId);
ResultSet rs = pstmt.executeQuery();
//Initiate a list to get all returned report objects and set attributes
/*
while (rs.next()) {
Diagram diagram = new Diagram();
diagram.setDiagramId(rs.getInt("diagram_Id"));
diagram.setDiagramName(rs.getString("diagramName"));
diagram.setCreatedTime(rs.getString("createdTime"));
diagram.setInEdition(rs.getBoolean("inEdition"));
diagram.setOwnerId(rs.getInt("owner_Id"));
diagram.setEcoreFilePath(rs.getString("filePath"));
searchResult.add(diagram);
}
*/
//add by Yidu Liang Mar22 2013 projectId, userId, diagramType, diagramName, filePath, fileType, notationFileName, notationFilePath, diFileName, diFilePath
while (rs.next()) {
Diagram diagram = new Diagram();
diagram.setDiagramId(rs.getInt("diagramId"));
diagram.setProjectId(rs.getInt("projectId"));
diagram.setUserId(rs.getInt("userId"));
//support for enum type
diagram.setDiagramType(DiagramType.fromString(rs.getString("diagramType")));
diagram.setDiagramName(rs.getString("diagramName"));
diagram.setFilePath(rs.getString("filePath"));
diagram.setFileType(rs.getString("fileType"));
diagram.setNotationFileName(rs.getString("notationFileName"));
diagram.setNotationFilePath(rs.getString("notationFilePath"));
diagram.setDiFilepath(rs.getString("diFilePath"));
diagram.setCreatedTime(rs.getString("createTime"));
searchResult.add(diagram);
}
rs.close();
pstmt.close();
conn.close();
return searchResult;
} catch (SQLException ex) {
Logger.getLogger(DiagramDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Get Diagram from DB
*
* @param diagram_Id
* The ID of the diagram
* @return Diagram object
*/
public static Diagram getDiagram(int diagram_Id) {
try {
Connection conn = DbManager.getConnection();
String sql = "SELECT * FROM diagram WHERE diagramId = ?;";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, diagram_Id);
ResultSet rs = pstmt.executeQuery();
if (!rs.next()) {
return null;
}
Diagram diagram = new Diagram();
diagram.setDiagramId(rs.getInt("diagramId"));
diagram.setProjectId(rs.getInt("projectId"));
diagram.setUserId(rs.getInt("userId"));
//support for enum type
diagram.setDiagramType(DiagramType.fromString(rs.getString("diagramType")));
diagram.setDiagramName(rs.getString("diagramName"));
diagram.setFilePath(rs.getString("filePath"));
diagram.setFileType(rs.getString("fileType"));
diagram.setNotationFileName(rs.getString("notationFileName"));
diagram.setNotationFilePath(rs.getString("notationFilePath"));
diagram.setDiFileName(rs.getString("diFlieName")); // TODO diFlieName typo in DB
diagram.setDiFilepath(rs.getString("diFilePath"));
pstmt.close();
conn.close();
return diagram;
} catch (SQLException ex) {
Logger.getLogger(DiagramDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Update Diagram from DB
*
* @param Diagram object
* projectId, userId, diagramType, diagramName, filePath, fileType, notationFileName, notationFilePath, diFileName, diFilePath
* @return true if success; false if fail
*/
public static boolean updateDiagram(Diagram diagram) {
try {
Connection conn = DbManager.getConnection();
String sql = "UPDATE diagram SET projectId = ?, userId = ?, diagramType = ?, diagramName = ?, filePath = ?, fileType = ?, notationFileName = ?, notationFilePath= ?, diFileName = ?, diFilePath = ? WHERE diagramId = ?;";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1,diagram.getProjectId()); // this need to be implementing
pstmt.setInt(2,diagram.getUserId());
//converted to an enum type to avoid hard coding
pstmt.setString(3,diagram.getDiagramType().toString()); // this need to be implementing
pstmt.setString(4,diagram.getDiagramName()); // this need to be implementing
pstmt.setString(5,diagram.getFilePath()); // this need to be implementing
pstmt.setString(6,diagram.getFileType()); // this need to be implementing
pstmt.setString(7,diagram.getNotationFileName()); // this need to be implementing
pstmt.setString(8,diagram.getNotationFilePath()); // this need to be implementing
pstmt.setString(9,diagram.getDiagramName()); // this need to be implementing
pstmt.setString(10,diagram.getDiFilepath()); // this need to be implementing
pstmt.executeUpdate();
pstmt.close();
conn.close();
return true;
} catch (SQLException ex) {
Logger.getLogger(DiagramDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
/**
* Delete Diagram from DB
*
* @param Diagram object
* @return true if success; false if fail
*/
public static boolean deleteDiagram(Diagram diagram) {
try {
Connection conn = DbManager.getConnection();
String sql = "DELETE FROM diagram WHERE diagram_Id = ?;";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, diagram.getDiagramId());
pstmt.executeUpdate();
pstmt.close();
conn.close();
return true;
} catch (SQLException ex) {
Logger.getLogger(DiagramDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
}
| true | true | public static boolean addDiagram(Diagram diagram) {
ResultSet rs;
try {
Connection conn = DbManager.getConnection();
//String sql = "INSERT INTO diagram (diagramName , createdTime , inEdition , owner_Id , filePath) VALUES (?,NOW(),?,?,?);";
//add by Yidu Liang Mar 20 2013
String sql = "insert into diagram (projectId, userId, diagramType, diagramName ,filePath, fileType, merged, notationFileName, notationFilePath, diFlieName, diFilePath)"+
"VALUES (?, ?, ?, ?, ? ,?, ?, ?, ?, ?,? )";
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
//pstmt.setString(1, diagram.getDiagramName());
//pstmt.setBoolean(2, diagram.isInEdition());
//pstmt.setInt(3, diagram.getOwnerId());
//pstmt.setString(4, diagram.getEcoreFilePath());
//System.out.println("diagram upload SQL test");
//System.out.println(diagram.getProjectId());
//System.out.println(diagram.getUserId());
//System.out.println(diagram.getDiagramType());
//System.out.println(diagram.getMerged());
pstmt.setInt(1,diagram.getProjectId()); // this need to be implementing
pstmt.setInt(2,diagram.getUserId());
pstmt.setString(3,diagram.getDiagramType().toString()); // this need to be implementing
pstmt.setString(4,diagram.getDiagramName()); // this need to be implementing
pstmt.setString(5,diagram.getFilePath()); // this need to be implementing
pstmt.setString(6,diagram.getFileType()); // this need to be implementing
pstmt.setInt(7,diagram.getMerged());
pstmt.setString(8,diagram.getNotationFileName()); // this need to be implementing
pstmt.setString(9,diagram.getNotationFilePath()); // this need to be implementing
pstmt.setString(10,diagram.getDiFileName()); // this need to be implementing
pstmt.setString(11,diagram.getDiFilepath()); // this need to be implementing
pstmt.executeUpdate();
//Get and set the auto-generated PK
rs = pstmt.getGeneratedKeys();
if (rs.next()) {
int newId = rs.getInt(1);
diagram.setDiagramId(newId);
}
rs.close();
pstmt.close();
conn.close();
return true;
} catch (SQLException ex) {
System.out.println("Exception"+ex.getMessage());
Logger.getLogger(DiagramDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
| public static boolean addDiagram(Diagram diagram) {
ResultSet rs;
try {
Connection conn = DbManager.getConnection();
//String sql = "INSERT INTO diagram (diagramName , createdTime , inEdition , owner_Id , filePath) VALUES (?,NOW(),?,?,?);";
//add by Yidu Liang Mar 20 2013
String sql = "insert into diagram (projectId, userId, diagramType, diagramName ,filePath, fileType, merged, notationFileName, notationFilePath, diFlieName, diFilePath)"+
"VALUES (?, ?, ?, ?, ? ,?, ?, ?, ?, ?,? )";
PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
//pstmt.setString(1, diagram.getDiagramName());
//pstmt.setBoolean(2, diagram.isInEdition());
//pstmt.setInt(3, diagram.getOwnerId());
//pstmt.setString(4, diagram.getEcoreFilePath());
//System.out.println("diagram upload SQL test");
//System.out.println(diagram.getProjectId());
//System.out.println(diagram.getUserId());
//System.out.println(diagram.getDiagramType());
//System.out.println(diagram.getMerged());
pstmt.setInt(1,diagram.getProjectId()); // this need to be implementing
pstmt.setInt(2,diagram.getUserId());
pstmt.setString(3,Integer.toString(1)); //Temporary hack to get code to work. Please replace when
//diagramType comes into effect @AniketHajirnis
pstmt.setString(4,diagram.getDiagramName()); // this need to be implementing
pstmt.setString(5,diagram.getFilePath()); // this need to be implementing
pstmt.setString(6,diagram.getFileType()); // this need to be implementing
pstmt.setInt(7,diagram.getMerged());
pstmt.setString(8,diagram.getNotationFileName()); // this need to be implementing
pstmt.setString(9,diagram.getNotationFilePath()); // this need to be implementing
pstmt.setString(10,diagram.getDiFileName()); // this need to be implementing
pstmt.setString(11,diagram.getDiFilepath()); // this need to be implementing
pstmt.executeUpdate();
//Get and set the auto-generated PK
rs = pstmt.getGeneratedKeys();
if (rs.next()) {
int newId = rs.getInt(1);
diagram.setDiagramId(newId);
}
rs.close();
pstmt.close();
conn.close();
return true;
} catch (SQLException ex) {
System.out.println("Exception"+ex.getMessage());
Logger.getLogger(DiagramDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
|
diff --git a/src/org/hyperic/hq/hqapi1/tools/UserCommand.java b/src/org/hyperic/hq/hqapi1/tools/UserCommand.java
index a380db6..b6d7e81 100644
--- a/src/org/hyperic/hq/hqapi1/tools/UserCommand.java
+++ b/src/org/hyperic/hq/hqapi1/tools/UserCommand.java
@@ -1,265 +1,265 @@
/*
*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2008, 2009], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* 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.hyperic.hq.hqapi1.tools;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import org.hyperic.hq.hqapi1.HQApi;
import org.hyperic.hq.hqapi1.RoleApi;
import org.hyperic.hq.hqapi1.UserApi;
import org.hyperic.hq.hqapi1.XmlUtil;
import org.hyperic.hq.hqapi1.types.ResponseStatus;
import org.hyperic.hq.hqapi1.types.Role;
import org.hyperic.hq.hqapi1.types.RoleResponse;
import org.hyperic.hq.hqapi1.types.StatusResponse;
import org.hyperic.hq.hqapi1.types.User;
import org.hyperic.hq.hqapi1.types.UserResponse;
import org.hyperic.hq.hqapi1.types.UsersResponse;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
@Component
public class UserCommand extends AbstractCommand {
private static String CMD_LIST = "list";
private static String CMD_SYNC = "sync";
private static String CMD_CREATE = "create";
private static String[] COMMANDS = { CMD_LIST, CMD_SYNC, CMD_CREATE };
private static String OPT_ID = "id";
private static String OPT_NAME = "name";
// create options
private static String OPT_FIRSTNAME = "firstName";
private static String OPT_LASTNAME = "lastName";
private static String OPT_DEPARTMENT = "department";
private static String OPT_EMAILADDRESS = "emailAddress";
private static String OPT_SMSADDRESS = "SMSAddress";
private static String OPT_PHONENUMBER = "phoneNumber";
private static String OPT_HTMLEMAIL = "htmlEmail";
private static String OPT_SETPASSWORD = "setPassword";
private static String OPT_ASSIGNTOROLE = "assignToRole";
private static String OPT_ASSIGNTOROLEID = "assignToRoleId";
private void printUsage() {
System.err.println("One of " + Arrays.toString(COMMANDS) + " required");
}
public String getName() {
return "user";
}
public int handleCommand(String[] args) throws Exception {
if (args.length == 0) {
printUsage();
return 1;
}
if (args[0].equals(CMD_LIST)) {
list(trim(args));
} else if (args[0].equals(CMD_SYNC)) {
sync(trim(args));
} else if (args[0].equals(CMD_CREATE)) {
create(trim(args));
} else {
printUsage();
return 1;
}
return 0;
}
private void list(String[] args) throws Exception {
OptionParser p = getOptionParser();
p.accepts(OPT_ID, "If specified, return the user with the given id.").
withRequiredArg().ofType(Integer.class);
p.accepts(OPT_NAME, "If specified, return the user with the given name").
withRequiredArg().ofType(String.class);
OptionSet options = getOptions(p, args);
HQApi api = getApi(options);
UserApi userApi = api.getUserApi();
UsersResponse users;
if (options.has(OPT_ID)) {
Integer id = (Integer)options.valueOf(OPT_ID);
UserResponse user = userApi.getUser(id);
checkSuccess(user);
users = new UsersResponse();
users.setStatus(ResponseStatus.SUCCESS);
users.getUser().add(user.getUser());
} else if (options.has(OPT_NAME)) {
String name = (String)options.valueOf(OPT_NAME);
UserResponse user = userApi.getUser(name);
checkSuccess(user);
users = new UsersResponse();
users.setStatus(ResponseStatus.SUCCESS);
users.getUser().add(user.getUser());
} else {
users = userApi.getUsers();
checkSuccess(users);
}
XmlUtil.serialize(users, System.out, Boolean.TRUE);
}
private void sync(String[] args) throws Exception {
OptionParser p = getOptionParser();
OptionSet options = getOptions(p, args);
HQApi api = getApi(options);
UserApi userApi = api.getUserApi();
InputStream is = getInputStream(options);
UsersResponse resp = XmlUtil.deserialize(UsersResponse.class, is);
List<User> users = resp.getUser();
StatusResponse syncResponse = userApi.syncUsers(users);
checkSuccess(syncResponse);
System.out.println("Successfully synced " + users.size() + " users.");
}
private void create(String[] args) throws Exception {
String[] OPT_REQUIRED = { OPT_NAME, OPT_FIRSTNAME, OPT_LASTNAME,
OPT_EMAILADDRESS, OPT_SETPASSWORD };
boolean ACTIVE = true; // Assume a newly created user should be active
OptionParser p = getOptionParser();
p.accepts(OPT_NAME, "Create user with username specified. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_FIRSTNAME, "Specifies the firstName field for the user. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_LASTNAME, "Specifies the lastName field for the user. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_DEPARTMENT, "Specifies the department field for the user.").
withRequiredArg().ofType(String.class);
p.accepts(OPT_EMAILADDRESS, "Specifies the emailAddress field for the user. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_SMSADDRESS, "Specifies the SMSAddress email address field for the user.").
withRequiredArg().ofType(String.class);
p.accepts(OPT_PHONENUMBER, "Specifies the phoneNumber field for the user.").
withRequiredArg().ofType(String.class);
p.accepts(OPT_SETPASSWORD, "Specifies the plain text password for the user. (prompted it not specified)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_HTMLEMAIL, "Specifies to send html formatted email to the user.");
p.accepts(OPT_ASSIGNTOROLE, "Assigns the user to the specified role by name").
withRequiredArg().ofType(String.class);
p.accepts(OPT_ASSIGNTOROLEID, "Assigns the user to the specified role by id").
withRequiredArg().ofType(Integer.class);
OptionSet options = getOptions(p, args);
if (!options.has(OPT_NAME) && !options.has(OPT_FIRSTNAME) && !options.has(OPT_LASTNAME) && !options.has(OPT_EMAILADDRESS)) {
System.err.println("All of required options: " + Arrays.toString(OPT_REQUIRED) + " missing");
System.exit(-1);
}
HQApi api = getApi(options);
UserApi userApi = api.getUserApi();
RoleApi roleApi = api.getRoleApi();
Role role = new Role();
RoleResponse roleResponse = null;
String password = null;
// Validate the role name
if (options.has(OPT_ASSIGNTOROLE)) {
roleResponse = roleApi.getRole(options.valueOf(OPT_ASSIGNTOROLE).toString());
checkSuccess(roleResponse);
role = roleResponse.getRole();
} else if (options.has((OPT_ASSIGNTOROLEID))) {
roleResponse = roleApi.getRole((Integer)options.valueOf(OPT_ASSIGNTOROLEID));
checkSuccess(roleResponse);
role = roleResponse.getRole();
}
if (!options.has(OPT_SETPASSWORD)) {
// prompt for password
try {
char[] passwordArray = PasswordField.getPassword(System.in,
"Enter password: ");
char[] passwordConfirmArray = PasswordField.getPassword(System.in,
"Repeat password: ");
if (String.valueOf(passwordArray).equals(String.valueOf(passwordConfirmArray))) {
password = String.valueOf(passwordArray);
} else {
System.out.println("Passwords do not match!");
System.exit(-1);
}
} catch (IOException ioe) {
System.err.println("Error reading password");
System.exit(-1);
}
} else {
password = options.valueOf(OPT_SETPASSWORD).toString();
}
User user = new User();
user.setName(options.valueOf(OPT_NAME).toString());
user.setFirstName(options.valueOf(OPT_FIRSTNAME).toString());
user.setLastName(options.valueOf(OPT_LASTNAME).toString());
user.setEmailAddress(options.valueOf(OPT_EMAILADDRESS).toString());
if (options.has(OPT_DEPARTMENT)) {
user.setDepartment(options.valueOf(OPT_DEPARTMENT).toString());
}
if (options.has(OPT_SMSADDRESS)) {
user.setSMSAddress(options.valueOf(OPT_SMSADDRESS).toString());
}
if (options.has(OPT_EMAILADDRESS)) {
user.setEmailAddress(options.valueOf(OPT_EMAILADDRESS).toString());
}
if (options.has(OPT_HTMLEMAIL)) {
user.setHtmlEmail(true);
} else {
user.setHtmlEmail(false);
}
user.setActive(ACTIVE);
UserResponse response = userApi.createUser(user, password);
checkSuccess(response);
System.out.println("Successfully created: " + user.getName() + " with id " + response.getUser().getId());
- if (role != null) {
+ if (role.getId() != null) {
role.getUser().add(user);
checkSuccess(roleApi.updateRole(role));
System.out.println("Successfully assigned " + user.getName() + " to role " + role.getName());
}
}
}
| true | true | private void create(String[] args) throws Exception {
String[] OPT_REQUIRED = { OPT_NAME, OPT_FIRSTNAME, OPT_LASTNAME,
OPT_EMAILADDRESS, OPT_SETPASSWORD };
boolean ACTIVE = true; // Assume a newly created user should be active
OptionParser p = getOptionParser();
p.accepts(OPT_NAME, "Create user with username specified. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_FIRSTNAME, "Specifies the firstName field for the user. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_LASTNAME, "Specifies the lastName field for the user. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_DEPARTMENT, "Specifies the department field for the user.").
withRequiredArg().ofType(String.class);
p.accepts(OPT_EMAILADDRESS, "Specifies the emailAddress field for the user. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_SMSADDRESS, "Specifies the SMSAddress email address field for the user.").
withRequiredArg().ofType(String.class);
p.accepts(OPT_PHONENUMBER, "Specifies the phoneNumber field for the user.").
withRequiredArg().ofType(String.class);
p.accepts(OPT_SETPASSWORD, "Specifies the plain text password for the user. (prompted it not specified)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_HTMLEMAIL, "Specifies to send html formatted email to the user.");
p.accepts(OPT_ASSIGNTOROLE, "Assigns the user to the specified role by name").
withRequiredArg().ofType(String.class);
p.accepts(OPT_ASSIGNTOROLEID, "Assigns the user to the specified role by id").
withRequiredArg().ofType(Integer.class);
OptionSet options = getOptions(p, args);
if (!options.has(OPT_NAME) && !options.has(OPT_FIRSTNAME) && !options.has(OPT_LASTNAME) && !options.has(OPT_EMAILADDRESS)) {
System.err.println("All of required options: " + Arrays.toString(OPT_REQUIRED) + " missing");
System.exit(-1);
}
HQApi api = getApi(options);
UserApi userApi = api.getUserApi();
RoleApi roleApi = api.getRoleApi();
Role role = new Role();
RoleResponse roleResponse = null;
String password = null;
// Validate the role name
if (options.has(OPT_ASSIGNTOROLE)) {
roleResponse = roleApi.getRole(options.valueOf(OPT_ASSIGNTOROLE).toString());
checkSuccess(roleResponse);
role = roleResponse.getRole();
} else if (options.has((OPT_ASSIGNTOROLEID))) {
roleResponse = roleApi.getRole((Integer)options.valueOf(OPT_ASSIGNTOROLEID));
checkSuccess(roleResponse);
role = roleResponse.getRole();
}
if (!options.has(OPT_SETPASSWORD)) {
// prompt for password
try {
char[] passwordArray = PasswordField.getPassword(System.in,
"Enter password: ");
char[] passwordConfirmArray = PasswordField.getPassword(System.in,
"Repeat password: ");
if (String.valueOf(passwordArray).equals(String.valueOf(passwordConfirmArray))) {
password = String.valueOf(passwordArray);
} else {
System.out.println("Passwords do not match!");
System.exit(-1);
}
} catch (IOException ioe) {
System.err.println("Error reading password");
System.exit(-1);
}
} else {
password = options.valueOf(OPT_SETPASSWORD).toString();
}
User user = new User();
user.setName(options.valueOf(OPT_NAME).toString());
user.setFirstName(options.valueOf(OPT_FIRSTNAME).toString());
user.setLastName(options.valueOf(OPT_LASTNAME).toString());
user.setEmailAddress(options.valueOf(OPT_EMAILADDRESS).toString());
if (options.has(OPT_DEPARTMENT)) {
user.setDepartment(options.valueOf(OPT_DEPARTMENT).toString());
}
if (options.has(OPT_SMSADDRESS)) {
user.setSMSAddress(options.valueOf(OPT_SMSADDRESS).toString());
}
if (options.has(OPT_EMAILADDRESS)) {
user.setEmailAddress(options.valueOf(OPT_EMAILADDRESS).toString());
}
if (options.has(OPT_HTMLEMAIL)) {
user.setHtmlEmail(true);
} else {
user.setHtmlEmail(false);
}
user.setActive(ACTIVE);
UserResponse response = userApi.createUser(user, password);
checkSuccess(response);
System.out.println("Successfully created: " + user.getName() + " with id " + response.getUser().getId());
if (role != null) {
role.getUser().add(user);
checkSuccess(roleApi.updateRole(role));
System.out.println("Successfully assigned " + user.getName() + " to role " + role.getName());
}
}
| private void create(String[] args) throws Exception {
String[] OPT_REQUIRED = { OPT_NAME, OPT_FIRSTNAME, OPT_LASTNAME,
OPT_EMAILADDRESS, OPT_SETPASSWORD };
boolean ACTIVE = true; // Assume a newly created user should be active
OptionParser p = getOptionParser();
p.accepts(OPT_NAME, "Create user with username specified. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_FIRSTNAME, "Specifies the firstName field for the user. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_LASTNAME, "Specifies the lastName field for the user. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_DEPARTMENT, "Specifies the department field for the user.").
withRequiredArg().ofType(String.class);
p.accepts(OPT_EMAILADDRESS, "Specifies the emailAddress field for the user. (required)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_SMSADDRESS, "Specifies the SMSAddress email address field for the user.").
withRequiredArg().ofType(String.class);
p.accepts(OPT_PHONENUMBER, "Specifies the phoneNumber field for the user.").
withRequiredArg().ofType(String.class);
p.accepts(OPT_SETPASSWORD, "Specifies the plain text password for the user. (prompted it not specified)").
withRequiredArg().ofType(String.class);
p.accepts(OPT_HTMLEMAIL, "Specifies to send html formatted email to the user.");
p.accepts(OPT_ASSIGNTOROLE, "Assigns the user to the specified role by name").
withRequiredArg().ofType(String.class);
p.accepts(OPT_ASSIGNTOROLEID, "Assigns the user to the specified role by id").
withRequiredArg().ofType(Integer.class);
OptionSet options = getOptions(p, args);
if (!options.has(OPT_NAME) && !options.has(OPT_FIRSTNAME) && !options.has(OPT_LASTNAME) && !options.has(OPT_EMAILADDRESS)) {
System.err.println("All of required options: " + Arrays.toString(OPT_REQUIRED) + " missing");
System.exit(-1);
}
HQApi api = getApi(options);
UserApi userApi = api.getUserApi();
RoleApi roleApi = api.getRoleApi();
Role role = new Role();
RoleResponse roleResponse = null;
String password = null;
// Validate the role name
if (options.has(OPT_ASSIGNTOROLE)) {
roleResponse = roleApi.getRole(options.valueOf(OPT_ASSIGNTOROLE).toString());
checkSuccess(roleResponse);
role = roleResponse.getRole();
} else if (options.has((OPT_ASSIGNTOROLEID))) {
roleResponse = roleApi.getRole((Integer)options.valueOf(OPT_ASSIGNTOROLEID));
checkSuccess(roleResponse);
role = roleResponse.getRole();
}
if (!options.has(OPT_SETPASSWORD)) {
// prompt for password
try {
char[] passwordArray = PasswordField.getPassword(System.in,
"Enter password: ");
char[] passwordConfirmArray = PasswordField.getPassword(System.in,
"Repeat password: ");
if (String.valueOf(passwordArray).equals(String.valueOf(passwordConfirmArray))) {
password = String.valueOf(passwordArray);
} else {
System.out.println("Passwords do not match!");
System.exit(-1);
}
} catch (IOException ioe) {
System.err.println("Error reading password");
System.exit(-1);
}
} else {
password = options.valueOf(OPT_SETPASSWORD).toString();
}
User user = new User();
user.setName(options.valueOf(OPT_NAME).toString());
user.setFirstName(options.valueOf(OPT_FIRSTNAME).toString());
user.setLastName(options.valueOf(OPT_LASTNAME).toString());
user.setEmailAddress(options.valueOf(OPT_EMAILADDRESS).toString());
if (options.has(OPT_DEPARTMENT)) {
user.setDepartment(options.valueOf(OPT_DEPARTMENT).toString());
}
if (options.has(OPT_SMSADDRESS)) {
user.setSMSAddress(options.valueOf(OPT_SMSADDRESS).toString());
}
if (options.has(OPT_EMAILADDRESS)) {
user.setEmailAddress(options.valueOf(OPT_EMAILADDRESS).toString());
}
if (options.has(OPT_HTMLEMAIL)) {
user.setHtmlEmail(true);
} else {
user.setHtmlEmail(false);
}
user.setActive(ACTIVE);
UserResponse response = userApi.createUser(user, password);
checkSuccess(response);
System.out.println("Successfully created: " + user.getName() + " with id " + response.getUser().getId());
if (role.getId() != null) {
role.getUser().add(user);
checkSuccess(roleApi.updateRole(role));
System.out.println("Successfully assigned " + user.getName() + " to role " + role.getName());
}
}
|
diff --git a/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java b/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java
index a9702b72..589b7894 100644
--- a/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java
+++ b/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java
@@ -1,3707 +1,3704 @@
/*******************************************************************************
* <e-Adventure> (formerly <e-Game>) is a research project of the <e-UCM>
* research group.
*
* Copyright 2005-2010 <e-UCM> research group.
*
* You can access a list of all the contributors to <e-Adventure> at:
* http://e-adventure.e-ucm.es/contributors
*
* <e-UCM> is a research group of the Department of Software Engineering
* and Artificial Intelligence at the Complutense University of Madrid
* (School of Computer Science).
*
* C Profesor Jose Garcia Santesmases sn,
* 28040 Madrid (Madrid), Spain.
*
* For more info please visit: <http://e-adventure.e-ucm.es> or
* <http://www.e-ucm.es>
*
* ****************************************************************************
*
* This file is part of <e-Adventure>, version 1.2.
*
* <e-Adventure> 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.
*
* <e-Adventure> 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 <e-Adventure>. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package es.eucm.eadventure.editor.control;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import es.eucm.eadventure.common.auxiliar.File;
import es.eucm.eadventure.common.auxiliar.ReleaseFolders;
import es.eucm.eadventure.common.auxiliar.ReportDialog;
import es.eucm.eadventure.common.data.adventure.AdventureData;
import es.eucm.eadventure.common.data.adventure.DescriptorData;
import es.eucm.eadventure.common.data.adventure.DescriptorData.DefaultClickAction;
import es.eucm.eadventure.common.data.adventure.DescriptorData.Perspective;
import es.eucm.eadventure.common.data.animation.Animation;
import es.eucm.eadventure.common.data.animation.Frame;
import es.eucm.eadventure.common.data.chapter.Chapter;
import es.eucm.eadventure.common.data.chapter.Trajectory;
import es.eucm.eadventure.common.data.chapter.elements.NPC;
import es.eucm.eadventure.common.data.chapter.elements.Player;
import es.eucm.eadventure.common.gui.TC;
import es.eucm.eadventure.common.loader.Loader;
import es.eucm.eadventure.common.loader.incidences.Incidence;
import es.eucm.eadventure.editor.auxiliar.filefilters.EADFileFilter;
import es.eucm.eadventure.editor.auxiliar.filefilters.FolderFileFilter;
import es.eucm.eadventure.editor.auxiliar.filefilters.JARFileFilter;
import es.eucm.eadventure.editor.auxiliar.filefilters.XMLFileFilter;
import es.eucm.eadventure.editor.control.config.ConfigData;
import es.eucm.eadventure.editor.control.config.ProjectConfigData;
import es.eucm.eadventure.editor.control.config.SCORMConfigData;
import es.eucm.eadventure.editor.control.controllers.AdventureDataControl;
import es.eucm.eadventure.editor.control.controllers.AssetsController;
import es.eucm.eadventure.editor.control.controllers.EditorImageLoader;
import es.eucm.eadventure.editor.control.controllers.VarFlagsController;
import es.eucm.eadventure.editor.control.controllers.adaptation.AdaptationProfilesDataControl;
import es.eucm.eadventure.editor.control.controllers.assessment.AssessmentProfilesDataControl;
import es.eucm.eadventure.editor.control.controllers.atrezzo.AtrezzoDataControl;
import es.eucm.eadventure.editor.control.controllers.character.NPCDataControl;
import es.eucm.eadventure.editor.control.controllers.general.AdvancedFeaturesDataControl;
import es.eucm.eadventure.editor.control.controllers.general.ChapterDataControl;
import es.eucm.eadventure.editor.control.controllers.general.ChapterListDataControl;
import es.eucm.eadventure.editor.control.controllers.item.ItemDataControl;
import es.eucm.eadventure.editor.control.controllers.metadata.lom.LOMDataControl;
import es.eucm.eadventure.editor.control.controllers.scene.SceneDataControl;
import es.eucm.eadventure.editor.control.tools.Tool;
import es.eucm.eadventure.editor.control.tools.general.SwapPlayerModeTool;
import es.eucm.eadventure.editor.control.tools.general.chapters.AddChapterTool;
import es.eucm.eadventure.editor.control.tools.general.chapters.DeleteChapterTool;
import es.eucm.eadventure.editor.control.tools.general.chapters.MoveChapterTool;
import es.eucm.eadventure.editor.control.writer.Writer;
import es.eucm.eadventure.editor.data.support.IdentifierSummary;
import es.eucm.eadventure.editor.data.support.VarFlagSummary;
import es.eucm.eadventure.editor.gui.LoadingScreen;
import es.eucm.eadventure.editor.gui.MainWindow;
import es.eucm.eadventure.editor.gui.displaydialogs.InvalidReportDialog;
import es.eucm.eadventure.editor.gui.editdialogs.AdventureDataDialog;
import es.eucm.eadventure.editor.gui.editdialogs.ExportToLOMDialog;
import es.eucm.eadventure.editor.gui.editdialogs.GraphicConfigDialog;
import es.eucm.eadventure.editor.gui.editdialogs.SearchDialog;
import es.eucm.eadventure.editor.gui.editdialogs.VarsFlagsDialog;
import es.eucm.eadventure.editor.gui.editdialogs.customizeguidialog.CustomizeGUIDialog;
import es.eucm.eadventure.editor.gui.metadatadialog.ims.IMSDialog;
import es.eucm.eadventure.editor.gui.metadatadialog.lomdialog.LOMDialog;
import es.eucm.eadventure.editor.gui.metadatadialog.lomes.LOMESDialog;
import es.eucm.eadventure.editor.gui.startdialog.FrameForInitialDialogs;
import es.eucm.eadventure.editor.gui.startdialog.StartDialog;
import es.eucm.eadventure.engine.EAdventureDebug;
/**
* This class is the main controller of the application. It holds the main
* operations and data to control the editor.
*
* @author Bruno Torijano Bueno
*/
/*
* @updated by Javier Torrente. New functionalities added - Support for .ead files. Therefore <e-Adventure> files are no
* longer .zip but .ead
*/
public class Controller {
/**
* Id for the complete chapter data element.
*/
public static final int CHAPTER = 0;
/**
* Id for the scenes list element.
*/
public static final int SCENES_LIST = 1;
/**
* Id for the scene element.
*/
public static final int SCENE = 2;
/**
* Id for the exits list element.
*/
public static final int EXITS_LIST = 3;
/**
* Id for the exit element.
*/
public static final int EXIT = 4;
/**
* Id for the item references list element.
*/
public static final int ITEM_REFERENCES_LIST = 5;
/**
* Id for the item reference element.
*/
public static final int ITEM_REFERENCE = 6;
/**
* Id for the NPC references list element.
*/
public static final int NPC_REFERENCES_LIST = 7;
/**
* Id for the NPC reference element.
*/
public static final int NPC_REFERENCE = 8;
/**
* Id for the cutscenes list element.
*/
public static final int CUTSCENES_LIST = 9;
/**
* Id for the slidescene element.
*/
public static final int CUTSCENE_SLIDES = 10;
public static final int CUTSCENE = 910;
public static final int CUTSCENE_VIDEO = 37;
/**
* Id for the books list element.
*/
public static final int BOOKS_LIST = 11;
/**
* Id for the book element.
*/
public static final int BOOK = 12;
/**
* Id for the book paragraphs list element.
*/
public static final int BOOK_PARAGRAPHS_LIST = 13;
/**
* Id for the title paragraph element.
*/
public static final int BOOK_TITLE_PARAGRAPH = 14;
/**
* Id for the text paragraph element.
*/
public static final int BOOK_TEXT_PARAGRAPH = 15;
/**
* Id for the bullet paragraph element.
*/
public static final int BOOK_BULLET_PARAGRAPH = 16;
/**
* Id for the image paragraph element.
*/
public static final int BOOK_IMAGE_PARAGRAPH = 17;
/**
* Id for the items list element.
*/
public static final int ITEMS_LIST = 18;
/**
* Id for the item element.
*/
public static final int ITEM = 19;
/**
* Id for the actions list element.
*/
public static final int ACTIONS_LIST = 20;
/**
* Id for the "Examine" action element.
*/
public static final int ACTION_EXAMINE = 21;
/**
* Id for the "Grab" action element.
*/
public static final int ACTION_GRAB = 22;
/**
* Id for the "Use" action element.
*/
public static final int ACTION_USE = 23;
/**
* Id for the "Custom" action element.
*/
public static final int ACTION_CUSTOM = 230;
/**
* Id for the "Talk to" action element.
*/
public static final int ACTION_TALK_TO = 231;
/**
* Id for the "Use with" action element.
*/
public static final int ACTION_USE_WITH = 24;
/**
* Id for the "Give to" action element.
*/
public static final int ACTION_GIVE_TO = 25;
/**
* Id for the "Drag-to" action element.
*/
public static final int ACTION_DRAG_TO = 251;
/**
* Id for the "Custom interact" action element.
*/
public static final int ACTION_CUSTOM_INTERACT = 250;
/**
* Id for the player element.
*/
public static final int PLAYER = 26;
/**
* Id for the NPCs list element.
*/
public static final int NPCS_LIST = 27;
/**
* Id for the NPC element.
*/
public static final int NPC = 28;
/**
* Id for the conversation references list element.
*/
public static final int CONVERSATION_REFERENCES_LIST = 29;
/**
* Id for the conversation reference element.
*/
public static final int CONVERSATION_REFERENCE = 30;
/**
* Id for the conversations list element.
*/
public static final int CONVERSATIONS_LIST = 31;
/**
* Id for the tree conversation element.
*/
public static final int CONVERSATION_TREE = 32;
/**
* Id for the graph conversation element.
*/
public static final int CONVERSATION_GRAPH = 33;
/**
* Id for the graph conversation element.
*/
public static final int CONVERSATION_DIALOGUE_LINE = 330;
/**
* Id for the graph conversation element.
*/
public static final int CONVERSATION_OPTION_LINE = 331;
/**
* Id for the resources element.
*/
public static final int RESOURCES = 34;
/**
* Id for the next scene element.
*/
public static final int NEXT_SCENE = 35;
/**
* If for the end scene element.
*/
public static final int END_SCENE = 36;
/**
* Id for Assessment Rule
*/
public static final int ASSESSMENT_RULE = 38;
/**
* Id for Adaptation Rule
*/
public static final int ADAPTATION_RULE = 39;
/**
* Id for Assessment Rules
*/
public static final int ASSESSMENT_PROFILE = 40;
/**
* Id for Adaptation Rules
*/
public static final int ADAPTATION_PROFILE = 41;
/**
* Id for the styled book element.
*/
public static final int STYLED_BOOK = 42;
/**
* Id for the page of a STYLED_BOK.
*/
public static final int BOOK_PAGE = 43;
/**
* Id for timers.
*/
public static final int TIMER = 44;
/**
* Id for the list of timers.
*/
public static final int TIMERS_LIST = 45;
/**
* Id for the advanced features node.
*/
public static final int ADVANCED_FEATURES = 46;
/**
* Id for the assessment profiles node.
*/
public static final int ASSESSSMENT_PROFILES = 47;
/**
* Id for the adaptation profiles node.
*/
public static final int ADAPTATION_PROFILES = 48;
/**
* Id for timed assessment rules
*/
public static final int TIMED_ASSESSMENT_RULE = 49;
/**
* Id for active areas list.
*/
public static final int ACTIVE_AREAS_LIST = 50;
/**
* Id for active area
*/
public static final int ACTIVE_AREA = 51;
/**
* Id for barriers list.
*/
public static final int BARRIERS_LIST = 52;
/**
* Id for barrier
*/
public static final int BARRIER = 53;
/**
* Id for global state
*/
public static final int GLOBAL_STATE = 54;
/**
* Id for global state list
*/
public static final int GLOBAL_STATE_LIST = 55;
/**
* Id for macro
*/
public static final int MACRO = 56;
/**
* Id for macro list
*/
public static final int MACRO_LIST = 57;
/**
* Id for atrezzo item element
*/
public static final int ATREZZO = 58;
/**
* Id for atrezzo list element
*/
public static final int ATREZZO_LIST = 59;
/**
* Id for atrezzo reference
*/
public static final int ATREZZO_REFERENCE = 60;
/**
* Id for atrezzo references list
*/
public static final int ATREZZO_REFERENCES_LIST = 61;
public static final int NODE = 62;
public static final int SIDE = 63;
public static final int TRAJECTORY = 64;
public static final int ANIMATION = 65;
public static final int EFFECT = 66;
//TYPES OF EAD FILES
public static final int FILE_ADVENTURE_1STPERSON_PLAYER = 0;
public static final int FILE_ADVENTURE_3RDPERSON_PLAYER = 1;
public static final int FILE_ASSESSMENT = 2;
public static final int FILE_ADAPTATION = 3;
/**
* Identifiers for differents scorm profiles
*/
public static final int SCORM12 = 0;
public static final int SCORM2004 = 1;
public static final int AGREGA = 2;
/**
* Singleton instance.
*/
private static Controller controllerInstance = null;
/**
* The main window of the application.
*/
private MainWindow mainWindow;
/**
* The complete path to the current open ZIP file.
*/
private String currentZipFile;
/**
* The path to the folder that holds the open file.
*/
private String currentZipPath;
/**
* The name of the file that is being currently edited. Used only to display
* info.
*/
private String currentZipName;
/**
* The data of the adventure being edited.
*/
private AdventureDataControl adventureDataControl;
/**
* Stores if the data has been modified since the last save.
*/
private boolean dataModified;
/**
* Stores the file that contains the GUI strings.
*/
private String languageFile;
private LoadingScreen loadingScreen;
private String lastDialogDirectory;
/*private boolean isTempFile = false;
public boolean isTempFile( ) {
return isTempFile;
}*/
private ChapterListDataControl chaptersController;
private AutoSave autoSave;
private Timer autoSaveTimer;
private boolean isLomEs = false;
/**
* Store all effects selection. Connects the type of effect with the number
* of times that has been used
*/
// private SelectedEffectsController selectedEffects;
/**
* Void and private constructor.
*/
private Controller( ) {
chaptersController = new ChapterListDataControl( );
}
private String getCurrentExportSaveFolder( ) {
return ReleaseFolders.exportsFolder( ).getAbsolutePath( );
}
public String getCurrentLoadFolder( ) {
return ReleaseFolders.projectsFolder( ).getAbsolutePath( );
}
public void setLastDirectory( String directory ) {
this.lastDialogDirectory = directory;
}
public String getLastDirectory( ) {
if( lastDialogDirectory != null ) {
return lastDialogDirectory;
}
else
return ReleaseFolders.projectsFolder( ).getAbsolutePath( );
}
/**
* Returns the instance of the controller.
*
* @return The instance of the controller
*/
public static Controller getInstance( ) {
if( controllerInstance == null )
controllerInstance = new Controller( );
return controllerInstance;
}
public int playerMode( ) {
return adventureDataControl.getPlayerMode( );
}
/**
* Initializing function.
*/
public void init( String arg ) {
// Load the configuration
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.init( );
SCORMConfigData.init( );
// Create necessary folders if no created befor
File projectsFolder = ReleaseFolders.projectsFolder( );
if( !projectsFolder.exists( ) ) {
projectsFolder.mkdirs( );
}
File tempFolder = ReleaseFolders.webTempFolder( );
if( !tempFolder.exists( ) ) {
projectsFolder.mkdirs( );
}
File exportsFolder = ReleaseFolders.exportsFolder( );
if( !exportsFolder.exists( ) ) {
exportsFolder.mkdirs( );
}
//Create splash screen
loadingScreen = new LoadingScreen( "PRUEBA", getLoadingImage( ), null );
// Set values for language config
languageFile = ReleaseFolders.LANGUAGE_UNKNOWN;
setLanguage( ReleaseFolders.getLanguageFromPath( ConfigData.getLanguangeFile( ) ), false );
// Create a list for the chapters
chaptersController = new ChapterListDataControl( );
// Inits the controller with empty data
currentZipFile = null;
currentZipPath = null;
currentZipName = null;
//adventureData = new AdventureDataControl( TextConstants.getText( "DefaultValue.AdventureTitle" ), TextConstants.getText( "DefaultValue.ChapterTitle" ), TextConstants.getText( "DefaultValue.SceneId" ) );
//selectedChapter = 0;
//chapterDataControlList.add( new ChapterDataControl( getSelectedChapterData( ) ) );
//identifierSummary = new IdentifierSummary( getSelectedChapterData( ) );
dataModified = false;
//Create main window and hide it
mainWindow = new MainWindow( );
// mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
// Prompt the user to create a new adventure or to load one
//while( currentZipFile == null ) {
// Load the options and show the dialog
//StartDialog start = new StartDialog( );
FrameForInitialDialogs start = new FrameForInitialDialogs(true);
if( arg != null ) {
File projectFile = new File( arg );
if( projectFile.exists( ) ) {
if( projectFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = projectFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( projectFile.isDirectory( ) && projectFile.exists( ) )
loadFile( projectFile.getAbsolutePath( ), true );
}
}
else if( ConfigData.showStartDialog( ) ) {
//int op = start.showOpenDialog( mainWindow );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
if( selectedFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else {
this.importGame( selectedFile.getAbsolutePath( ) );
}
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
//selectedChapter = 0;
}
if( currentZipFile == null ) {
//newFile( FILE_ADVENTURE_3RDPERSON_PLAYER );
//selectedChapter = -1;
mainWindow.reloadData( );
}
/*
* int optionSelected = mainWindow.showOptionDialog( TextConstants.getText( "StartDialog.Title" ),
* TextConstants.getText( "StartDialog.Message" ), options );
* // If the user wants to create a new file, show the dialog if( optionSelected == 0 ) newFile( );
* // If the user wants to load a existing adventure, show the load dialog else if( optionSelected == 1 )
* loadFile( );
* // If the dialog was closed, exit the aplication else if( optionSelected == JOptionPane.CLOSED_OPTION )
* exit( );
*/
//}
// Show the window
/*mainWindow.setEnabled( true );
mainWindow.reloadData( );
try {
Thread.sleep( 1 );
} catch( InterruptedException e ) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
// Create the main window and hide it
//mainWindow.setVisible( false );
// initialize the selected effects container
//selectedEffects = new SelectedEffectsController();
mainWindow.setResizable( true );
//mainWindow.setEnabled( true );
// mainWindow.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainWindow.setVisible( true );
//DEBUGGING
//tsd = new ToolSystemDebugger( chaptersController );
}
/*public void addSelectedEffect(String name){
selectedEffects.addSelectedEffect(name);
}
public SelectedEffectsController getSelectedEffectsController(){
return selectedEffects;
}*/
public void startAutoSave( int minutes ) {
stopAutoSave( );
if( ( ProjectConfigData.existsKey( "autosave" ) && ProjectConfigData.getProperty( "autosave" ).equals( "yes" ) ) || !ProjectConfigData.existsKey( "autosave" ) ) {
/* autoSaveTimer = new Timer();
autoSave = new AutoSave();
autoSaveTimer.schedule(autoSave, 10000, minutes * 60 * 1000);
*/}
if( !ProjectConfigData.existsKey( "autosave" ) )
ProjectConfigData.setProperty( "autosave", "yes" );
}
public void stopAutoSave( ) {
if( autoSaveTimer != null ) {
autoSaveTimer.cancel( );
autoSave.stop( );
autoSaveTimer = null;
}
autoSave = null;
}
//private ToolSystemDebugger tsd;
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// General data functions of the aplication
/**
* Returns the complete path to the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public String getProjectFolder( ) {
return currentZipFile;
}
/**
* Returns the File object representing the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public File getProjectFolderFile( ) {
return new File( currentZipFile );
}
/**
* Returns the name of the file currently open.
*
* @return The name of the current file
*/
public String getFileName( ) {
String filename;
// Show "New" if no current file is currently open
if( currentZipName != null )
filename = currentZipName;
else
filename = "http://e-adventure.e-ucm.es";
return filename;
}
/**
* Returns the parent path of the file being currently edited.
*
* @return Parent path of the current file
*/
public String getFilePath( ) {
return currentZipPath;
}
/**
* Returns an array with the chapter titles.
*
* @return Array with the chapter titles
*/
public String[] getChapterTitles( ) {
return chaptersController.getChapterTitles( );
}
/**
* Returns the index of the chapter currently selected.
*
* @return Index of the selected chapter
*/
public int getSelectedChapter( ) {
return chaptersController.getSelectedChapter( );
}
/**
* Returns the selected chapter data controller.
*
* @return The selected chapter data controller
*/
public ChapterDataControl getSelectedChapterDataControl( ) {
return chaptersController.getSelectedChapterDataControl( );
}
/**
* Returns the identifier summary.
*
* @return The identifier summary
*/
public IdentifierSummary getIdentifierSummary( ) {
return chaptersController.getIdentifierSummary( );
}
/**
* Returns the varFlag summary.
*
* @return The varFlag summary
*/
public VarFlagSummary getVarFlagSummary( ) {
return chaptersController.getVarFlagSummary( );
}
public ChapterListDataControl getCharapterList( ) {
return chaptersController;
}
/**
* Returns whether the data has been modified since the last save.
*
* @return True if the data has been modified, false otherwise
*/
public boolean isDataModified( ) {
return dataModified;
}
/**
* Called when the data has been modified, it sets the value to true.
*/
public void dataModified( ) {
// If the data were not modified, change the value and set the new title of the window
if( !dataModified ) {
dataModified = true;
mainWindow.updateTitle( );
}
}
public boolean isPlayTransparent( ) {
if( adventureDataControl == null ) {
return false;
}
return adventureDataControl.getPlayerMode( ) == DescriptorData.MODE_PLAYER_1STPERSON;
}
public void swapPlayerMode( boolean showConfirmation ) {
addTool( new SwapPlayerModeTool( showConfirmation, adventureDataControl, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions that perform usual application actions
/**
* This method creates a new file with it's respective data.
*
* @return True if the new data was created successfully, false otherwise
*/
public boolean newFile( int fileType ) {
boolean fileCreated = false;
if( fileType == Controller.FILE_ADVENTURE_1STPERSON_PLAYER || fileType == Controller.FILE_ADVENTURE_3RDPERSON_PLAYER )
fileCreated = newAdventureFile( fileType );
else if( fileType == Controller.FILE_ASSESSMENT ) {
//fileCreated = newAssessmentFile();
}
else if( fileType == Controller.FILE_ADAPTATION ) {
//fileCreated = newAdaptationFile();
}
if( fileCreated )
AssetsController.resetCache( );
return fileCreated;
}
public boolean newFile( ) {
boolean createNewFile = true;
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.NewFileTitle" ), TC.get( "Operation.NewFileMessage" ) );
// If the data must be saved, create the new file only if the save was successful
if( option == JOptionPane.YES_OPTION )
createNewFile = saveFile( false );
// If the data must not be saved, create the new data directly
else if( option == JOptionPane.NO_OPTION ) {
createNewFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
createNewFile = false;
}
}
if( createNewFile ) {
stopAutoSave( );
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.init( );
// Show dialog
//StartDialog start = new StartDialog( StartDialog.NEW_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs( StartDialog.NEW_TAB );
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( mainWindow );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
if( selectedFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else {
this.importGame( selectedFile.getAbsolutePath( ) );
}
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
if( currentZipFile == null ) {
mainWindow.reloadData( );
}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
//DEBUGGING
//tsd = new ToolSystemDebugger( chaptersController );
}
Controller.gc();
return createNewFile;
}
private boolean newAdventureFile( int fileType ) {
boolean fileCreated = false;
// Decide the directory of the temp file and give a name for it
// If there is a valid temp directory in the system, use it
//String tempDir = System.getenv( "TEMP" );
//String completeFilePath = "";
//isTempFile = true;
//if( tempDir != null ) {
// completeFilePath = tempDir + "/" + TEMP_NAME;
//}
// If the temp directory is not valid, use the home directory
//else {
// completeFilePath = FileSystemView.getFileSystemView( ).getHomeDirectory( ) + "/" + TEMP_NAME;
//}
boolean create = false;
java.io.File selectedDir = null;
java.io.File selectedFile = null;
// Prompt main folder of the project
//ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
int op = start.showStartDialog( );
// If some folder is selected, check all characters are correct
// if( folderSelector.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFile.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new File( selectedFile.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the parent folder is not forbidden
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( !directory.deleteAll( ) ) {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
}
}
create = true;
}
else {
// Create new folder?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotCreatedTitle" ), TC.get( "Operation.NewProject.FolderNotCreatedMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
else {
create = false;
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove( );
// Create the new project?
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.CreateProject" ), getLoadingImage( ), mainWindow);
if( create ) {
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.CreateProject" ) );
loadingScreen.setVisible( true );
// Set the new file, path and create the new adventure
currentZipFile = selectedDir.getAbsolutePath( );
currentZipPath = selectedDir.getParent( );
currentZipName = selectedDir.getName( );
int playerMode = -1;
if( fileType == FILE_ADVENTURE_3RDPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_3RDPERSON;
else if( fileType == FILE_ADVENTURE_1STPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_1STPERSON;
adventureDataControl = new AdventureDataControl( TC.get( "DefaultValue.AdventureTitle" ), TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ), playerMode );
// Clear the list of data controllers and refill it
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Init project properties (empty)
ProjectConfigData.init( );
SCORMConfigData.init( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
// Set modified to false and update the window title
dataModified = false;
try {
Thread.sleep( 1 );
}
catch( InterruptedException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWNERROR" );
}
try {
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
}
catch( IOException e ) {
}
mainWindow.reloadData( );
// The file was saved
fileCreated = true;
}
else
fileCreated = false;
}
if( fileCreated ) {
ConfigData.fileLoaded( currentZipFile );
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
}
else {
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
loadingScreen.setVisible( false );
Controller.gc();
return fileCreated;
}
public void showLoadingScreen( String message ) {
loadingScreen.setMessage( message );
loadingScreen.setVisible( true );
}
public void hideLoadingScreen( ) {
loadingScreen.setVisible( false );
}
public boolean fixIncidences( List<Incidence> incidences ) {
boolean abort = false;
List<Chapter> chapters = this.adventureDataControl.getChapters( );
for( int i = 0; i < incidences.size( ); i++ ) {
Incidence current = incidences.get( i );
// Critical importance: abort operation, the game could not be loaded
if( current.getImportance( ) == Incidence.IMPORTANCE_CRITICAL ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
break;
}
// High importance: the game is partially unreadable, but it is possible to continue.
else if( current.getImportance( ) == Incidence.IMPORTANCE_HIGH ) {
// An error occurred relating to the load of a chapter which is unreadable.
// When this happens the chapter returned in the adventure data structure is corrupted.
// Options: 1) Delete chapter. 2) Select chapter from other file. 3) Abort
if( current.getAffectedArea( ) == Incidence.CHAPTER_INCIDENCE && current.getType( ) == Incidence.XML_INCIDENCE ) {
String dialogTitle = TC.get( "ErrorSolving.Chapter.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( );
String dialogMessage = TC.get( "ErrorSolving.Chapter.Message", new String[] { current.getMessage( ), current.getAffectedResource( ) } );
String[] options = { TC.get( "GeneralText.Delete" ), TC.get( "GeneralText.Replace" ), TC.get( "GeneralText.Abort" ), TC.get( "GeneralText.ReportError" ) };
int option = showOptionDialog( dialogTitle, dialogMessage, options );
// Delete chapter
if( option == 0 ) {
String chapterName = current.getAffectedResource( );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( chapterName ) ) {
chapters.remove( j );
//this.chapterDataControlList.remove( j );
// Update selected chapter if necessary
if( chapters.size( ) == 0 ) {
// When there are no more chapters, add a new, blank one
Chapter newChapter = new Chapter( TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ) );
chapters.add( newChapter );
//chapterDataControlList.add( new ChapterDataControl (newChapter) );
}
chaptersController = new ChapterListDataControl( chapters );
dataModified( );
break;
}
}
}
// Replace chapter
else if( option == 1 ) {
boolean replaced = false;
JFileChooser xmlChooser = new JFileChooser( );
xmlChooser.setDialogTitle( TC.get( "GeneralText.Select" ) );
xmlChooser.setFileFilter( new XMLFileFilter( ) );
xmlChooser.setMultiSelectionEnabled( false );
// A file is selected
if( xmlChooser.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
// Get absolute path
String absolutePath = xmlChooser.getSelectedFile( ).getAbsolutePath( );
// Try to load chapter with it
List<Incidence> newChapterIncidences = new ArrayList<Incidence>( );
Chapter chapter = Loader.loadChapterData( AssetsController.getInputStreamCreator( ), absolutePath, incidences, true );
// IF no incidences occurred
if( chapter != null && newChapterIncidences.size( ) == 0 ) {
// Try comparing names
int found = -1;
for( int j = 0; found == -1 && j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( current.getAffectedResource( ) ) ) {
found = j;
}
}
// Replace it if found
if( found >= 0 ) {
//this.chapterDataControlList.remove( found );
chapters.set( found, chapter );
chaptersController = new ChapterListDataControl( chapters );
//chapterDataControlList.add( found, new ChapterDataControl(chapter) );
// Copy original file to project
File destinyFile = new File( this.getProjectFolder( ), chapter.getChapterPath( ) );
if( destinyFile.exists( ) )
destinyFile.delete( );
File sourceFile = new File( absolutePath );
sourceFile.copyTo( destinyFile );
replaced = true;
dataModified( );
}
}
}
// The chapter was not replaced: inform
if( !replaced ) {
mainWindow.showWarningDialog( TC.get( "ErrorSolving.Chapter.NotReplaced.Title" ), TC.get( "ErrorSolving.Chapter.NotReplaced.Message" ) );
}
}
// Report Dialog
else if( option == 3 ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
}
// Other case: abort
else {
abort = true;
break;
}
}
}
// Medium importance: the game might be slightly affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_MEDIUM ) {
// If an asset is missing or damaged. Delete references
if( current.getType( ) == Incidence.ASSET_INCIDENCE ) {
this.deleteAssetReferences( current.getAffectedResource( ) );
// if (current.getAffectedArea( ) == AssetsController.CATEGORY_ICON||current.getAffectedArea( ) == AssetsController.CATEGORY_BACKGROUND){
// mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), current.getMessage( ) );
//}else
mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.Asset.Deleted.Message", current.getAffectedResource( ) ) );
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAssessmentName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAssessmentName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
// adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAdaptationName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAdaptationName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// Abort
else {
abort = true;
break;
}
}
// Low importance: the game will not be affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_LOW ) {
if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
//adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
}
}
return abort;
}
/**
* Called when the user wants to load data from a file.
*
* @return True if a file was loaded successfully, false otherwise
*/
public boolean loadFile( ) {
return loadFile( null, true );
}
public boolean replaceSelectedChapter( Chapter newChapter ) {
chaptersController.replaceSelectedChapter( newChapter );
//mainWindow.updateTree();
mainWindow.reloadData( );
return true;
}
public NPC getNPC(String npcId){
return this.getSelectedChapterDataControl().getNPCsList( ).getNPC( npcId );
}
private boolean loadFile( String completeFilePath, boolean loadingImage ) {
boolean fileLoaded = false;
boolean hasIncedence = false;
try {
boolean loadFile = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.LoadFileTitle" ), TC.get( "Operation.LoadFileMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
loadFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
loadFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
loadFile = false;
}
}
if( loadFile && completeFilePath == null ) {
this.stopAutoSave( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.loadFromXML( );
// Show dialog
// StartDialog start = new StartDialog( StartDialog.OPEN_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs(StartDialog.OPEN_TAB );
//start.askForProject();
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( null );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
String absPath = selectedFile.getAbsolutePath( ).toLowerCase( );
if( absPath.endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else
// importGame is the same method for .ead, .jar and .zip (LO) import
this.importGame( selectedFile.getAbsolutePath( ) );
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
// if( currentZipFile == null ) {
// mainWindow.reloadData( );
//}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
return true;
}
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.LoadProject" ), getLoadingImage( ), mainWindow);
// If some file was selected
if( completeFilePath != null ) {
if( loadingImage ) {
loadingScreen.setMessage( TC.get( "Operation.LoadProject" ) );
this.loadingScreen.setVisible( true );
loadingImage = true;
}
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Load the data from the file, and update the info
List<Incidence> incidences = new ArrayList<Incidence>( );
//ls.start( );
/*AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator(completeFilePath),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ASSESSMENT),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ADAPTATION),incidences );
*/
AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator( completeFilePath ), incidences, true );
//mainWindow.setNormalState( );
// If the adventure was loaded without problems, update the data
if( loadedAdventureData != null ) {
// Update the values of the controller
currentZipFile = newFile.getAbsolutePath( );
currentZipPath = newFile.getParent( );
currentZipName = newFile.getName( );
loadedAdventureData.setProjectName( currentZipName );
adventureDataControl = new AdventureDataControl( loadedAdventureData );
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Check asset files
AssetsController.checkAssetFilesConsistency( incidences );
Incidence.sortIncidences( incidences );
// If there is any incidence
if( incidences.size( ) > 0 ) {
boolean abort = fixIncidences( incidences );
if( abort ) {
mainWindow.showInformationDialog( TC.get( "Error.LoadAborted.Title" ), TC.get( "Error.LoadAborted.Message" ) );
hasIncedence = true;
}
}
ProjectConfigData.loadFromXML( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
dataModified = false;
// The file was loaded
fileLoaded = true;
// Reloads the view of the window
mainWindow.reloadData( );
}
}
//if the file was loaded, update the RecentFiles list:
if( fileLoaded ) {
ConfigData.fileLoaded( currentZipFile );
AssetsController.resetCache( );
// Load project config file
ProjectConfigData.loadFromXML( );
startAutoSave( 15 );
// Feedback
//loadingScreen.close( );
if( !hasIncedence )
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
else
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedWithErrorTitle" ), TC.get( "Operation.FileLoadedWithErrorMessage" ) );
}
else {
// Feedback
//loadingScreen.close( );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
if( loadingImage )
//ls.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
e.printStackTrace( );
fileLoaded = false;
if( loadingImage )
loadingScreen.setVisible( false );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
Controller.gc();
return fileLoaded;
}
public boolean importJAR(){
return false;
}
public boolean importLO(){
return false;
}
/**
* Called when the user wants to save data to a file.
*
* @param saveAs
* True if the destiny file must be chosen inconditionally
* @return True if a file was saved successfully, false otherwise
*/
public boolean saveFile( boolean saveAs ) {
boolean fileSaved = false;
try {
boolean saveFile = true;
// Select a new file if it is a "Save as" action
if( saveAs ) {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProjectAs" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentLoadFolder( ), new FolderFileFilter( false, false, null ) );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Create a file to extract the name and path
File newFolder;
File newFile;
if( completeFilePath.endsWith( ".eap" ) ) {
newFile = new File( completeFilePath );
newFolder = new File( completeFilePath.substring( 0, completeFilePath.length( ) - 4 ) );
}
else {
newFile = new File( completeFilePath + ".eap" );
newFolder = new File( completeFilePath );
}
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( newFile ) ) {
if( FolderFileFilter.checkCharacters( newFolder.getName( ) ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file and the file it is not the current path of the project
if( ( this.currentZipFile == null || !newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) && ( ( !newFile.exists( ) && !newFolder.exists( ) ) || !newFolder.exists( ) || newFolder.list( ).length == 0 || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage", newFolder.getName( ) ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
//if( newFile.exists( ) )
// newFile.delete( );
if( !newFile.exists( ) )
newFile.create( );
// If this is a "Save as" operation, copy the assets from the old file to the new one
if( saveAs ) {
loadingScreen.setMessage( TC.get( "Operation.SaveProjectAs" ) );
loadingScreen.setVisible( true );
AssetsController.copyAssets( currentZipFile, newFolder.getAbsolutePath( ) );
}
// Set the new file and path
currentZipFile = newFolder.getAbsolutePath( );
currentZipPath = newFolder.getParent( );
currentZipName = newFolder.getName( );
AssetsController.createFolderStructure();
}
// If the file was not overwritten, don't save the data
else
saveFile = false;
// In case the selected folder is the same that the previous one, report an error
if( !saveFile && this.currentZipFile != null && newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) {
this.showErrorDialog( TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Title" ), TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
saveFile = false;
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
saveFile = false;
}
}
// If no file was selected, don't save the data
else
saveFile = false;
}
else {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProject" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.SaveProject" ) );
loadingScreen.setVisible( true );
}
// If the data must be saved
if( saveFile ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
// If the zip was temp file, delete it
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// If the data is not valid, show an error message
if( !valid )
mainWindow.showWarningDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventurInconsistentWarning" ) );
// Control the version number
String newValue = increaseVersionNumber( adventureDataControl.getAdventureData( ).getVersionNumber( ) );
adventureDataControl.getAdventureData( ).setVersionNumber( newValue );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
File eapFile = new File( currentZipFile + ".eap" );
if( !eapFile.exists( ) )
eapFile.create( );
// Set modified to false and update the window title
dataModified = false;
mainWindow.updateTitle( );
// The file was saved
fileSaved = true;
}
}
//If the file was saved, update the recent files list:
if( fileSaved ) {
ConfigData.fileLoaded( currentZipFile );
ProjectConfigData.storeToXML( );
AssetsController.resetCache( );
// also, look for adaptation and assessment folder, and delete them
File currentAssessFolder = new File( currentZipFile + File.separator + "assessment" );
if( currentAssessFolder.exists( ) ) {
File[] files = currentAssessFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAssessFolder.delete( );
}
File currentAdaptFolder = new File( currentZipFile + File.separator + "adaptation" );
if( currentAdaptFolder.exists( ) ) {
File[] files = currentAdaptFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAdaptFolder.delete( );
}
}
}
catch( Exception e ) {
fileSaved = false;
mainWindow.showInformationDialog( TC.get( "Operation.FileNotSavedTitle" ), TC.get( "Operation.FileNotSavedMessage" ) );
}
Controller.gc();
loadingScreen.setVisible( false );
return fileSaved;
}
/**
* Increase the game version number
*
* @param digits
* @param index
* @return the version number after increase it
*/
private String increaseVersionNumber( char[] digits, int index ) {
if( digits[index] != '9' ) {
// increase in "1" the ASCII code
digits[index]++;
return new String( digits );
}
else if( index == 0 ) {
char[] aux = new char[ digits.length + 1 ];
aux[0] = '1';
aux[1] = '0';
for( int i = 2; i < aux.length; i++ )
aux[i] = digits[i - 1];
return new String( aux );
}
else {
digits[index] = '0';
return increaseVersionNumber( digits, --index );
}
}
private String increaseVersionNumber( String versionNumber ) {
char[] digits = versionNumber.toCharArray( );
return increaseVersionNumber( digits, digits.length - 1 );
}
public void importChapter( ) {
}
public void importGame( ) {
importGame( null );
}
public void importGame( String eadPath ) {
boolean importGame = true;
java.io.File selectedFile = null;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
importGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
importGame = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
importGame = false;
}
}
if( importGame ) {
if (eadPath.endsWith( ".zip" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportLO.InfoMessage" ) );
else if (eadPath.endsWith( ".jar" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportJAR.InfoMessage" ));
// Ask origin file
JFileChooser chooser = new JFileChooser( );
chooser.setFileFilter( new EADFileFilter( ) );
chooser.setMultiSelectionEnabled( false );
chooser.setCurrentDirectory( new File( getCurrentExportSaveFolder( ) ) );
int option = JFileChooser.APPROVE_OPTION;
if( eadPath == null )
option = chooser.showOpenDialog( mainWindow );
if( option == JFileChooser.APPROVE_OPTION ) {
java.io.File originFile = null;
if( eadPath == null )
originFile = chooser.getSelectedFile( );
else
originFile = new File( eadPath );
// if( !originFile.getAbsolutePath( ).endsWith( ".ead" ) )
// originFile = new java.io.File( originFile.getAbsolutePath( ) + ".ead" );
// If the file not exists display error
if( !originFile.exists( ) )
mainWindow.showErrorDialog( TC.get( "Error.Import.FileNotFound.Title" ), TC.get( "Error.Import.FileNotFound.Title", originFile.getName( ) ) );
// Otherwise ask folder for the new project
else {
boolean create = false;
java.io.File selectedDir = null;
// Prompt main folder of the project
// ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
// If some folder is selected, check all characters are correct
int op = start.showStartDialog( );
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFolder.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new java.io.File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new java.io.File( selectedFolder.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.deleteAll( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
} // FIXME: else branch to return to previous dialog when the user tries to assign an existing name to his project
// and select "no" in re-writing confirmation panel
}
else {
create = true;
}
}
else {
// Create new folder?
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove();
// Create the new project?
if( create ) {
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ImportProject" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ImportProject" ) );
loadingScreen.setVisible( true );
//AssetsController.createFolderStructure();
if( !selectedDir.exists( ) )
selectedDir.mkdirs( );
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
boolean correctFile = true;
// Unzip directory
if (eadPath.endsWith( ".ead" ))
File.unzipDir( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) );
else if (eadPath.endsWith( ".zip" )){
// import EadJAR returns false when selected jar is not a eadventure jar
if (!File.importEadventureLO( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get( "Operation.ImportLO.FileNotLoadedMessage") );
correctFile = false;
}
}else if (eadPath.endsWith( ".jar" )){
// import EadLO returns false when selected zip is not a eadventure LO
if (!File.importEadventureJar( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.ImportJAR.FileNotLoaded") );
correctFile = false;
}
}
//ProjectConfigData.loadFromXML( );
// Load new project
if (correctFile) {
loadFile( selectedDir.getAbsolutePath( ), false );
//loadingScreen.close( );
loadingScreen.setVisible( false );
} else {
//remove .eapFile
selectedFile.delete( );
selectedDir.delete( );
}
}
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.FileNotLoadedMessage" ));
}
}
public boolean exportGame( ) {
return exportGame( null );
}
public boolean exportGame( String targetFilePath ) {
boolean exportGame = true;
boolean exported = false;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String selectedPath = targetFilePath;
if( selectedPath == null )
selectedPath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new EADFileFilter( ) );
if( selectedPath != null ) {
if( !selectedPath.toLowerCase( ).endsWith( ".ead" ) )
selectedPath = selectedPath + ".ead";
java.io.File destinyFile = new File( selectedPath );
// Check the destinyFile is not in the project folder
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
// If the file exists, ask to overwrite
if( !destinyFile.exists( ) || targetFilePath != null || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsEAD" ), getLoadingImage( ), mainWindow);
if( targetFilePath == null ) {
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsEAD" ) );
loadingScreen.setVisible( true );
}
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
exported = true;
if( targetFilePath == null )
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
if( targetFilePath == null )
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
exported = false;
}
return exported;
}
public boolean createBackup( String targetFilePath ) {
boolean fileSaved = false;
if( targetFilePath == null )
targetFilePath = currentZipFile + ".tmp";
File category = new File( currentZipFile, "backup" );
try {
boolean valid = chaptersController.isValid( null, null );
category.create( );
if( Writer.writeData( currentZipFile + File.separatorChar + "backup", adventureDataControl, valid ) ) {
fileSaved = true;
}
if( fileSaved ) {
String selectedPath = targetFilePath;
if( selectedPath != null ) {
java.io.File destinyFile = new File( selectedPath );
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || targetFilePath != null ) {
destinyFile.delete( );
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) )
fileSaved = true;
}
}
else
fileSaved = false;
}
}
}
catch( Exception e ) {
fileSaved = false;
}
if( category.exists( ) ) {
category.deleteAll( );
}
return fileSaved;
}
public void exportStandaloneGame( ) {
boolean exportGame = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new JARFileFilter());
if( completeFilePath != null ) {
if( !completeFilePath.toLowerCase( ).endsWith( ".jar" ) )
completeFilePath = completeFilePath + ".jar";
// If the file exists, ask to overwrite
java.io.File destinyFile = new File( completeFilePath );
// Check the destinyFile is not in the project folder
if( isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsJAR" ) );
loadingScreen.setVisible( true );
if( Writer.exportStandalone( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotSavedTitle"), TC.get("Operation.FileNotSavedMessage") );
}
}
public void exportToLOM( ) {
boolean exportFile = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportFile = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportFile = false;
}
if( exportFile ) {
// Ask the data of the Learning Object:
ExportToLOMDialog dialog = new ExportToLOMDialog( TC.get( "Operation.ExportToLOM.DefaultValue" ) );
String loName = dialog.getLomName( );
String authorName = dialog.getAuthorName( );
String organization = dialog.getOrganizationName( );
boolean windowed = dialog.getWindowed( );
int type = dialog.getType( );
boolean validated = dialog.isValidated( );
if( type == 2 && !hasScormProfiles( SCORM12 ) ) {
// error situation: both profiles must be scorm 1.2 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM12.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM12.BadProfiles.Message" ) );
}
else if( type == 3 && !hasScormProfiles( SCORM2004 ) ) {
// error situation: both profiles must be scorm 2004 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004.BadProfiles.Message" ) );
}
else if( type == 4 && !hasScormProfiles( AGREGA ) ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
}
//TODO comprobaciones de perfiles
// else if( type == 5 ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
// mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
if( validated ) {
//String loName = this.showInputDialog( TextConstants.getText( "Operation.ExportToLOM.Title" ), TextConstants.getText( "Operation.ExportToLOM.Message" ), TextConstants.getText( "Operation.ExportToLOM.DefaultValue" ));
if( loName != null && !loName.equals( "" ) && !loName.contains( " " ) ) {
//Check authorName & organization
if( authorName != null && authorName.length( ) > 5 && organization != null && organization.length( ) > 5 ) {
//Ask for the name of the zip
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new FileFilter( ) {
@Override
public boolean accept( java.io.File arg0 ) {
return arg0.getAbsolutePath( ).toLowerCase( ).endsWith( ".zip" ) || arg0.isDirectory( );
}
@Override
public String getDescription( ) {
return "Zip files (*.zip)";
}
} );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Add the ".zip" if it is not present in the name
if( !completeFilePath.toLowerCase( ).endsWith( ".zip" ) )
completeFilePath += ".zip";
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Check the selected file is contained in a valid folder
if( isValidTargetFile( newFile ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file
if( !newFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", newFile.getName( ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
try {
if( newFile.exists( ) )
newFile.delete( );
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsJAR" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsLO" ) );
loadingScreen.setVisible( true );
this.updateLOMLanguage( );
if( type == 0 && Writer.exportAsLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 1 && Writer.exportAsWebCTObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 2 && Writer.exportAsSCORM( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 3 && Writer.exportAsSCORM2004( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 4 && Writer.exportAsAGREGA( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 5 && Writer.exportAsLAMSLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ){
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
ReportDialog.GenerateErrorReport( e, true, TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
}
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Title" ), TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
}
}
/**
* Check if assessment and adaptation profiles are both scorm 1.2 or scorm
* 2004
*
* @param scormType
* the scorm type, 1.2 or 2004
* @return
*/
private boolean hasScormProfiles( int scormType ) {
if( scormType == SCORM12 ) {
// check that adaptation and assessment profiles are scorm 1.2 profiles
return chaptersController.hasScorm12Profiles( adventureDataControl );
}
else if( scormType == SCORM2004 || scormType == AGREGA ) {
// check that adaptation and assessment profiles are scorm 2004 profiles
return chaptersController.hasScorm2004Profiles( adventureDataControl );
}
return false;
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void run( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
// First update flags
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.normalRun( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void debugRun( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.debug( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Check if the current project is saved before run. If not, ask user to
* save it.
*
* @return if false is returned, the game will not be launched
*/
private boolean canBeRun( ) {
if( dataModified ) {
if( mainWindow.showStrictConfirmDialog( TC.get( "Run.CanBeRun.Title" ), TC.get( "Run.CanBeRun.Text" ) ) ) {
this.saveFile( false );
return true;
}
else
return false;
}
else
return true;
}
/**
* Determines if the target file of an exportation process is valid. The
* file cannot be located neither inside the project folder, nor inside the
* web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetFile( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ), getProjectFolderFile( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Determines if the target folder for a new project is valid. The folder
* cannot be located inside the web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetProject( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Exits from the aplication.
*/
public void exit( ) {
boolean exit = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.ExitTitle" ), TC.get( "Operation.ExitMessage" ) );
// If the data must be saved, lexit only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exit = saveFile( false );
// If the data must not be saved, exit directly
else if( option == JOptionPane.NO_OPTION )
exit = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exit = false;
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
}
// Exit the aplication
if( exit ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
//AssetsController.cleanVideoCache( );
System.exit( 0 );
}
}
/**
* Checks if the adventure is valid or not. It shows information to the
* user, whether the data is valid or not.
*/
public boolean checkAdventureConsistency( ) {
return checkAdventureConsistency( true );
}
public boolean checkAdventureConsistency( boolean showSuccessFeedback ) {
// Create a list to store the incidences
List<String> incidences = new ArrayList<String>( );
// Check all the chapters
boolean valid = chaptersController.isValid( null, incidences );
// If the data is valid, show a dialog with the information
if( valid ) {
if( showSuccessFeedback )
mainWindow.showInformationDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventureConsistentReport" ) );
// If it is not valid, show a dialog with the problems
}
else
new InvalidReportDialog( incidences, TC.get( "Operation.AdventureInconsistentReport" ) );
return valid;
}
public void checkFileConsistency( ) {
}
/**
* Shows the adventure data dialog editor.
*/
public void showAdventureDataDialog( ) {
new AdventureDataDialog( );
}
/**
* Shows the LOM data dialog editor.
*/
public void showLOMDataDialog( ) {
isLomEs = false;
new LOMDialog( adventureDataControl.getLomController( ) );
}
/**
* Shows the LOM for SCORM packages data dialog editor.
*/
public void showLOMSCORMDataDialog( ) {
isLomEs = false;
new IMSDialog( adventureDataControl.getImsController( ) );
}
/**
* Shows the LOMES for AGREGA packages data dialog editor.
*/
public void showLOMESDataDialog( ) {
isLomEs = true;
new LOMESDialog( adventureDataControl.getLOMESController( ) );
}
/**
* Shows the GUI style selection dialog.
*/
public void showGUIStylesDialog( ) {
adventureDataControl.showGUIStylesDialog( );
}
public void changeToolGUIStyleDialog( int optionSelected ){
if (optionSelected != 1){
adventureDataControl.setGUIStyleDialog( optionSelected );
}
}
/**
* Asks for confirmation and then deletes all unreferenced assets. Checks
* for animations indirectly referenced assets.
*/
public void deleteUnsuedAssets( ) {
if( !this.showStrictConfirmDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.Warning" ) ) )
return;
int deletedAssetCount = 0;
ArrayList<String> assets = new ArrayList<String>( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BACKGROUND ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_VIDEO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_CURSOR ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BUTTON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ICON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_STYLED_TEXT ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ARROW_BOOK ) )
if( !assets.contains( temp ) )
assets.add( temp );
/* assets.remove( "gui/cursors/arrow_left.png" );
assets.remove( "gui/cursors/arrow_right.png" ); */
for( String temp : assets ) {
int references = 0;
references = countAssetReferences( temp );
if( references == 0 ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp ).delete( );
deletedAssetCount++;
}
}
assets.clear( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION ) )
if( !assets.contains( temp ) )
assets.add( temp );
int i = 0;
while( i < assets.size( ) ) {
String temp = assets.get( i );
if( countAssetReferences( AssetsController.removeSuffix( temp ) ) != 0 ) {
assets.remove( temp );
if( temp.endsWith( "eaa" ) ) {
Animation a = Loader.loadAnimation( AssetsController.getInputStreamCreator( ), temp, new EditorImageLoader( ) );
for( Frame f : a.getFrames( ) ) {
if( f.getUri( ) != null && assets.contains( f.getUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
if( f.getSoundUri( ) != null && assets.contains( f.getSoundUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getSoundUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
}
}
else {
int j = 0;
while( j < assets.size( ) ) {
if( assets.get( j ).startsWith( AssetsController.removeSuffix( temp ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
else
j++;
}
}
}
else {
i++;
}
}
for( String temp2 : assets ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp2 ).delete( );
deletedAssetCount++;
}
if( deletedAssetCount != 0 )
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.AssetsDeleted", new String[] { String.valueOf( deletedAssetCount ) } ) );
else
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.NoUnsuedAssetsFound" ) );
}
/**
* Shows the flags dialog.
*/
public void showEditFlagDialog( ) {
new VarsFlagsDialog( new VarFlagsController( getVarFlagSummary( ) ) );
}
/**
* Sets a new selected chapter with the given index.
*
* @param selectedChapter
* Index of the new selected chapter
*/
public void setSelectedChapter( int selectedChapter ) {
chaptersController.setSelectedChapterInternal( selectedChapter );
mainWindow.reloadData( );
}
public void updateVarFlagSummary( ) {
chaptersController.updateVarFlagSummary( );
}
/**
* Adds a new chapter to the adventure. This method asks for the title of
* the chapter to the user, and updates the view of the application if a new
* chapter was added.
*/
public void addChapter( ) {
addTool( new AddChapterTool( chaptersController ) );
}
/**
* Deletes the selected chapter from the adventure. This method asks the
* user for confirmation, and updates the view if needed.
*/
public void deleteChapter( ) {
addTool( new DeleteChapterTool( chaptersController ) );
}
/**
* Moves the selected chapter to the previous position of the chapter's
* list.
*/
public void moveChapterUp( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_UP, chaptersController ) );
}
/**
* Moves the selected chapter to the next position of the chapter's list.
*
*/
public void moveChapterDown( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_DOWN, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods to edit and get the adventure general data (title and description)
/**
* Returns the title of the adventure.
*
* @return Adventure's title
*/
public String getAdventureTitle( ) {
return adventureDataControl.getTitle( );
}
/**
* Returns the description of the adventure.
*
* @return Adventure's description
*/
public String getAdventureDescription( ) {
return adventureDataControl.getDescription( );
}
/**
* Returns the LOM controller.
*
* @return Adventure LOM controller.
*
*/
public LOMDataControl getLOMDataControl( ) {
return adventureDataControl.getLomController( );
}
/**
* Sets the new title of the adventure.
*
* @param title
* Title of the adventure
*/
public void setAdventureTitle( String title ) {
// If the value is different
if( !title.equals( adventureDataControl.getTitle( ) ) ) {
// Set the new title and modify the data
adventureDataControl.setTitle( title );
}
}
/**
* Sets the new description of the adventure.
*
* @param description
* Description of the adventure
*/
public void setAdventureDescription( String description ) {
// If the value is different
if( !description.equals( adventureDataControl.getDescription( ) ) ) {
// Set the new description and modify the data
adventureDataControl.setDescription( description );
}
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods that perform specific tasks for the microcontrollers
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId ) {
return isElementIdValid( elementId, true );
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user
* if showError is true
*
* @param elementId
* Element identifier to be checked
* @param showError
* True if the error message must be shown
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId, boolean showError ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) && !elementId.contains( "'" )) {
// If the identifier doesn't exist already
if( !getIdentifierSummary( ).existsId( elementId ) ) {
// If the identifier is not a reserved identifier
if( !elementId.equals( Player.IDENTIFIER ) && !elementId.equals( TC.get( "ConversationLine.PlayerName" ) ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) ){
elementIdValid = isCharacterValid(elementId);
if (!elementIdValid)
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorCharacter" ) );
}
// Show non-letter first character error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show invalid identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorReservedIdentifier", elementId ) );
}
// Show repeated identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorAlreadyUsed" ) );
}
// Show blank spaces error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
public boolean isCharacterValid(String elementId){
Character chId;
boolean isValid = true;
int i=1;
while (i < elementId.length( ) && isValid) {
chId = elementId.charAt( i );
- if (chId =='&' || chId == '%' || chId == '?' || chId == '�' ||
- chId =='�' || chId == '!' || chId== '=' || chId == '$' ||
- chId == '*' || chId == '/' || chId == '(' || chId == ')' )
- isValid = false;
- i++;
+ isValid = Character.isLetterOrDigit( chId );
+ i++;
}
return isValid;
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isPropertyIdValid( String elementId ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) )
elementIdValid = true;
// Show non-letter first character error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show blank spaces error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
/**
* This method returns the absolute path of the background image of the
* given scene.
*
* @param sceneId
* Scene id
* @return Path to the background image, null if it was not found
*/
public String getSceneImagePath( String sceneId ) {
String sceneImagePath = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) )
sceneImagePath = scene.getPreviewBackground( );
return sceneImagePath;
}
/**
* This method returns the trajectory of a scene from its id.
*
* @param sceneId
* Scene id
* @return Trajectory of the scene, null if it was not found
*/
public Trajectory getSceneTrajectory( String sceneId ) {
Trajectory trajectory = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) && scene.getTrajectory( ).hasTrajectory( ) )
trajectory = (Trajectory) scene.getTrajectory( ).getContent( );
return trajectory;
}
/**
* This method returns the absolute path of the default image of the player.
*
* @return Default image of the player
*/
public String getPlayerImagePath( ) {
if( getSelectedChapterDataControl( ) != null )
return getSelectedChapterDataControl( ).getPlayer( ).getPreviewImage( );
else
return null;
}
/**
* Returns the player
*/
public Player getPlayer(){
return (Player)getSelectedChapterDataControl( ).getPlayer( ).getContent( );
}
/**
* This method returns the absolute path of the default image of the given
* element (item or character).
*
* @param elementId
* Id of the element
* @return Default image of the requested element
*/
public String getElementImagePath( String elementId ) {
String elementImage = null;
// Search for the image in the items, comparing the identifiers
for( ItemDataControl item : getSelectedChapterDataControl( ).getItemsList( ).getItems( ) )
if( elementId.equals( item.getId( ) ) )
elementImage = item.getPreviewImage( );
// Search for the image in the characters, comparing the identifiers
for( NPCDataControl npc : getSelectedChapterDataControl( ).getNPCsList( ).getNPCs( ) )
if( elementId.equals( npc.getId( ) ) )
elementImage = npc.getPreviewImage( );
// Search for the image in the items, comparing the identifiers
for( AtrezzoDataControl atrezzo : getSelectedChapterDataControl( ).getAtrezzoList( ).getAtrezzoList( ) )
if( elementId.equals( atrezzo.getId( ) ) )
elementImage = atrezzo.getPreviewImage( );
return elementImage;
}
/**
* Counts all the references to a given asset in the entire script.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
* @return Number of references to the given asset
*/
public int countAssetReferences( String assetPath ) {
return adventureDataControl.countAssetReferences( assetPath ) + chaptersController.countAssetReferences( assetPath );
}
/**
* Gets a list with all the assets referenced in the chapter along with the
* types of those assets
*
* @param assetPaths
* @param assetTypes
*/
public void getAssetReferences( List<String> assetPaths, List<Integer> assetTypes ) {
adventureDataControl.getAssetReferences( assetPaths, assetTypes );
chaptersController.getAssetReferences( assetPaths, assetTypes );
}
/**
* Deletes a given asset from the script, removing all occurrences.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
*/
public void deleteAssetReferences( String assetPath ) {
adventureDataControl.deleteAssetReferences( assetPath );
chaptersController.deleteAssetReferences( assetPath );
}
/**
* Counts all the references to a given identifier in the entire script.
*
* @param id
* Identifier to which the references must be found
* @return Number of references to the given identifier
*/
public int countIdentifierReferences( String id ) {
return getSelectedChapterDataControl( ).countIdentifierReferences( id );
}
/**
* Deletes a given identifier from the script, removing all occurrences.
*
* @param id
* Identifier to be deleted
*/
public void deleteIdentifierReferences( String id ) {
chaptersController.deleteIdentifierReferences( id );
}
/**
* Replaces a given identifier with another one, in all the occurrences in
* the script.
*
* @param oldId
* Old identifier to be replaced
* @param newId
* New identifier to replace the old one
*/
public void replaceIdentifierReferences( String oldId, String newId ) {
getSelectedChapterDataControl( ).replaceIdentifierReferences( oldId, newId );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods linked with the GUI
/**
* Updates the chapter menu with the new names of the chapters.
*/
public void updateChapterMenu( ) {
mainWindow.updateChapterMenu( );
}
/**
* Updates the tree of the main window.
*/
public void updateStructure( ) {
mainWindow.updateStructure( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadPanel( ) {
mainWindow.reloadPanel( );
}
public void updatePanel( ) {
mainWindow.updatePanel( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadData( ) {
mainWindow.reloadData( );
}
/**
* Returns the last window opened by the application.
*
* @return Last window opened
*/
public Window peekWindow( ) {
return mainWindow.peekWindow( );
}
/**
* Pushes a new window in the windows stack.
*
* @param window
* Window to push
*/
public void pushWindow( Window window ) {
mainWindow.pushWindow( window );
}
/**
* Pops the last window pushed into the stack.
*/
public void popWindow( ) {
mainWindow.popWindow( );
}
/**
* Shows a load dialog to select multiple files.
*
* @param filter
* File filter for the dialog
* @return Full path of the selected files, null if no files were selected
*/
public String[] showMultipleSelectionLoadDialog( FileFilter filter ) {
return mainWindow.showMultipleSelectionLoadDialog( currentZipPath, filter );
}
/**
* Shows a dialog with the options "Yes" and "No", with the given title and
* text.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @return True if the "Yes" button was pressed, false otherwise
*/
public boolean showStrictConfirmDialog( String title, String message ) {
return mainWindow.showStrictConfirmDialog( title, message );
}
/**
* Shows a dialog with the given set of options.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param options
* Array of strings containing the options of the dialog
* @return The index of the option selected, JOptionPane.CLOSED_OPTION if
* the dialog was closed.
*/
public int showOptionDialog( String title, String message, String[] options ) {
return mainWindow.showOptionDialog( title, message, options );
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param defaultValue
* Default value of the dialog
* @return String typed in the dialog, null if the cancel button was pressed
*/
public String showInputDialog( String title, String message, String defaultValue ) {
return mainWindow.showInputDialog( title, message, defaultValue );
}
public String showInputDialog( String title, String message) {
return mainWindow.showInputDialog( title, message);
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param selectionValues
* Possible selection values of the dialog
* @return Option selected in the dialog, null if the cancel button was
* pressed
*/
public String showInputDialog( String title, String message, Object[] selectionValues ) {
return mainWindow.showInputDialog( title, message, selectionValues );
}
/**
* Uses the GUI to show an error dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
*/
public void showErrorDialog( String title, String message ) {
mainWindow.showErrorDialog( title, message );
}
public void showCustomizeGUIDialog( ) {
new CustomizeGUIDialog( this.adventureDataControl );
}
public boolean isFolderLoaded( ) {
return chaptersController.isAnyChapterSelected( );
}
public String getEditorMinVersion( ) {
return "1.0b";
}
public String getEditorVersion( ) {
return "1.0b";
}
public void updateLOMLanguage( ) {
this.adventureDataControl.getLomController( ).updateLanguage( );
}
public void updateIMSLanguage( ) {
this.adventureDataControl.getImsController( ).updateLanguage( );
}
public void showAboutDialog( ) {
try {
JDialog dialog = new JDialog( Controller.getInstance( ).peekWindow( ), TC.get( "About" ), Dialog.ModalityType.TOOLKIT_MODAL );
dialog.getContentPane( ).setLayout( new BorderLayout( ) );
JPanel panel = new JPanel();
panel.setLayout( new BorderLayout() );
File file = new File( ConfigData.getAboutFile( ) );
if( file.exists( ) ) {
JEditorPane pane = new JEditorPane( );
pane.setPage( file.toURI( ).toURL( ) );
pane.setEditable( false );
panel.add( pane, BorderLayout.CENTER );
}
JPanel version = new JPanel();
version.setLayout( new BorderLayout() );
JButton checkVersion = new JButton(TC.get( "About.CheckNewVersion" ));
version.add(checkVersion, BorderLayout. CENTER);
final JLabel label = new JLabel("");
version.add(label, BorderLayout.SOUTH);
checkVersion.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
java.io.BufferedInputStream in = null;
try {
in = new java.io.BufferedInputStream(new java.net.URL("http://e-adventure.e-ucm.es/files/version").openStream());
byte data[] = new byte[1024];
int bytes = 0;
String a = null;
while((bytes = in.read(data,0,1024)) >= 0)
{
a = new String(data, 0, bytes);
}
a = a.substring( 0, a.length( ) - 1 );
System.out.println(getCurrentVersion().split( "-" )[0] + " " + a);
if (getCurrentVersion().split( "-" )[0].equals( a )) {
label.setText(TC.get( "About.LatestRelease" ));
} else {
label.setText( TC.get("About.NewReleaseAvailable"));
}
label.updateUI( );
in.close();
}
catch( IOException e1 ) {
label.setText( TC.get( "About.LatestRelease" ) );
label.updateUI( );
}
}
});
panel.add( version, BorderLayout.NORTH );
dialog.getContentPane( ).add( panel, BorderLayout.CENTER );
dialog.setSize( 275, 560 );
Dimension screenSize = Toolkit.getDefaultToolkit( ).getScreenSize( );
dialog.setLocation( ( screenSize.width - dialog.getWidth( ) ) / 2, ( screenSize.height - dialog.getHeight( ) ) / 2 );
dialog.setVisible( true );
}
catch( IOException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWERROR" );
}
}
private String getCurrentVersion() {
File moreinfo = new File( "RELEASE" );
String release = null;
if( moreinfo.exists( ) ) {
try {
FileInputStream fis = new FileInputStream( moreinfo );
BufferedInputStream bis = new BufferedInputStream( fis );
int nextChar = -1;
while( ( nextChar = bis.read( ) ) != -1 ) {
if( release == null )
release = "" + (char) nextChar;
else
release += (char) nextChar;
}
if( release != null ) {
return release;
}
}
catch( Exception ex ) {
}
}
return "NOVERSION";
}
public AssessmentProfilesDataControl getAssessmentController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAssessmentProfilesDataControl( );
}
public AdaptationProfilesDataControl getAdaptationController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdaptationProfilesDataControl( );
}
public boolean isCommentaries( ) {
return this.adventureDataControl.isCommentaries( );
}
public void setCommentaries( boolean b ) {
this.adventureDataControl.setCommentaries( b );
}
public boolean isKeepShowing( ) {
return this.adventureDataControl.isKeepShowing( );
}
public void setKeepShowing( boolean b ) {
this.adventureDataControl.setKeepShowing( b );
}
/**
* Returns an int value representing the current language used to display
* the editor
*
* @return
*/
public String getLanguage( ) {
return this.languageFile;
}
/**
* Get the default lenguage
* @return name of default language in standard internationalization
*/
public String getDefaultLanguage( ) {
return ReleaseFolders.LANGUAGE_DEFAULT;
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window always
*
* @param language
*/
public void setLanguage( String language ) {
setLanguage( language, true );
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window if reloadData is true
*
* @param language
*/
public void setLanguage( String language, boolean reloadData ) {
// image loading route
String dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + language + "/Editor2D-Loading.png";
// if there isn't file, load the default file
File fichero = new File(dirImageLoading);
if (!fichero.exists( ))
dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + getDefaultLanguage( ) + "/Editor2D-Loading.png";
//about file route
String dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getAboutFilePath( language );
File fichero2 = new File(dirAboutFile);
if (!fichero2.exists( ))
dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getDefaultAboutFilePath( );
ConfigData.setLanguangeFile( ReleaseFolders.getLanguageFilePath( language ), dirAboutFile, dirImageLoading );
languageFile = language;
TC.loadStrings( ReleaseFolders.getLanguageFilePath4Editor( true, languageFile ) );
TC.appendStrings( ReleaseFolders.getLanguageFilePath4Editor( false, languageFile ) );
loadingScreen.setImage( getLoadingImage( ) );
if( reloadData )
mainWindow.reloadData( );
}
public String getLoadingImage( ) {
return ConfigData.getLoadingImage( );
}
public void showGraphicConfigDialog( ) {
// Show the dialog
// GraphicConfigDialog guiStylesDialog = new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
// If the new GUI style is different from the current, and valid, change the value
/* int optionSelected = guiStylesDialog.getOptionSelected( );
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
adventureDataControl.setGraphicConfig( optionSelected );
}*/
}
public void changeToolGraphicConfig( int optionSelected ) {
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
// this.grafhicDialog.cambiarCheckBox( );
adventureDataControl.setGraphicConfig( optionSelected );
}
}
// METHODS TO MANAGE UNDO/REDO
public boolean addTool( Tool tool ) {
boolean added = chaptersController.addTool( tool );
//tsd.update();
return added;
}
public void undoTool( ) {
chaptersController.undoTool( );
//tsd.update();
}
public void redoTool( ) {
chaptersController.redoTool( );
//tsd.update();
}
public void pushLocalToolManager( ) {
chaptersController.pushLocalToolManager( );
}
public void popLocalToolManager( ) {
chaptersController.popLocalToolManager( );
}
public void search( ) {
new SearchDialog( );
}
public boolean getAutoSaveEnabled( ) {
if( ProjectConfigData.existsKey( "autosave" ) ) {
String temp = ProjectConfigData.getProperty( "autosave" );
if( temp.equals( "yes" ) ) {
return true;
}
else {
return false;
}
}
return true;
}
public void setAutoSaveEnabled( boolean selected ) {
if( selected != getAutoSaveEnabled( ) ) {
ProjectConfigData.setProperty( "autosave", ( selected ? "yes" : "no" ) );
startAutoSave( 15 );
}
}
/**
* @return the isLomEs
*/
public boolean isLomEs( ) {
return isLomEs;
}
public int getGUIConfigConfiguration(){
return this.adventureDataControl.getGraphicConfig( );
}
public String getDefaultExitCursorPath( ) {
String temp = this.adventureDataControl.getCursorPath( "exit" );
if( temp != null && temp.length( ) > 0 )
return temp;
else
return "gui/cursors/exit.png";
}
public AdvancedFeaturesDataControl getAdvancedFeaturesController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdvancedFeaturesController( );
}
public static Color generateColor( int i ) {
int r = ( i * 180 ) % 256;
int g = ( ( i + 4 ) * 130 ) % 256;
int b = ( ( i + 2 ) * 155 ) % 256;
if( r > 250 && g > 250 && b > 250 ) {
r = 0;
g = 0;
b = 0;
}
return new Color( r, g, b );
}
private static final Runnable gc = new Runnable() { public void run() { System.gc( );} };
/**
* Public method to perform garbage collection on a different thread.
*/
public static void gc() {
new Thread(gc).start( );
}
public static java.io.File createTempDirectory() throws IOException
{
final java.io.File temp;
temp = java.io.File.createTempFile("temp", Long.toString(System.nanoTime()));
if(!(temp.delete()))
throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
if(!(temp.mkdir()))
throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
return (temp);
}
public DefaultClickAction getDefaultCursorAction( ) {
return this.adventureDataControl.getDefaultClickAction( );
}
public void setDefaultCursorAction( DefaultClickAction defaultClickAction ) {
this.adventureDataControl.setDefaultClickAction(defaultClickAction);
}
public Perspective getPerspective() {
return this.adventureDataControl.getPerspective( );
}
public void setPerspective( Perspective perspective ) {
this.adventureDataControl.setPerspective( perspective );
}
}
| true | true | public void startAutoSave( int minutes ) {
stopAutoSave( );
if( ( ProjectConfigData.existsKey( "autosave" ) && ProjectConfigData.getProperty( "autosave" ).equals( "yes" ) ) || !ProjectConfigData.existsKey( "autosave" ) ) {
/* autoSaveTimer = new Timer();
autoSave = new AutoSave();
autoSaveTimer.schedule(autoSave, 10000, minutes * 60 * 1000);
*/}
if( !ProjectConfigData.existsKey( "autosave" ) )
ProjectConfigData.setProperty( "autosave", "yes" );
}
public void stopAutoSave( ) {
if( autoSaveTimer != null ) {
autoSaveTimer.cancel( );
autoSave.stop( );
autoSaveTimer = null;
}
autoSave = null;
}
//private ToolSystemDebugger tsd;
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// General data functions of the aplication
/**
* Returns the complete path to the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public String getProjectFolder( ) {
return currentZipFile;
}
/**
* Returns the File object representing the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public File getProjectFolderFile( ) {
return new File( currentZipFile );
}
/**
* Returns the name of the file currently open.
*
* @return The name of the current file
*/
public String getFileName( ) {
String filename;
// Show "New" if no current file is currently open
if( currentZipName != null )
filename = currentZipName;
else
filename = "http://e-adventure.e-ucm.es";
return filename;
}
/**
* Returns the parent path of the file being currently edited.
*
* @return Parent path of the current file
*/
public String getFilePath( ) {
return currentZipPath;
}
/**
* Returns an array with the chapter titles.
*
* @return Array with the chapter titles
*/
public String[] getChapterTitles( ) {
return chaptersController.getChapterTitles( );
}
/**
* Returns the index of the chapter currently selected.
*
* @return Index of the selected chapter
*/
public int getSelectedChapter( ) {
return chaptersController.getSelectedChapter( );
}
/**
* Returns the selected chapter data controller.
*
* @return The selected chapter data controller
*/
public ChapterDataControl getSelectedChapterDataControl( ) {
return chaptersController.getSelectedChapterDataControl( );
}
/**
* Returns the identifier summary.
*
* @return The identifier summary
*/
public IdentifierSummary getIdentifierSummary( ) {
return chaptersController.getIdentifierSummary( );
}
/**
* Returns the varFlag summary.
*
* @return The varFlag summary
*/
public VarFlagSummary getVarFlagSummary( ) {
return chaptersController.getVarFlagSummary( );
}
public ChapterListDataControl getCharapterList( ) {
return chaptersController;
}
/**
* Returns whether the data has been modified since the last save.
*
* @return True if the data has been modified, false otherwise
*/
public boolean isDataModified( ) {
return dataModified;
}
/**
* Called when the data has been modified, it sets the value to true.
*/
public void dataModified( ) {
// If the data were not modified, change the value and set the new title of the window
if( !dataModified ) {
dataModified = true;
mainWindow.updateTitle( );
}
}
public boolean isPlayTransparent( ) {
if( adventureDataControl == null ) {
return false;
}
return adventureDataControl.getPlayerMode( ) == DescriptorData.MODE_PLAYER_1STPERSON;
}
public void swapPlayerMode( boolean showConfirmation ) {
addTool( new SwapPlayerModeTool( showConfirmation, adventureDataControl, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions that perform usual application actions
/**
* This method creates a new file with it's respective data.
*
* @return True if the new data was created successfully, false otherwise
*/
public boolean newFile( int fileType ) {
boolean fileCreated = false;
if( fileType == Controller.FILE_ADVENTURE_1STPERSON_PLAYER || fileType == Controller.FILE_ADVENTURE_3RDPERSON_PLAYER )
fileCreated = newAdventureFile( fileType );
else if( fileType == Controller.FILE_ASSESSMENT ) {
//fileCreated = newAssessmentFile();
}
else if( fileType == Controller.FILE_ADAPTATION ) {
//fileCreated = newAdaptationFile();
}
if( fileCreated )
AssetsController.resetCache( );
return fileCreated;
}
public boolean newFile( ) {
boolean createNewFile = true;
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.NewFileTitle" ), TC.get( "Operation.NewFileMessage" ) );
// If the data must be saved, create the new file only if the save was successful
if( option == JOptionPane.YES_OPTION )
createNewFile = saveFile( false );
// If the data must not be saved, create the new data directly
else if( option == JOptionPane.NO_OPTION ) {
createNewFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
createNewFile = false;
}
}
if( createNewFile ) {
stopAutoSave( );
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.init( );
// Show dialog
//StartDialog start = new StartDialog( StartDialog.NEW_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs( StartDialog.NEW_TAB );
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( mainWindow );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
if( selectedFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else {
this.importGame( selectedFile.getAbsolutePath( ) );
}
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
if( currentZipFile == null ) {
mainWindow.reloadData( );
}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
//DEBUGGING
//tsd = new ToolSystemDebugger( chaptersController );
}
Controller.gc();
return createNewFile;
}
private boolean newAdventureFile( int fileType ) {
boolean fileCreated = false;
// Decide the directory of the temp file and give a name for it
// If there is a valid temp directory in the system, use it
//String tempDir = System.getenv( "TEMP" );
//String completeFilePath = "";
//isTempFile = true;
//if( tempDir != null ) {
// completeFilePath = tempDir + "/" + TEMP_NAME;
//}
// If the temp directory is not valid, use the home directory
//else {
// completeFilePath = FileSystemView.getFileSystemView( ).getHomeDirectory( ) + "/" + TEMP_NAME;
//}
boolean create = false;
java.io.File selectedDir = null;
java.io.File selectedFile = null;
// Prompt main folder of the project
//ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
int op = start.showStartDialog( );
// If some folder is selected, check all characters are correct
// if( folderSelector.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFile.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new File( selectedFile.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the parent folder is not forbidden
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( !directory.deleteAll( ) ) {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
}
}
create = true;
}
else {
// Create new folder?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotCreatedTitle" ), TC.get( "Operation.NewProject.FolderNotCreatedMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
else {
create = false;
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove( );
// Create the new project?
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.CreateProject" ), getLoadingImage( ), mainWindow);
if( create ) {
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.CreateProject" ) );
loadingScreen.setVisible( true );
// Set the new file, path and create the new adventure
currentZipFile = selectedDir.getAbsolutePath( );
currentZipPath = selectedDir.getParent( );
currentZipName = selectedDir.getName( );
int playerMode = -1;
if( fileType == FILE_ADVENTURE_3RDPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_3RDPERSON;
else if( fileType == FILE_ADVENTURE_1STPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_1STPERSON;
adventureDataControl = new AdventureDataControl( TC.get( "DefaultValue.AdventureTitle" ), TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ), playerMode );
// Clear the list of data controllers and refill it
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Init project properties (empty)
ProjectConfigData.init( );
SCORMConfigData.init( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
// Set modified to false and update the window title
dataModified = false;
try {
Thread.sleep( 1 );
}
catch( InterruptedException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWNERROR" );
}
try {
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
}
catch( IOException e ) {
}
mainWindow.reloadData( );
// The file was saved
fileCreated = true;
}
else
fileCreated = false;
}
if( fileCreated ) {
ConfigData.fileLoaded( currentZipFile );
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
}
else {
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
loadingScreen.setVisible( false );
Controller.gc();
return fileCreated;
}
public void showLoadingScreen( String message ) {
loadingScreen.setMessage( message );
loadingScreen.setVisible( true );
}
public void hideLoadingScreen( ) {
loadingScreen.setVisible( false );
}
public boolean fixIncidences( List<Incidence> incidences ) {
boolean abort = false;
List<Chapter> chapters = this.adventureDataControl.getChapters( );
for( int i = 0; i < incidences.size( ); i++ ) {
Incidence current = incidences.get( i );
// Critical importance: abort operation, the game could not be loaded
if( current.getImportance( ) == Incidence.IMPORTANCE_CRITICAL ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
break;
}
// High importance: the game is partially unreadable, but it is possible to continue.
else if( current.getImportance( ) == Incidence.IMPORTANCE_HIGH ) {
// An error occurred relating to the load of a chapter which is unreadable.
// When this happens the chapter returned in the adventure data structure is corrupted.
// Options: 1) Delete chapter. 2) Select chapter from other file. 3) Abort
if( current.getAffectedArea( ) == Incidence.CHAPTER_INCIDENCE && current.getType( ) == Incidence.XML_INCIDENCE ) {
String dialogTitle = TC.get( "ErrorSolving.Chapter.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( );
String dialogMessage = TC.get( "ErrorSolving.Chapter.Message", new String[] { current.getMessage( ), current.getAffectedResource( ) } );
String[] options = { TC.get( "GeneralText.Delete" ), TC.get( "GeneralText.Replace" ), TC.get( "GeneralText.Abort" ), TC.get( "GeneralText.ReportError" ) };
int option = showOptionDialog( dialogTitle, dialogMessage, options );
// Delete chapter
if( option == 0 ) {
String chapterName = current.getAffectedResource( );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( chapterName ) ) {
chapters.remove( j );
//this.chapterDataControlList.remove( j );
// Update selected chapter if necessary
if( chapters.size( ) == 0 ) {
// When there are no more chapters, add a new, blank one
Chapter newChapter = new Chapter( TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ) );
chapters.add( newChapter );
//chapterDataControlList.add( new ChapterDataControl (newChapter) );
}
chaptersController = new ChapterListDataControl( chapters );
dataModified( );
break;
}
}
}
// Replace chapter
else if( option == 1 ) {
boolean replaced = false;
JFileChooser xmlChooser = new JFileChooser( );
xmlChooser.setDialogTitle( TC.get( "GeneralText.Select" ) );
xmlChooser.setFileFilter( new XMLFileFilter( ) );
xmlChooser.setMultiSelectionEnabled( false );
// A file is selected
if( xmlChooser.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
// Get absolute path
String absolutePath = xmlChooser.getSelectedFile( ).getAbsolutePath( );
// Try to load chapter with it
List<Incidence> newChapterIncidences = new ArrayList<Incidence>( );
Chapter chapter = Loader.loadChapterData( AssetsController.getInputStreamCreator( ), absolutePath, incidences, true );
// IF no incidences occurred
if( chapter != null && newChapterIncidences.size( ) == 0 ) {
// Try comparing names
int found = -1;
for( int j = 0; found == -1 && j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( current.getAffectedResource( ) ) ) {
found = j;
}
}
// Replace it if found
if( found >= 0 ) {
//this.chapterDataControlList.remove( found );
chapters.set( found, chapter );
chaptersController = new ChapterListDataControl( chapters );
//chapterDataControlList.add( found, new ChapterDataControl(chapter) );
// Copy original file to project
File destinyFile = new File( this.getProjectFolder( ), chapter.getChapterPath( ) );
if( destinyFile.exists( ) )
destinyFile.delete( );
File sourceFile = new File( absolutePath );
sourceFile.copyTo( destinyFile );
replaced = true;
dataModified( );
}
}
}
// The chapter was not replaced: inform
if( !replaced ) {
mainWindow.showWarningDialog( TC.get( "ErrorSolving.Chapter.NotReplaced.Title" ), TC.get( "ErrorSolving.Chapter.NotReplaced.Message" ) );
}
}
// Report Dialog
else if( option == 3 ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
}
// Other case: abort
else {
abort = true;
break;
}
}
}
// Medium importance: the game might be slightly affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_MEDIUM ) {
// If an asset is missing or damaged. Delete references
if( current.getType( ) == Incidence.ASSET_INCIDENCE ) {
this.deleteAssetReferences( current.getAffectedResource( ) );
// if (current.getAffectedArea( ) == AssetsController.CATEGORY_ICON||current.getAffectedArea( ) == AssetsController.CATEGORY_BACKGROUND){
// mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), current.getMessage( ) );
//}else
mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.Asset.Deleted.Message", current.getAffectedResource( ) ) );
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAssessmentName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAssessmentName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
// adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAdaptationName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAdaptationName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// Abort
else {
abort = true;
break;
}
}
// Low importance: the game will not be affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_LOW ) {
if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
//adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
}
}
return abort;
}
/**
* Called when the user wants to load data from a file.
*
* @return True if a file was loaded successfully, false otherwise
*/
public boolean loadFile( ) {
return loadFile( null, true );
}
public boolean replaceSelectedChapter( Chapter newChapter ) {
chaptersController.replaceSelectedChapter( newChapter );
//mainWindow.updateTree();
mainWindow.reloadData( );
return true;
}
public NPC getNPC(String npcId){
return this.getSelectedChapterDataControl().getNPCsList( ).getNPC( npcId );
}
private boolean loadFile( String completeFilePath, boolean loadingImage ) {
boolean fileLoaded = false;
boolean hasIncedence = false;
try {
boolean loadFile = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.LoadFileTitle" ), TC.get( "Operation.LoadFileMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
loadFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
loadFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
loadFile = false;
}
}
if( loadFile && completeFilePath == null ) {
this.stopAutoSave( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.loadFromXML( );
// Show dialog
// StartDialog start = new StartDialog( StartDialog.OPEN_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs(StartDialog.OPEN_TAB );
//start.askForProject();
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( null );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
String absPath = selectedFile.getAbsolutePath( ).toLowerCase( );
if( absPath.endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else
// importGame is the same method for .ead, .jar and .zip (LO) import
this.importGame( selectedFile.getAbsolutePath( ) );
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
// if( currentZipFile == null ) {
// mainWindow.reloadData( );
//}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
return true;
}
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.LoadProject" ), getLoadingImage( ), mainWindow);
// If some file was selected
if( completeFilePath != null ) {
if( loadingImage ) {
loadingScreen.setMessage( TC.get( "Operation.LoadProject" ) );
this.loadingScreen.setVisible( true );
loadingImage = true;
}
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Load the data from the file, and update the info
List<Incidence> incidences = new ArrayList<Incidence>( );
//ls.start( );
/*AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator(completeFilePath),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ASSESSMENT),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ADAPTATION),incidences );
*/
AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator( completeFilePath ), incidences, true );
//mainWindow.setNormalState( );
// If the adventure was loaded without problems, update the data
if( loadedAdventureData != null ) {
// Update the values of the controller
currentZipFile = newFile.getAbsolutePath( );
currentZipPath = newFile.getParent( );
currentZipName = newFile.getName( );
loadedAdventureData.setProjectName( currentZipName );
adventureDataControl = new AdventureDataControl( loadedAdventureData );
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Check asset files
AssetsController.checkAssetFilesConsistency( incidences );
Incidence.sortIncidences( incidences );
// If there is any incidence
if( incidences.size( ) > 0 ) {
boolean abort = fixIncidences( incidences );
if( abort ) {
mainWindow.showInformationDialog( TC.get( "Error.LoadAborted.Title" ), TC.get( "Error.LoadAborted.Message" ) );
hasIncedence = true;
}
}
ProjectConfigData.loadFromXML( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
dataModified = false;
// The file was loaded
fileLoaded = true;
// Reloads the view of the window
mainWindow.reloadData( );
}
}
//if the file was loaded, update the RecentFiles list:
if( fileLoaded ) {
ConfigData.fileLoaded( currentZipFile );
AssetsController.resetCache( );
// Load project config file
ProjectConfigData.loadFromXML( );
startAutoSave( 15 );
// Feedback
//loadingScreen.close( );
if( !hasIncedence )
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
else
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedWithErrorTitle" ), TC.get( "Operation.FileLoadedWithErrorMessage" ) );
}
else {
// Feedback
//loadingScreen.close( );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
if( loadingImage )
//ls.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
e.printStackTrace( );
fileLoaded = false;
if( loadingImage )
loadingScreen.setVisible( false );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
Controller.gc();
return fileLoaded;
}
public boolean importJAR(){
return false;
}
public boolean importLO(){
return false;
}
/**
* Called when the user wants to save data to a file.
*
* @param saveAs
* True if the destiny file must be chosen inconditionally
* @return True if a file was saved successfully, false otherwise
*/
public boolean saveFile( boolean saveAs ) {
boolean fileSaved = false;
try {
boolean saveFile = true;
// Select a new file if it is a "Save as" action
if( saveAs ) {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProjectAs" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentLoadFolder( ), new FolderFileFilter( false, false, null ) );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Create a file to extract the name and path
File newFolder;
File newFile;
if( completeFilePath.endsWith( ".eap" ) ) {
newFile = new File( completeFilePath );
newFolder = new File( completeFilePath.substring( 0, completeFilePath.length( ) - 4 ) );
}
else {
newFile = new File( completeFilePath + ".eap" );
newFolder = new File( completeFilePath );
}
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( newFile ) ) {
if( FolderFileFilter.checkCharacters( newFolder.getName( ) ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file and the file it is not the current path of the project
if( ( this.currentZipFile == null || !newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) && ( ( !newFile.exists( ) && !newFolder.exists( ) ) || !newFolder.exists( ) || newFolder.list( ).length == 0 || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage", newFolder.getName( ) ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
//if( newFile.exists( ) )
// newFile.delete( );
if( !newFile.exists( ) )
newFile.create( );
// If this is a "Save as" operation, copy the assets from the old file to the new one
if( saveAs ) {
loadingScreen.setMessage( TC.get( "Operation.SaveProjectAs" ) );
loadingScreen.setVisible( true );
AssetsController.copyAssets( currentZipFile, newFolder.getAbsolutePath( ) );
}
// Set the new file and path
currentZipFile = newFolder.getAbsolutePath( );
currentZipPath = newFolder.getParent( );
currentZipName = newFolder.getName( );
AssetsController.createFolderStructure();
}
// If the file was not overwritten, don't save the data
else
saveFile = false;
// In case the selected folder is the same that the previous one, report an error
if( !saveFile && this.currentZipFile != null && newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) {
this.showErrorDialog( TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Title" ), TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
saveFile = false;
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
saveFile = false;
}
}
// If no file was selected, don't save the data
else
saveFile = false;
}
else {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProject" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.SaveProject" ) );
loadingScreen.setVisible( true );
}
// If the data must be saved
if( saveFile ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
// If the zip was temp file, delete it
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// If the data is not valid, show an error message
if( !valid )
mainWindow.showWarningDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventurInconsistentWarning" ) );
// Control the version number
String newValue = increaseVersionNumber( adventureDataControl.getAdventureData( ).getVersionNumber( ) );
adventureDataControl.getAdventureData( ).setVersionNumber( newValue );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
File eapFile = new File( currentZipFile + ".eap" );
if( !eapFile.exists( ) )
eapFile.create( );
// Set modified to false and update the window title
dataModified = false;
mainWindow.updateTitle( );
// The file was saved
fileSaved = true;
}
}
//If the file was saved, update the recent files list:
if( fileSaved ) {
ConfigData.fileLoaded( currentZipFile );
ProjectConfigData.storeToXML( );
AssetsController.resetCache( );
// also, look for adaptation and assessment folder, and delete them
File currentAssessFolder = new File( currentZipFile + File.separator + "assessment" );
if( currentAssessFolder.exists( ) ) {
File[] files = currentAssessFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAssessFolder.delete( );
}
File currentAdaptFolder = new File( currentZipFile + File.separator + "adaptation" );
if( currentAdaptFolder.exists( ) ) {
File[] files = currentAdaptFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAdaptFolder.delete( );
}
}
}
catch( Exception e ) {
fileSaved = false;
mainWindow.showInformationDialog( TC.get( "Operation.FileNotSavedTitle" ), TC.get( "Operation.FileNotSavedMessage" ) );
}
Controller.gc();
loadingScreen.setVisible( false );
return fileSaved;
}
/**
* Increase the game version number
*
* @param digits
* @param index
* @return the version number after increase it
*/
private String increaseVersionNumber( char[] digits, int index ) {
if( digits[index] != '9' ) {
// increase in "1" the ASCII code
digits[index]++;
return new String( digits );
}
else if( index == 0 ) {
char[] aux = new char[ digits.length + 1 ];
aux[0] = '1';
aux[1] = '0';
for( int i = 2; i < aux.length; i++ )
aux[i] = digits[i - 1];
return new String( aux );
}
else {
digits[index] = '0';
return increaseVersionNumber( digits, --index );
}
}
private String increaseVersionNumber( String versionNumber ) {
char[] digits = versionNumber.toCharArray( );
return increaseVersionNumber( digits, digits.length - 1 );
}
public void importChapter( ) {
}
public void importGame( ) {
importGame( null );
}
public void importGame( String eadPath ) {
boolean importGame = true;
java.io.File selectedFile = null;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
importGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
importGame = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
importGame = false;
}
}
if( importGame ) {
if (eadPath.endsWith( ".zip" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportLO.InfoMessage" ) );
else if (eadPath.endsWith( ".jar" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportJAR.InfoMessage" ));
// Ask origin file
JFileChooser chooser = new JFileChooser( );
chooser.setFileFilter( new EADFileFilter( ) );
chooser.setMultiSelectionEnabled( false );
chooser.setCurrentDirectory( new File( getCurrentExportSaveFolder( ) ) );
int option = JFileChooser.APPROVE_OPTION;
if( eadPath == null )
option = chooser.showOpenDialog( mainWindow );
if( option == JFileChooser.APPROVE_OPTION ) {
java.io.File originFile = null;
if( eadPath == null )
originFile = chooser.getSelectedFile( );
else
originFile = new File( eadPath );
// if( !originFile.getAbsolutePath( ).endsWith( ".ead" ) )
// originFile = new java.io.File( originFile.getAbsolutePath( ) + ".ead" );
// If the file not exists display error
if( !originFile.exists( ) )
mainWindow.showErrorDialog( TC.get( "Error.Import.FileNotFound.Title" ), TC.get( "Error.Import.FileNotFound.Title", originFile.getName( ) ) );
// Otherwise ask folder for the new project
else {
boolean create = false;
java.io.File selectedDir = null;
// Prompt main folder of the project
// ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
// If some folder is selected, check all characters are correct
int op = start.showStartDialog( );
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFolder.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new java.io.File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new java.io.File( selectedFolder.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.deleteAll( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
} // FIXME: else branch to return to previous dialog when the user tries to assign an existing name to his project
// and select "no" in re-writing confirmation panel
}
else {
create = true;
}
}
else {
// Create new folder?
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove();
// Create the new project?
if( create ) {
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ImportProject" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ImportProject" ) );
loadingScreen.setVisible( true );
//AssetsController.createFolderStructure();
if( !selectedDir.exists( ) )
selectedDir.mkdirs( );
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
boolean correctFile = true;
// Unzip directory
if (eadPath.endsWith( ".ead" ))
File.unzipDir( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) );
else if (eadPath.endsWith( ".zip" )){
// import EadJAR returns false when selected jar is not a eadventure jar
if (!File.importEadventureLO( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get( "Operation.ImportLO.FileNotLoadedMessage") );
correctFile = false;
}
}else if (eadPath.endsWith( ".jar" )){
// import EadLO returns false when selected zip is not a eadventure LO
if (!File.importEadventureJar( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.ImportJAR.FileNotLoaded") );
correctFile = false;
}
}
//ProjectConfigData.loadFromXML( );
// Load new project
if (correctFile) {
loadFile( selectedDir.getAbsolutePath( ), false );
//loadingScreen.close( );
loadingScreen.setVisible( false );
} else {
//remove .eapFile
selectedFile.delete( );
selectedDir.delete( );
}
}
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.FileNotLoadedMessage" ));
}
}
public boolean exportGame( ) {
return exportGame( null );
}
public boolean exportGame( String targetFilePath ) {
boolean exportGame = true;
boolean exported = false;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String selectedPath = targetFilePath;
if( selectedPath == null )
selectedPath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new EADFileFilter( ) );
if( selectedPath != null ) {
if( !selectedPath.toLowerCase( ).endsWith( ".ead" ) )
selectedPath = selectedPath + ".ead";
java.io.File destinyFile = new File( selectedPath );
// Check the destinyFile is not in the project folder
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
// If the file exists, ask to overwrite
if( !destinyFile.exists( ) || targetFilePath != null || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsEAD" ), getLoadingImage( ), mainWindow);
if( targetFilePath == null ) {
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsEAD" ) );
loadingScreen.setVisible( true );
}
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
exported = true;
if( targetFilePath == null )
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
if( targetFilePath == null )
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
exported = false;
}
return exported;
}
public boolean createBackup( String targetFilePath ) {
boolean fileSaved = false;
if( targetFilePath == null )
targetFilePath = currentZipFile + ".tmp";
File category = new File( currentZipFile, "backup" );
try {
boolean valid = chaptersController.isValid( null, null );
category.create( );
if( Writer.writeData( currentZipFile + File.separatorChar + "backup", adventureDataControl, valid ) ) {
fileSaved = true;
}
if( fileSaved ) {
String selectedPath = targetFilePath;
if( selectedPath != null ) {
java.io.File destinyFile = new File( selectedPath );
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || targetFilePath != null ) {
destinyFile.delete( );
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) )
fileSaved = true;
}
}
else
fileSaved = false;
}
}
}
catch( Exception e ) {
fileSaved = false;
}
if( category.exists( ) ) {
category.deleteAll( );
}
return fileSaved;
}
public void exportStandaloneGame( ) {
boolean exportGame = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new JARFileFilter());
if( completeFilePath != null ) {
if( !completeFilePath.toLowerCase( ).endsWith( ".jar" ) )
completeFilePath = completeFilePath + ".jar";
// If the file exists, ask to overwrite
java.io.File destinyFile = new File( completeFilePath );
// Check the destinyFile is not in the project folder
if( isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsJAR" ) );
loadingScreen.setVisible( true );
if( Writer.exportStandalone( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotSavedTitle"), TC.get("Operation.FileNotSavedMessage") );
}
}
public void exportToLOM( ) {
boolean exportFile = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportFile = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportFile = false;
}
if( exportFile ) {
// Ask the data of the Learning Object:
ExportToLOMDialog dialog = new ExportToLOMDialog( TC.get( "Operation.ExportToLOM.DefaultValue" ) );
String loName = dialog.getLomName( );
String authorName = dialog.getAuthorName( );
String organization = dialog.getOrganizationName( );
boolean windowed = dialog.getWindowed( );
int type = dialog.getType( );
boolean validated = dialog.isValidated( );
if( type == 2 && !hasScormProfiles( SCORM12 ) ) {
// error situation: both profiles must be scorm 1.2 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM12.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM12.BadProfiles.Message" ) );
}
else if( type == 3 && !hasScormProfiles( SCORM2004 ) ) {
// error situation: both profiles must be scorm 2004 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004.BadProfiles.Message" ) );
}
else if( type == 4 && !hasScormProfiles( AGREGA ) ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
}
//TODO comprobaciones de perfiles
// else if( type == 5 ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
// mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
if( validated ) {
//String loName = this.showInputDialog( TextConstants.getText( "Operation.ExportToLOM.Title" ), TextConstants.getText( "Operation.ExportToLOM.Message" ), TextConstants.getText( "Operation.ExportToLOM.DefaultValue" ));
if( loName != null && !loName.equals( "" ) && !loName.contains( " " ) ) {
//Check authorName & organization
if( authorName != null && authorName.length( ) > 5 && organization != null && organization.length( ) > 5 ) {
//Ask for the name of the zip
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new FileFilter( ) {
@Override
public boolean accept( java.io.File arg0 ) {
return arg0.getAbsolutePath( ).toLowerCase( ).endsWith( ".zip" ) || arg0.isDirectory( );
}
@Override
public String getDescription( ) {
return "Zip files (*.zip)";
}
} );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Add the ".zip" if it is not present in the name
if( !completeFilePath.toLowerCase( ).endsWith( ".zip" ) )
completeFilePath += ".zip";
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Check the selected file is contained in a valid folder
if( isValidTargetFile( newFile ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file
if( !newFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", newFile.getName( ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
try {
if( newFile.exists( ) )
newFile.delete( );
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsJAR" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsLO" ) );
loadingScreen.setVisible( true );
this.updateLOMLanguage( );
if( type == 0 && Writer.exportAsLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 1 && Writer.exportAsWebCTObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 2 && Writer.exportAsSCORM( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 3 && Writer.exportAsSCORM2004( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 4 && Writer.exportAsAGREGA( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 5 && Writer.exportAsLAMSLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ){
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
ReportDialog.GenerateErrorReport( e, true, TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
}
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Title" ), TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
}
}
/**
* Check if assessment and adaptation profiles are both scorm 1.2 or scorm
* 2004
*
* @param scormType
* the scorm type, 1.2 or 2004
* @return
*/
private boolean hasScormProfiles( int scormType ) {
if( scormType == SCORM12 ) {
// check that adaptation and assessment profiles are scorm 1.2 profiles
return chaptersController.hasScorm12Profiles( adventureDataControl );
}
else if( scormType == SCORM2004 || scormType == AGREGA ) {
// check that adaptation and assessment profiles are scorm 2004 profiles
return chaptersController.hasScorm2004Profiles( adventureDataControl );
}
return false;
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void run( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
// First update flags
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.normalRun( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void debugRun( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.debug( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Check if the current project is saved before run. If not, ask user to
* save it.
*
* @return if false is returned, the game will not be launched
*/
private boolean canBeRun( ) {
if( dataModified ) {
if( mainWindow.showStrictConfirmDialog( TC.get( "Run.CanBeRun.Title" ), TC.get( "Run.CanBeRun.Text" ) ) ) {
this.saveFile( false );
return true;
}
else
return false;
}
else
return true;
}
/**
* Determines if the target file of an exportation process is valid. The
* file cannot be located neither inside the project folder, nor inside the
* web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetFile( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ), getProjectFolderFile( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Determines if the target folder for a new project is valid. The folder
* cannot be located inside the web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetProject( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Exits from the aplication.
*/
public void exit( ) {
boolean exit = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.ExitTitle" ), TC.get( "Operation.ExitMessage" ) );
// If the data must be saved, lexit only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exit = saveFile( false );
// If the data must not be saved, exit directly
else if( option == JOptionPane.NO_OPTION )
exit = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exit = false;
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
}
// Exit the aplication
if( exit ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
//AssetsController.cleanVideoCache( );
System.exit( 0 );
}
}
/**
* Checks if the adventure is valid or not. It shows information to the
* user, whether the data is valid or not.
*/
public boolean checkAdventureConsistency( ) {
return checkAdventureConsistency( true );
}
public boolean checkAdventureConsistency( boolean showSuccessFeedback ) {
// Create a list to store the incidences
List<String> incidences = new ArrayList<String>( );
// Check all the chapters
boolean valid = chaptersController.isValid( null, incidences );
// If the data is valid, show a dialog with the information
if( valid ) {
if( showSuccessFeedback )
mainWindow.showInformationDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventureConsistentReport" ) );
// If it is not valid, show a dialog with the problems
}
else
new InvalidReportDialog( incidences, TC.get( "Operation.AdventureInconsistentReport" ) );
return valid;
}
public void checkFileConsistency( ) {
}
/**
* Shows the adventure data dialog editor.
*/
public void showAdventureDataDialog( ) {
new AdventureDataDialog( );
}
/**
* Shows the LOM data dialog editor.
*/
public void showLOMDataDialog( ) {
isLomEs = false;
new LOMDialog( adventureDataControl.getLomController( ) );
}
/**
* Shows the LOM for SCORM packages data dialog editor.
*/
public void showLOMSCORMDataDialog( ) {
isLomEs = false;
new IMSDialog( adventureDataControl.getImsController( ) );
}
/**
* Shows the LOMES for AGREGA packages data dialog editor.
*/
public void showLOMESDataDialog( ) {
isLomEs = true;
new LOMESDialog( adventureDataControl.getLOMESController( ) );
}
/**
* Shows the GUI style selection dialog.
*/
public void showGUIStylesDialog( ) {
adventureDataControl.showGUIStylesDialog( );
}
public void changeToolGUIStyleDialog( int optionSelected ){
if (optionSelected != 1){
adventureDataControl.setGUIStyleDialog( optionSelected );
}
}
/**
* Asks for confirmation and then deletes all unreferenced assets. Checks
* for animations indirectly referenced assets.
*/
public void deleteUnsuedAssets( ) {
if( !this.showStrictConfirmDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.Warning" ) ) )
return;
int deletedAssetCount = 0;
ArrayList<String> assets = new ArrayList<String>( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BACKGROUND ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_VIDEO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_CURSOR ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BUTTON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ICON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_STYLED_TEXT ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ARROW_BOOK ) )
if( !assets.contains( temp ) )
assets.add( temp );
/* assets.remove( "gui/cursors/arrow_left.png" );
assets.remove( "gui/cursors/arrow_right.png" ); */
for( String temp : assets ) {
int references = 0;
references = countAssetReferences( temp );
if( references == 0 ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp ).delete( );
deletedAssetCount++;
}
}
assets.clear( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION ) )
if( !assets.contains( temp ) )
assets.add( temp );
int i = 0;
while( i < assets.size( ) ) {
String temp = assets.get( i );
if( countAssetReferences( AssetsController.removeSuffix( temp ) ) != 0 ) {
assets.remove( temp );
if( temp.endsWith( "eaa" ) ) {
Animation a = Loader.loadAnimation( AssetsController.getInputStreamCreator( ), temp, new EditorImageLoader( ) );
for( Frame f : a.getFrames( ) ) {
if( f.getUri( ) != null && assets.contains( f.getUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
if( f.getSoundUri( ) != null && assets.contains( f.getSoundUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getSoundUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
}
}
else {
int j = 0;
while( j < assets.size( ) ) {
if( assets.get( j ).startsWith( AssetsController.removeSuffix( temp ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
else
j++;
}
}
}
else {
i++;
}
}
for( String temp2 : assets ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp2 ).delete( );
deletedAssetCount++;
}
if( deletedAssetCount != 0 )
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.AssetsDeleted", new String[] { String.valueOf( deletedAssetCount ) } ) );
else
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.NoUnsuedAssetsFound" ) );
}
/**
* Shows the flags dialog.
*/
public void showEditFlagDialog( ) {
new VarsFlagsDialog( new VarFlagsController( getVarFlagSummary( ) ) );
}
/**
* Sets a new selected chapter with the given index.
*
* @param selectedChapter
* Index of the new selected chapter
*/
public void setSelectedChapter( int selectedChapter ) {
chaptersController.setSelectedChapterInternal( selectedChapter );
mainWindow.reloadData( );
}
public void updateVarFlagSummary( ) {
chaptersController.updateVarFlagSummary( );
}
/**
* Adds a new chapter to the adventure. This method asks for the title of
* the chapter to the user, and updates the view of the application if a new
* chapter was added.
*/
public void addChapter( ) {
addTool( new AddChapterTool( chaptersController ) );
}
/**
* Deletes the selected chapter from the adventure. This method asks the
* user for confirmation, and updates the view if needed.
*/
public void deleteChapter( ) {
addTool( new DeleteChapterTool( chaptersController ) );
}
/**
* Moves the selected chapter to the previous position of the chapter's
* list.
*/
public void moveChapterUp( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_UP, chaptersController ) );
}
/**
* Moves the selected chapter to the next position of the chapter's list.
*
*/
public void moveChapterDown( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_DOWN, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods to edit and get the adventure general data (title and description)
/**
* Returns the title of the adventure.
*
* @return Adventure's title
*/
public String getAdventureTitle( ) {
return adventureDataControl.getTitle( );
}
/**
* Returns the description of the adventure.
*
* @return Adventure's description
*/
public String getAdventureDescription( ) {
return adventureDataControl.getDescription( );
}
/**
* Returns the LOM controller.
*
* @return Adventure LOM controller.
*
*/
public LOMDataControl getLOMDataControl( ) {
return adventureDataControl.getLomController( );
}
/**
* Sets the new title of the adventure.
*
* @param title
* Title of the adventure
*/
public void setAdventureTitle( String title ) {
// If the value is different
if( !title.equals( adventureDataControl.getTitle( ) ) ) {
// Set the new title and modify the data
adventureDataControl.setTitle( title );
}
}
/**
* Sets the new description of the adventure.
*
* @param description
* Description of the adventure
*/
public void setAdventureDescription( String description ) {
// If the value is different
if( !description.equals( adventureDataControl.getDescription( ) ) ) {
// Set the new description and modify the data
adventureDataControl.setDescription( description );
}
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods that perform specific tasks for the microcontrollers
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId ) {
return isElementIdValid( elementId, true );
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user
* if showError is true
*
* @param elementId
* Element identifier to be checked
* @param showError
* True if the error message must be shown
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId, boolean showError ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) && !elementId.contains( "'" )) {
// If the identifier doesn't exist already
if( !getIdentifierSummary( ).existsId( elementId ) ) {
// If the identifier is not a reserved identifier
if( !elementId.equals( Player.IDENTIFIER ) && !elementId.equals( TC.get( "ConversationLine.PlayerName" ) ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) ){
elementIdValid = isCharacterValid(elementId);
if (!elementIdValid)
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorCharacter" ) );
}
// Show non-letter first character error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show invalid identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorReservedIdentifier", elementId ) );
}
// Show repeated identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorAlreadyUsed" ) );
}
// Show blank spaces error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
public boolean isCharacterValid(String elementId){
Character chId;
boolean isValid = true;
int i=1;
while (i < elementId.length( ) && isValid) {
chId = elementId.charAt( i );
if (chId =='&' || chId == '%' || chId == '?' || chId == '�' ||
chId =='�' || chId == '!' || chId== '=' || chId == '$' ||
chId == '*' || chId == '/' || chId == '(' || chId == ')' )
isValid = false;
i++;
}
return isValid;
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isPropertyIdValid( String elementId ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) )
elementIdValid = true;
// Show non-letter first character error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show blank spaces error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
/**
* This method returns the absolute path of the background image of the
* given scene.
*
* @param sceneId
* Scene id
* @return Path to the background image, null if it was not found
*/
public String getSceneImagePath( String sceneId ) {
String sceneImagePath = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) )
sceneImagePath = scene.getPreviewBackground( );
return sceneImagePath;
}
/**
* This method returns the trajectory of a scene from its id.
*
* @param sceneId
* Scene id
* @return Trajectory of the scene, null if it was not found
*/
public Trajectory getSceneTrajectory( String sceneId ) {
Trajectory trajectory = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) && scene.getTrajectory( ).hasTrajectory( ) )
trajectory = (Trajectory) scene.getTrajectory( ).getContent( );
return trajectory;
}
/**
* This method returns the absolute path of the default image of the player.
*
* @return Default image of the player
*/
public String getPlayerImagePath( ) {
if( getSelectedChapterDataControl( ) != null )
return getSelectedChapterDataControl( ).getPlayer( ).getPreviewImage( );
else
return null;
}
/**
* Returns the player
*/
public Player getPlayer(){
return (Player)getSelectedChapterDataControl( ).getPlayer( ).getContent( );
}
/**
* This method returns the absolute path of the default image of the given
* element (item or character).
*
* @param elementId
* Id of the element
* @return Default image of the requested element
*/
public String getElementImagePath( String elementId ) {
String elementImage = null;
// Search for the image in the items, comparing the identifiers
for( ItemDataControl item : getSelectedChapterDataControl( ).getItemsList( ).getItems( ) )
if( elementId.equals( item.getId( ) ) )
elementImage = item.getPreviewImage( );
// Search for the image in the characters, comparing the identifiers
for( NPCDataControl npc : getSelectedChapterDataControl( ).getNPCsList( ).getNPCs( ) )
if( elementId.equals( npc.getId( ) ) )
elementImage = npc.getPreviewImage( );
// Search for the image in the items, comparing the identifiers
for( AtrezzoDataControl atrezzo : getSelectedChapterDataControl( ).getAtrezzoList( ).getAtrezzoList( ) )
if( elementId.equals( atrezzo.getId( ) ) )
elementImage = atrezzo.getPreviewImage( );
return elementImage;
}
/**
* Counts all the references to a given asset in the entire script.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
* @return Number of references to the given asset
*/
public int countAssetReferences( String assetPath ) {
return adventureDataControl.countAssetReferences( assetPath ) + chaptersController.countAssetReferences( assetPath );
}
/**
* Gets a list with all the assets referenced in the chapter along with the
* types of those assets
*
* @param assetPaths
* @param assetTypes
*/
public void getAssetReferences( List<String> assetPaths, List<Integer> assetTypes ) {
adventureDataControl.getAssetReferences( assetPaths, assetTypes );
chaptersController.getAssetReferences( assetPaths, assetTypes );
}
/**
* Deletes a given asset from the script, removing all occurrences.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
*/
public void deleteAssetReferences( String assetPath ) {
adventureDataControl.deleteAssetReferences( assetPath );
chaptersController.deleteAssetReferences( assetPath );
}
/**
* Counts all the references to a given identifier in the entire script.
*
* @param id
* Identifier to which the references must be found
* @return Number of references to the given identifier
*/
public int countIdentifierReferences( String id ) {
return getSelectedChapterDataControl( ).countIdentifierReferences( id );
}
/**
* Deletes a given identifier from the script, removing all occurrences.
*
* @param id
* Identifier to be deleted
*/
public void deleteIdentifierReferences( String id ) {
chaptersController.deleteIdentifierReferences( id );
}
/**
* Replaces a given identifier with another one, in all the occurrences in
* the script.
*
* @param oldId
* Old identifier to be replaced
* @param newId
* New identifier to replace the old one
*/
public void replaceIdentifierReferences( String oldId, String newId ) {
getSelectedChapterDataControl( ).replaceIdentifierReferences( oldId, newId );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods linked with the GUI
/**
* Updates the chapter menu with the new names of the chapters.
*/
public void updateChapterMenu( ) {
mainWindow.updateChapterMenu( );
}
/**
* Updates the tree of the main window.
*/
public void updateStructure( ) {
mainWindow.updateStructure( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadPanel( ) {
mainWindow.reloadPanel( );
}
public void updatePanel( ) {
mainWindow.updatePanel( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadData( ) {
mainWindow.reloadData( );
}
/**
* Returns the last window opened by the application.
*
* @return Last window opened
*/
public Window peekWindow( ) {
return mainWindow.peekWindow( );
}
/**
* Pushes a new window in the windows stack.
*
* @param window
* Window to push
*/
public void pushWindow( Window window ) {
mainWindow.pushWindow( window );
}
/**
* Pops the last window pushed into the stack.
*/
public void popWindow( ) {
mainWindow.popWindow( );
}
/**
* Shows a load dialog to select multiple files.
*
* @param filter
* File filter for the dialog
* @return Full path of the selected files, null if no files were selected
*/
public String[] showMultipleSelectionLoadDialog( FileFilter filter ) {
return mainWindow.showMultipleSelectionLoadDialog( currentZipPath, filter );
}
/**
* Shows a dialog with the options "Yes" and "No", with the given title and
* text.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @return True if the "Yes" button was pressed, false otherwise
*/
public boolean showStrictConfirmDialog( String title, String message ) {
return mainWindow.showStrictConfirmDialog( title, message );
}
/**
* Shows a dialog with the given set of options.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param options
* Array of strings containing the options of the dialog
* @return The index of the option selected, JOptionPane.CLOSED_OPTION if
* the dialog was closed.
*/
public int showOptionDialog( String title, String message, String[] options ) {
return mainWindow.showOptionDialog( title, message, options );
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param defaultValue
* Default value of the dialog
* @return String typed in the dialog, null if the cancel button was pressed
*/
public String showInputDialog( String title, String message, String defaultValue ) {
return mainWindow.showInputDialog( title, message, defaultValue );
}
public String showInputDialog( String title, String message) {
return mainWindow.showInputDialog( title, message);
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param selectionValues
* Possible selection values of the dialog
* @return Option selected in the dialog, null if the cancel button was
* pressed
*/
public String showInputDialog( String title, String message, Object[] selectionValues ) {
return mainWindow.showInputDialog( title, message, selectionValues );
}
/**
* Uses the GUI to show an error dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
*/
public void showErrorDialog( String title, String message ) {
mainWindow.showErrorDialog( title, message );
}
public void showCustomizeGUIDialog( ) {
new CustomizeGUIDialog( this.adventureDataControl );
}
public boolean isFolderLoaded( ) {
return chaptersController.isAnyChapterSelected( );
}
public String getEditorMinVersion( ) {
return "1.0b";
}
public String getEditorVersion( ) {
return "1.0b";
}
public void updateLOMLanguage( ) {
this.adventureDataControl.getLomController( ).updateLanguage( );
}
public void updateIMSLanguage( ) {
this.adventureDataControl.getImsController( ).updateLanguage( );
}
public void showAboutDialog( ) {
try {
JDialog dialog = new JDialog( Controller.getInstance( ).peekWindow( ), TC.get( "About" ), Dialog.ModalityType.TOOLKIT_MODAL );
dialog.getContentPane( ).setLayout( new BorderLayout( ) );
JPanel panel = new JPanel();
panel.setLayout( new BorderLayout() );
File file = new File( ConfigData.getAboutFile( ) );
if( file.exists( ) ) {
JEditorPane pane = new JEditorPane( );
pane.setPage( file.toURI( ).toURL( ) );
pane.setEditable( false );
panel.add( pane, BorderLayout.CENTER );
}
JPanel version = new JPanel();
version.setLayout( new BorderLayout() );
JButton checkVersion = new JButton(TC.get( "About.CheckNewVersion" ));
version.add(checkVersion, BorderLayout. CENTER);
final JLabel label = new JLabel("");
version.add(label, BorderLayout.SOUTH);
checkVersion.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
java.io.BufferedInputStream in = null;
try {
in = new java.io.BufferedInputStream(new java.net.URL("http://e-adventure.e-ucm.es/files/version").openStream());
byte data[] = new byte[1024];
int bytes = 0;
String a = null;
while((bytes = in.read(data,0,1024)) >= 0)
{
a = new String(data, 0, bytes);
}
a = a.substring( 0, a.length( ) - 1 );
System.out.println(getCurrentVersion().split( "-" )[0] + " " + a);
if (getCurrentVersion().split( "-" )[0].equals( a )) {
label.setText(TC.get( "About.LatestRelease" ));
} else {
label.setText( TC.get("About.NewReleaseAvailable"));
}
label.updateUI( );
in.close();
}
catch( IOException e1 ) {
label.setText( TC.get( "About.LatestRelease" ) );
label.updateUI( );
}
}
});
panel.add( version, BorderLayout.NORTH );
dialog.getContentPane( ).add( panel, BorderLayout.CENTER );
dialog.setSize( 275, 560 );
Dimension screenSize = Toolkit.getDefaultToolkit( ).getScreenSize( );
dialog.setLocation( ( screenSize.width - dialog.getWidth( ) ) / 2, ( screenSize.height - dialog.getHeight( ) ) / 2 );
dialog.setVisible( true );
}
catch( IOException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWERROR" );
}
}
private String getCurrentVersion() {
File moreinfo = new File( "RELEASE" );
String release = null;
if( moreinfo.exists( ) ) {
try {
FileInputStream fis = new FileInputStream( moreinfo );
BufferedInputStream bis = new BufferedInputStream( fis );
int nextChar = -1;
while( ( nextChar = bis.read( ) ) != -1 ) {
if( release == null )
release = "" + (char) nextChar;
else
release += (char) nextChar;
}
if( release != null ) {
return release;
}
}
catch( Exception ex ) {
}
}
return "NOVERSION";
}
public AssessmentProfilesDataControl getAssessmentController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAssessmentProfilesDataControl( );
}
public AdaptationProfilesDataControl getAdaptationController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdaptationProfilesDataControl( );
}
public boolean isCommentaries( ) {
return this.adventureDataControl.isCommentaries( );
}
public void setCommentaries( boolean b ) {
this.adventureDataControl.setCommentaries( b );
}
public boolean isKeepShowing( ) {
return this.adventureDataControl.isKeepShowing( );
}
public void setKeepShowing( boolean b ) {
this.adventureDataControl.setKeepShowing( b );
}
/**
* Returns an int value representing the current language used to display
* the editor
*
* @return
*/
public String getLanguage( ) {
return this.languageFile;
}
/**
* Get the default lenguage
* @return name of default language in standard internationalization
*/
public String getDefaultLanguage( ) {
return ReleaseFolders.LANGUAGE_DEFAULT;
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window always
*
* @param language
*/
public void setLanguage( String language ) {
setLanguage( language, true );
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window if reloadData is true
*
* @param language
*/
public void setLanguage( String language, boolean reloadData ) {
// image loading route
String dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + language + "/Editor2D-Loading.png";
// if there isn't file, load the default file
File fichero = new File(dirImageLoading);
if (!fichero.exists( ))
dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + getDefaultLanguage( ) + "/Editor2D-Loading.png";
//about file route
String dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getAboutFilePath( language );
File fichero2 = new File(dirAboutFile);
if (!fichero2.exists( ))
dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getDefaultAboutFilePath( );
ConfigData.setLanguangeFile( ReleaseFolders.getLanguageFilePath( language ), dirAboutFile, dirImageLoading );
languageFile = language;
TC.loadStrings( ReleaseFolders.getLanguageFilePath4Editor( true, languageFile ) );
TC.appendStrings( ReleaseFolders.getLanguageFilePath4Editor( false, languageFile ) );
loadingScreen.setImage( getLoadingImage( ) );
if( reloadData )
mainWindow.reloadData( );
}
public String getLoadingImage( ) {
return ConfigData.getLoadingImage( );
}
public void showGraphicConfigDialog( ) {
// Show the dialog
// GraphicConfigDialog guiStylesDialog = new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
// If the new GUI style is different from the current, and valid, change the value
/* int optionSelected = guiStylesDialog.getOptionSelected( );
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
adventureDataControl.setGraphicConfig( optionSelected );
}*/
}
public void changeToolGraphicConfig( int optionSelected ) {
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
// this.grafhicDialog.cambiarCheckBox( );
adventureDataControl.setGraphicConfig( optionSelected );
}
}
// METHODS TO MANAGE UNDO/REDO
public boolean addTool( Tool tool ) {
boolean added = chaptersController.addTool( tool );
//tsd.update();
return added;
}
public void undoTool( ) {
chaptersController.undoTool( );
//tsd.update();
}
public void redoTool( ) {
chaptersController.redoTool( );
//tsd.update();
}
public void pushLocalToolManager( ) {
chaptersController.pushLocalToolManager( );
}
public void popLocalToolManager( ) {
chaptersController.popLocalToolManager( );
}
public void search( ) {
new SearchDialog( );
}
public boolean getAutoSaveEnabled( ) {
if( ProjectConfigData.existsKey( "autosave" ) ) {
String temp = ProjectConfigData.getProperty( "autosave" );
if( temp.equals( "yes" ) ) {
return true;
}
else {
return false;
}
}
return true;
}
public void setAutoSaveEnabled( boolean selected ) {
if( selected != getAutoSaveEnabled( ) ) {
ProjectConfigData.setProperty( "autosave", ( selected ? "yes" : "no" ) );
startAutoSave( 15 );
}
}
/**
* @return the isLomEs
*/
public boolean isLomEs( ) {
return isLomEs;
}
public int getGUIConfigConfiguration(){
return this.adventureDataControl.getGraphicConfig( );
}
public String getDefaultExitCursorPath( ) {
String temp = this.adventureDataControl.getCursorPath( "exit" );
if( temp != null && temp.length( ) > 0 )
return temp;
else
return "gui/cursors/exit.png";
}
public AdvancedFeaturesDataControl getAdvancedFeaturesController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdvancedFeaturesController( );
}
public static Color generateColor( int i ) {
int r = ( i * 180 ) % 256;
int g = ( ( i + 4 ) * 130 ) % 256;
int b = ( ( i + 2 ) * 155 ) % 256;
if( r > 250 && g > 250 && b > 250 ) {
r = 0;
g = 0;
b = 0;
}
return new Color( r, g, b );
}
private static final Runnable gc = new Runnable() { public void run() { System.gc( );} };
/**
* Public method to perform garbage collection on a different thread.
*/
public static void gc() {
new Thread(gc).start( );
}
public static java.io.File createTempDirectory() throws IOException
{
final java.io.File temp;
temp = java.io.File.createTempFile("temp", Long.toString(System.nanoTime()));
if(!(temp.delete()))
throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
if(!(temp.mkdir()))
throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
return (temp);
}
public DefaultClickAction getDefaultCursorAction( ) {
return this.adventureDataControl.getDefaultClickAction( );
}
public void setDefaultCursorAction( DefaultClickAction defaultClickAction ) {
this.adventureDataControl.setDefaultClickAction(defaultClickAction);
}
public Perspective getPerspective() {
return this.adventureDataControl.getPerspective( );
}
public void setPerspective( Perspective perspective ) {
this.adventureDataControl.setPerspective( perspective );
}
}
| public void startAutoSave( int minutes ) {
stopAutoSave( );
if( ( ProjectConfigData.existsKey( "autosave" ) && ProjectConfigData.getProperty( "autosave" ).equals( "yes" ) ) || !ProjectConfigData.existsKey( "autosave" ) ) {
/* autoSaveTimer = new Timer();
autoSave = new AutoSave();
autoSaveTimer.schedule(autoSave, 10000, minutes * 60 * 1000);
*/}
if( !ProjectConfigData.existsKey( "autosave" ) )
ProjectConfigData.setProperty( "autosave", "yes" );
}
public void stopAutoSave( ) {
if( autoSaveTimer != null ) {
autoSaveTimer.cancel( );
autoSave.stop( );
autoSaveTimer = null;
}
autoSave = null;
}
//private ToolSystemDebugger tsd;
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// General data functions of the aplication
/**
* Returns the complete path to the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public String getProjectFolder( ) {
return currentZipFile;
}
/**
* Returns the File object representing the currently open Project.
*
* @return The complete path to the ZIP file, null if none is open
*/
public File getProjectFolderFile( ) {
return new File( currentZipFile );
}
/**
* Returns the name of the file currently open.
*
* @return The name of the current file
*/
public String getFileName( ) {
String filename;
// Show "New" if no current file is currently open
if( currentZipName != null )
filename = currentZipName;
else
filename = "http://e-adventure.e-ucm.es";
return filename;
}
/**
* Returns the parent path of the file being currently edited.
*
* @return Parent path of the current file
*/
public String getFilePath( ) {
return currentZipPath;
}
/**
* Returns an array with the chapter titles.
*
* @return Array with the chapter titles
*/
public String[] getChapterTitles( ) {
return chaptersController.getChapterTitles( );
}
/**
* Returns the index of the chapter currently selected.
*
* @return Index of the selected chapter
*/
public int getSelectedChapter( ) {
return chaptersController.getSelectedChapter( );
}
/**
* Returns the selected chapter data controller.
*
* @return The selected chapter data controller
*/
public ChapterDataControl getSelectedChapterDataControl( ) {
return chaptersController.getSelectedChapterDataControl( );
}
/**
* Returns the identifier summary.
*
* @return The identifier summary
*/
public IdentifierSummary getIdentifierSummary( ) {
return chaptersController.getIdentifierSummary( );
}
/**
* Returns the varFlag summary.
*
* @return The varFlag summary
*/
public VarFlagSummary getVarFlagSummary( ) {
return chaptersController.getVarFlagSummary( );
}
public ChapterListDataControl getCharapterList( ) {
return chaptersController;
}
/**
* Returns whether the data has been modified since the last save.
*
* @return True if the data has been modified, false otherwise
*/
public boolean isDataModified( ) {
return dataModified;
}
/**
* Called when the data has been modified, it sets the value to true.
*/
public void dataModified( ) {
// If the data were not modified, change the value and set the new title of the window
if( !dataModified ) {
dataModified = true;
mainWindow.updateTitle( );
}
}
public boolean isPlayTransparent( ) {
if( adventureDataControl == null ) {
return false;
}
return adventureDataControl.getPlayerMode( ) == DescriptorData.MODE_PLAYER_1STPERSON;
}
public void swapPlayerMode( boolean showConfirmation ) {
addTool( new SwapPlayerModeTool( showConfirmation, adventureDataControl, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Functions that perform usual application actions
/**
* This method creates a new file with it's respective data.
*
* @return True if the new data was created successfully, false otherwise
*/
public boolean newFile( int fileType ) {
boolean fileCreated = false;
if( fileType == Controller.FILE_ADVENTURE_1STPERSON_PLAYER || fileType == Controller.FILE_ADVENTURE_3RDPERSON_PLAYER )
fileCreated = newAdventureFile( fileType );
else if( fileType == Controller.FILE_ASSESSMENT ) {
//fileCreated = newAssessmentFile();
}
else if( fileType == Controller.FILE_ADAPTATION ) {
//fileCreated = newAdaptationFile();
}
if( fileCreated )
AssetsController.resetCache( );
return fileCreated;
}
public boolean newFile( ) {
boolean createNewFile = true;
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.NewFileTitle" ), TC.get( "Operation.NewFileMessage" ) );
// If the data must be saved, create the new file only if the save was successful
if( option == JOptionPane.YES_OPTION )
createNewFile = saveFile( false );
// If the data must not be saved, create the new data directly
else if( option == JOptionPane.NO_OPTION ) {
createNewFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
createNewFile = false;
}
}
if( createNewFile ) {
stopAutoSave( );
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.init( );
// Show dialog
//StartDialog start = new StartDialog( StartDialog.NEW_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs( StartDialog.NEW_TAB );
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( mainWindow );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
if( selectedFile.getAbsolutePath( ).toLowerCase( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else {
this.importGame( selectedFile.getAbsolutePath( ) );
}
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
if( currentZipFile == null ) {
mainWindow.reloadData( );
}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
//DEBUGGING
//tsd = new ToolSystemDebugger( chaptersController );
}
Controller.gc();
return createNewFile;
}
private boolean newAdventureFile( int fileType ) {
boolean fileCreated = false;
// Decide the directory of the temp file and give a name for it
// If there is a valid temp directory in the system, use it
//String tempDir = System.getenv( "TEMP" );
//String completeFilePath = "";
//isTempFile = true;
//if( tempDir != null ) {
// completeFilePath = tempDir + "/" + TEMP_NAME;
//}
// If the temp directory is not valid, use the home directory
//else {
// completeFilePath = FileSystemView.getFileSystemView( ).getHomeDirectory( ) + "/" + TEMP_NAME;
//}
boolean create = false;
java.io.File selectedDir = null;
java.io.File selectedFile = null;
// Prompt main folder of the project
//ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
int op = start.showStartDialog( );
// If some folder is selected, check all characters are correct
// if( folderSelector.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFile.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new File( selectedFile.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the parent folder is not forbidden
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( !directory.deleteAll( ) ) {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
}
}
create = true;
}
else {
// Create new folder?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotCreatedTitle" ), TC.get( "Operation.NewProject.FolderNotCreatedMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
else {
create = false;
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove( );
// Create the new project?
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.CreateProject" ), getLoadingImage( ), mainWindow);
if( create ) {
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.CreateProject" ) );
loadingScreen.setVisible( true );
// Set the new file, path and create the new adventure
currentZipFile = selectedDir.getAbsolutePath( );
currentZipPath = selectedDir.getParent( );
currentZipName = selectedDir.getName( );
int playerMode = -1;
if( fileType == FILE_ADVENTURE_3RDPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_3RDPERSON;
else if( fileType == FILE_ADVENTURE_1STPERSON_PLAYER )
playerMode = DescriptorData.MODE_PLAYER_1STPERSON;
adventureDataControl = new AdventureDataControl( TC.get( "DefaultValue.AdventureTitle" ), TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ), playerMode );
// Clear the list of data controllers and refill it
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Init project properties (empty)
ProjectConfigData.init( );
SCORMConfigData.init( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
// Set modified to false and update the window title
dataModified = false;
try {
Thread.sleep( 1 );
}
catch( InterruptedException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWNERROR" );
}
try {
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
}
catch( IOException e ) {
}
mainWindow.reloadData( );
// The file was saved
fileCreated = true;
}
else
fileCreated = false;
}
if( fileCreated ) {
ConfigData.fileLoaded( currentZipFile );
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
}
else {
// Feedback
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
loadingScreen.setVisible( false );
Controller.gc();
return fileCreated;
}
public void showLoadingScreen( String message ) {
loadingScreen.setMessage( message );
loadingScreen.setVisible( true );
}
public void hideLoadingScreen( ) {
loadingScreen.setVisible( false );
}
public boolean fixIncidences( List<Incidence> incidences ) {
boolean abort = false;
List<Chapter> chapters = this.adventureDataControl.getChapters( );
for( int i = 0; i < incidences.size( ); i++ ) {
Incidence current = incidences.get( i );
// Critical importance: abort operation, the game could not be loaded
if( current.getImportance( ) == Incidence.IMPORTANCE_CRITICAL ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
break;
}
// High importance: the game is partially unreadable, but it is possible to continue.
else if( current.getImportance( ) == Incidence.IMPORTANCE_HIGH ) {
// An error occurred relating to the load of a chapter which is unreadable.
// When this happens the chapter returned in the adventure data structure is corrupted.
// Options: 1) Delete chapter. 2) Select chapter from other file. 3) Abort
if( current.getAffectedArea( ) == Incidence.CHAPTER_INCIDENCE && current.getType( ) == Incidence.XML_INCIDENCE ) {
String dialogTitle = TC.get( "ErrorSolving.Chapter.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( );
String dialogMessage = TC.get( "ErrorSolving.Chapter.Message", new String[] { current.getMessage( ), current.getAffectedResource( ) } );
String[] options = { TC.get( "GeneralText.Delete" ), TC.get( "GeneralText.Replace" ), TC.get( "GeneralText.Abort" ), TC.get( "GeneralText.ReportError" ) };
int option = showOptionDialog( dialogTitle, dialogMessage, options );
// Delete chapter
if( option == 0 ) {
String chapterName = current.getAffectedResource( );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( chapterName ) ) {
chapters.remove( j );
//this.chapterDataControlList.remove( j );
// Update selected chapter if necessary
if( chapters.size( ) == 0 ) {
// When there are no more chapters, add a new, blank one
Chapter newChapter = new Chapter( TC.get( "DefaultValue.ChapterTitle" ), TC.get( "DefaultValue.SceneId" ) );
chapters.add( newChapter );
//chapterDataControlList.add( new ChapterDataControl (newChapter) );
}
chaptersController = new ChapterListDataControl( chapters );
dataModified( );
break;
}
}
}
// Replace chapter
else if( option == 1 ) {
boolean replaced = false;
JFileChooser xmlChooser = new JFileChooser( );
xmlChooser.setDialogTitle( TC.get( "GeneralText.Select" ) );
xmlChooser.setFileFilter( new XMLFileFilter( ) );
xmlChooser.setMultiSelectionEnabled( false );
// A file is selected
if( xmlChooser.showOpenDialog( mainWindow ) == JFileChooser.APPROVE_OPTION ) {
// Get absolute path
String absolutePath = xmlChooser.getSelectedFile( ).getAbsolutePath( );
// Try to load chapter with it
List<Incidence> newChapterIncidences = new ArrayList<Incidence>( );
Chapter chapter = Loader.loadChapterData( AssetsController.getInputStreamCreator( ), absolutePath, incidences, true );
// IF no incidences occurred
if( chapter != null && newChapterIncidences.size( ) == 0 ) {
// Try comparing names
int found = -1;
for( int j = 0; found == -1 && j < chapters.size( ); j++ ) {
if( chapters.get( j ).getChapterPath( ).equals( current.getAffectedResource( ) ) ) {
found = j;
}
}
// Replace it if found
if( found >= 0 ) {
//this.chapterDataControlList.remove( found );
chapters.set( found, chapter );
chaptersController = new ChapterListDataControl( chapters );
//chapterDataControlList.add( found, new ChapterDataControl(chapter) );
// Copy original file to project
File destinyFile = new File( this.getProjectFolder( ), chapter.getChapterPath( ) );
if( destinyFile.exists( ) )
destinyFile.delete( );
File sourceFile = new File( absolutePath );
sourceFile.copyTo( destinyFile );
replaced = true;
dataModified( );
}
}
}
// The chapter was not replaced: inform
if( !replaced ) {
mainWindow.showWarningDialog( TC.get( "ErrorSolving.Chapter.NotReplaced.Title" ), TC.get( "ErrorSolving.Chapter.NotReplaced.Message" ) );
}
}
// Report Dialog
else if( option == 3 ) {
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
abort = true;
}
// Other case: abort
else {
abort = true;
break;
}
}
}
// Medium importance: the game might be slightly affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_MEDIUM ) {
// If an asset is missing or damaged. Delete references
if( current.getType( ) == Incidence.ASSET_INCIDENCE ) {
this.deleteAssetReferences( current.getAffectedResource( ) );
// if (current.getAffectedArea( ) == AssetsController.CATEGORY_ICON||current.getAffectedArea( ) == AssetsController.CATEGORY_BACKGROUND){
// mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), current.getMessage( ) );
//}else
mainWindow.showInformationDialog( TC.get( "ErrorSolving.Asset.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.Asset.Deleted.Message", current.getAffectedResource( ) ) );
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AssessmentReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAssessmentName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAssessmentName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
// adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// If it was an assessment profile (referenced) delete the assessment configuration of the chapter
else if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
mainWindow.showInformationDialog( TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Title" ) + " - Error " + ( i + 1 ) + "/" + incidences.size( ), TC.get( "ErrorSolving.AdaptationReferenced.Deleted.Message", current.getAffectedResource( ) ) );
for( int j = 0; j < chapters.size( ); j++ ) {
if( chapters.get( j ).getAdaptationName( ).equals( current.getAffectedResource( ) ) ) {
chapters.get( j ).setAdaptationName( "" );
dataModified( );
}
}
if( current.getException( ) != null )
ReportDialog.GenerateErrorReport( current.getException( ), true, TC.get( "GeneralText.LoadError" ) );
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
}
// Abort
else {
abort = true;
break;
}
}
// Low importance: the game will not be affected
else if( current.getImportance( ) == Incidence.IMPORTANCE_LOW ) {
if( current.getAffectedArea( ) == Incidence.ADAPTATION_INCIDENCE ) {
//adventureData.getAdaptationRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
if( current.getAffectedArea( ) == Incidence.ASSESSMENT_INCIDENCE ) {
//adventureData.getAssessmentRulesListDataControl( ).deleteIdentifierReferences( current.getAffectedResource( ) );
dataModified( );
}
}
}
return abort;
}
/**
* Called when the user wants to load data from a file.
*
* @return True if a file was loaded successfully, false otherwise
*/
public boolean loadFile( ) {
return loadFile( null, true );
}
public boolean replaceSelectedChapter( Chapter newChapter ) {
chaptersController.replaceSelectedChapter( newChapter );
//mainWindow.updateTree();
mainWindow.reloadData( );
return true;
}
public NPC getNPC(String npcId){
return this.getSelectedChapterDataControl().getNPCsList( ).getNPC( npcId );
}
private boolean loadFile( String completeFilePath, boolean loadingImage ) {
boolean fileLoaded = false;
boolean hasIncedence = false;
try {
boolean loadFile = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.LoadFileTitle" ), TC.get( "Operation.LoadFileMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
loadFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
loadFile = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
loadFile = false;
}
}
if( loadFile && completeFilePath == null ) {
this.stopAutoSave( );
ConfigData.loadFromXML( ReleaseFolders.configFileEditorRelativePath( ) );
ProjectConfigData.loadFromXML( );
// Show dialog
// StartDialog start = new StartDialog( StartDialog.OPEN_TAB );
FrameForInitialDialogs start = new FrameForInitialDialogs(StartDialog.OPEN_TAB );
//start.askForProject();
//mainWindow.setEnabled( false );
//mainWindow.setExtendedState(JFrame.ICONIFIED | mainWindow.getExtendedState());
mainWindow.setVisible( false );
//int op = start.showOpenDialog( null );
int op = start.showStartDialog( );
//start.end();
if( op == StartDialog.NEW_FILE_OPTION ) {
newFile( start.getFileType( ) );
}
else if( op == StartDialog.OPEN_FILE_OPTION ) {
java.io.File selectedFile = start.getSelectedFile( );
String absPath = selectedFile.getAbsolutePath( ).toLowerCase( );
if( absPath.endsWith( ".eap" ) ) {
String absolutePath = selectedFile.getPath( );
loadFile( absolutePath.substring( 0, absolutePath.length( ) - 4 ), true );
}
else if( selectedFile.isDirectory( ) && selectedFile.exists( ) )
loadFile( start.getSelectedFile( ).getAbsolutePath( ), true );
else
// importGame is the same method for .ead, .jar and .zip (LO) import
this.importGame( selectedFile.getAbsolutePath( ) );
}
else if( op == StartDialog.RECENT_FILE_OPTION ) {
loadFile( start.getRecentFile( ).getAbsolutePath( ), true );
}
else if( op == StartDialog.CANCEL_OPTION ) {
exit( );
}
start.remove();
// if( currentZipFile == null ) {
// mainWindow.reloadData( );
//}
mainWindow.setResizable( true );
mainWindow.setEnabled( true );
mainWindow.setVisible( true );
return true;
}
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.LoadProject" ), getLoadingImage( ), mainWindow);
// If some file was selected
if( completeFilePath != null ) {
if( loadingImage ) {
loadingScreen.setMessage( TC.get( "Operation.LoadProject" ) );
this.loadingScreen.setVisible( true );
loadingImage = true;
}
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Load the data from the file, and update the info
List<Incidence> incidences = new ArrayList<Incidence>( );
//ls.start( );
/*AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator(completeFilePath),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ASSESSMENT),
AssetsController.getCategoryFolder(AssetsController.CATEGORY_ADAPTATION),incidences );
*/
AdventureData loadedAdventureData = Loader.loadAdventureData( AssetsController.getInputStreamCreator( completeFilePath ), incidences, true );
//mainWindow.setNormalState( );
// If the adventure was loaded without problems, update the data
if( loadedAdventureData != null ) {
// Update the values of the controller
currentZipFile = newFile.getAbsolutePath( );
currentZipPath = newFile.getParent( );
currentZipName = newFile.getName( );
loadedAdventureData.setProjectName( currentZipName );
adventureDataControl = new AdventureDataControl( loadedAdventureData );
chaptersController = new ChapterListDataControl( adventureDataControl.getChapters( ) );
// Check asset files
AssetsController.checkAssetFilesConsistency( incidences );
Incidence.sortIncidences( incidences );
// If there is any incidence
if( incidences.size( ) > 0 ) {
boolean abort = fixIncidences( incidences );
if( abort ) {
mainWindow.showInformationDialog( TC.get( "Error.LoadAborted.Title" ), TC.get( "Error.LoadAborted.Message" ) );
hasIncedence = true;
}
}
ProjectConfigData.loadFromXML( );
AssetsController.createFolderStructure( );
AssetsController.addSpecialAssets( );
dataModified = false;
// The file was loaded
fileLoaded = true;
// Reloads the view of the window
mainWindow.reloadData( );
}
}
//if the file was loaded, update the RecentFiles list:
if( fileLoaded ) {
ConfigData.fileLoaded( currentZipFile );
AssetsController.resetCache( );
// Load project config file
ProjectConfigData.loadFromXML( );
startAutoSave( 15 );
// Feedback
//loadingScreen.close( );
if( !hasIncedence )
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedTitle" ), TC.get( "Operation.FileLoadedMessage" ) );
else
mainWindow.showInformationDialog( TC.get( "Operation.FileLoadedWithErrorTitle" ), TC.get( "Operation.FileLoadedWithErrorMessage" ) );
}
else {
// Feedback
//loadingScreen.close( );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
if( loadingImage )
//ls.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
e.printStackTrace( );
fileLoaded = false;
if( loadingImage )
loadingScreen.setVisible( false );
mainWindow.showInformationDialog( TC.get( "Operation.FileNotLoadedTitle" ), TC.get( "Operation.FileNotLoadedMessage" ) );
}
Controller.gc();
return fileLoaded;
}
public boolean importJAR(){
return false;
}
public boolean importLO(){
return false;
}
/**
* Called when the user wants to save data to a file.
*
* @param saveAs
* True if the destiny file must be chosen inconditionally
* @return True if a file was saved successfully, false otherwise
*/
public boolean saveFile( boolean saveAs ) {
boolean fileSaved = false;
try {
boolean saveFile = true;
// Select a new file if it is a "Save as" action
if( saveAs ) {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProjectAs" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentLoadFolder( ), new FolderFileFilter( false, false, null ) );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Create a file to extract the name and path
File newFolder;
File newFile;
if( completeFilePath.endsWith( ".eap" ) ) {
newFile = new File( completeFilePath );
newFolder = new File( completeFilePath.substring( 0, completeFilePath.length( ) - 4 ) );
}
else {
newFile = new File( completeFilePath + ".eap" );
newFolder = new File( completeFilePath );
}
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( newFile ) ) {
if( FolderFileFilter.checkCharacters( newFolder.getName( ) ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file and the file it is not the current path of the project
if( ( this.currentZipFile == null || !newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) && ( ( !newFile.exists( ) && !newFolder.exists( ) ) || !newFolder.exists( ) || newFolder.list( ).length == 0 || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage", newFolder.getName( ) ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
//if( newFile.exists( ) )
// newFile.delete( );
if( !newFile.exists( ) )
newFile.create( );
// If this is a "Save as" operation, copy the assets from the old file to the new one
if( saveAs ) {
loadingScreen.setMessage( TC.get( "Operation.SaveProjectAs" ) );
loadingScreen.setVisible( true );
AssetsController.copyAssets( currentZipFile, newFolder.getAbsolutePath( ) );
}
// Set the new file and path
currentZipFile = newFolder.getAbsolutePath( );
currentZipPath = newFolder.getParent( );
currentZipName = newFolder.getName( );
AssetsController.createFolderStructure();
}
// If the file was not overwritten, don't save the data
else
saveFile = false;
// In case the selected folder is the same that the previous one, report an error
if( !saveFile && this.currentZipFile != null && newFolder.getAbsolutePath( ).toLowerCase( ).equals( this.currentZipFile.toLowerCase( ) ) ) {
this.showErrorDialog( TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Title" ), TC.get( "Operation.SaveProjectAs.TargetFolderInUse.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
saveFile = false;
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
saveFile = false;
}
}
// If no file was selected, don't save the data
else
saveFile = false;
}
else {
//loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.SaveProject" ), getLoadingImage( ), mainWindow);
//loadingScreen.setVisible( true );
loadingScreen.setMessage( TC.get( "Operation.SaveProject" ) );
loadingScreen.setVisible( true );
}
// If the data must be saved
if( saveFile ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
// If the zip was temp file, delete it
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
// Check the consistency of the chapters
boolean valid = chaptersController.isValid( null, null );
// If the data is not valid, show an error message
if( !valid )
mainWindow.showWarningDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventurInconsistentWarning" ) );
// Control the version number
String newValue = increaseVersionNumber( adventureDataControl.getAdventureData( ).getVersionNumber( ) );
adventureDataControl.getAdventureData( ).setVersionNumber( newValue );
// Save the data
if( Writer.writeData( currentZipFile, adventureDataControl, valid ) ) {
File eapFile = new File( currentZipFile + ".eap" );
if( !eapFile.exists( ) )
eapFile.create( );
// Set modified to false and update the window title
dataModified = false;
mainWindow.updateTitle( );
// The file was saved
fileSaved = true;
}
}
//If the file was saved, update the recent files list:
if( fileSaved ) {
ConfigData.fileLoaded( currentZipFile );
ProjectConfigData.storeToXML( );
AssetsController.resetCache( );
// also, look for adaptation and assessment folder, and delete them
File currentAssessFolder = new File( currentZipFile + File.separator + "assessment" );
if( currentAssessFolder.exists( ) ) {
File[] files = currentAssessFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAssessFolder.delete( );
}
File currentAdaptFolder = new File( currentZipFile + File.separator + "adaptation" );
if( currentAdaptFolder.exists( ) ) {
File[] files = currentAdaptFolder.listFiles( );
for( int x = 0; x < files.length; x++ )
files[x].delete( );
currentAdaptFolder.delete( );
}
}
}
catch( Exception e ) {
fileSaved = false;
mainWindow.showInformationDialog( TC.get( "Operation.FileNotSavedTitle" ), TC.get( "Operation.FileNotSavedMessage" ) );
}
Controller.gc();
loadingScreen.setVisible( false );
return fileSaved;
}
/**
* Increase the game version number
*
* @param digits
* @param index
* @return the version number after increase it
*/
private String increaseVersionNumber( char[] digits, int index ) {
if( digits[index] != '9' ) {
// increase in "1" the ASCII code
digits[index]++;
return new String( digits );
}
else if( index == 0 ) {
char[] aux = new char[ digits.length + 1 ];
aux[0] = '1';
aux[1] = '0';
for( int i = 2; i < aux.length; i++ )
aux[i] = digits[i - 1];
return new String( aux );
}
else {
digits[index] = '0';
return increaseVersionNumber( digits, --index );
}
}
private String increaseVersionNumber( String versionNumber ) {
char[] digits = versionNumber.toCharArray( );
return increaseVersionNumber( digits, digits.length - 1 );
}
public void importChapter( ) {
}
public void importGame( ) {
importGame( null );
}
public void importGame( String eadPath ) {
boolean importGame = true;
java.io.File selectedFile = null;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
importGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION ) {
importGame = true;
dataModified = false;
mainWindow.updateTitle( );
}
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION ) {
importGame = false;
}
}
if( importGame ) {
if (eadPath.endsWith( ".zip" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportLO.InfoMessage" ) );
else if (eadPath.endsWith( ".jar" ))
mainWindow.showInformationDialog( TC.get( "Operation.ImportProject" ), TC.get( "Operation.ImportJAR.InfoMessage" ));
// Ask origin file
JFileChooser chooser = new JFileChooser( );
chooser.setFileFilter( new EADFileFilter( ) );
chooser.setMultiSelectionEnabled( false );
chooser.setCurrentDirectory( new File( getCurrentExportSaveFolder( ) ) );
int option = JFileChooser.APPROVE_OPTION;
if( eadPath == null )
option = chooser.showOpenDialog( mainWindow );
if( option == JFileChooser.APPROVE_OPTION ) {
java.io.File originFile = null;
if( eadPath == null )
originFile = chooser.getSelectedFile( );
else
originFile = new File( eadPath );
// if( !originFile.getAbsolutePath( ).endsWith( ".ead" ) )
// originFile = new java.io.File( originFile.getAbsolutePath( ) + ".ead" );
// If the file not exists display error
if( !originFile.exists( ) )
mainWindow.showErrorDialog( TC.get( "Error.Import.FileNotFound.Title" ), TC.get( "Error.Import.FileNotFound.Title", originFile.getName( ) ) );
// Otherwise ask folder for the new project
else {
boolean create = false;
java.io.File selectedDir = null;
// Prompt main folder of the project
// ProjectFolderChooser folderSelector = new ProjectFolderChooser( false, false );
FrameForInitialDialogs start = new FrameForInitialDialogs(false);
// If some folder is selected, check all characters are correct
int op = start.showStartDialog( );
if( op == StartDialog.APROVE_SELECTION ) {
java.io.File selectedFolder = start.getSelectedFile( );
selectedFile = selectedFolder;
if( selectedFolder.getAbsolutePath( ).endsWith( ".eap" ) ) {
String absolutePath = selectedFolder.getAbsolutePath( );
selectedFolder = new java.io.File( absolutePath.substring( 0, absolutePath.length( ) - 4 ) );
}
else {
selectedFile = new java.io.File( selectedFolder.getAbsolutePath( ) + ".eap" );
}
selectedDir = selectedFolder;
// Check the selectedFolder is not inside a forbidden one
if( isValidTargetProject( selectedFolder ) ) {
if( FolderFileFilter.checkCharacters( selectedFolder.getName( ) ) ) {
// Folder can be created/used
// Does the folder exist?
if( selectedFolder.exists( ) ) {
//Is the folder empty?
if( selectedFolder.list( ).length > 0 ) {
// Delete content?
if( this.showStrictConfirmDialog( TC.get( "Operation.NewProject.FolderNotEmptyTitle" ), TC.get( "Operation.NewProject.FolderNotEmptyMessage" ) ) ) {
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.deleteAll( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.DeletingFolderContents" ) );
}
} // FIXME: else branch to return to previous dialog when the user tries to assign an existing name to his project
// and select "no" in re-writing confirmation panel
}
else {
create = true;
}
}
else {
// Create new folder?
File directory = new File( selectedFolder.getAbsolutePath( ) );
if( directory.mkdirs( ) ) {
create = true;
}
else {
this.showStrictConfirmDialog( TC.get( "Error.Title" ), TC.get( "Error.CreatingFolder" ) );
}
}
}
else {
// Display error message
this.showErrorDialog( TC.get( "Error.Title" ), TC.get( "Error.ProjectFolderName", FolderFileFilter.getAllowedChars( ) ) );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.NewProject.ForbiddenParent.Title" ), TC.get( "Operation.NewProject.ForbiddenParent.Message" ) );
create = false;
}
}
start.remove();
// Create the new project?
if( create ) {
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ImportProject" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ImportProject" ) );
loadingScreen.setVisible( true );
//AssetsController.createFolderStructure();
if( !selectedDir.exists( ) )
selectedDir.mkdirs( );
if( selectedFile != null && !selectedFile.exists( ) )
selectedFile.createNewFile( );
boolean correctFile = true;
// Unzip directory
if (eadPath.endsWith( ".ead" ))
File.unzipDir( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) );
else if (eadPath.endsWith( ".zip" )){
// import EadJAR returns false when selected jar is not a eadventure jar
if (!File.importEadventureLO( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get( "Operation.ImportLO.FileNotLoadedMessage") );
correctFile = false;
}
}else if (eadPath.endsWith( ".jar" )){
// import EadLO returns false when selected zip is not a eadventure LO
if (!File.importEadventureJar( originFile.getAbsolutePath( ), selectedDir.getAbsolutePath( ) )){
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.ImportJAR.FileNotLoaded") );
correctFile = false;
}
}
//ProjectConfigData.loadFromXML( );
// Load new project
if (correctFile) {
loadFile( selectedDir.getAbsolutePath( ), false );
//loadingScreen.close( );
loadingScreen.setVisible( false );
} else {
//remove .eapFile
selectedFile.delete( );
selectedDir.delete( );
}
}
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotLoadedTitle"), TC.get("Operation.FileNotLoadedMessage" ));
}
}
public boolean exportGame( ) {
return exportGame( null );
}
public boolean exportGame( String targetFilePath ) {
boolean exportGame = true;
boolean exported = false;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String selectedPath = targetFilePath;
if( selectedPath == null )
selectedPath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new EADFileFilter( ) );
if( selectedPath != null ) {
if( !selectedPath.toLowerCase( ).endsWith( ".ead" ) )
selectedPath = selectedPath + ".ead";
java.io.File destinyFile = new File( selectedPath );
// Check the destinyFile is not in the project folder
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
// If the file exists, ask to overwrite
if( !destinyFile.exists( ) || targetFilePath != null || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsEAD" ), getLoadingImage( ), mainWindow);
if( targetFilePath == null ) {
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsEAD" ) );
loadingScreen.setVisible( true );
}
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
exported = true;
if( targetFilePath == null )
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
if( targetFilePath == null )
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
exported = false;
}
return exported;
}
public boolean createBackup( String targetFilePath ) {
boolean fileSaved = false;
if( targetFilePath == null )
targetFilePath = currentZipFile + ".tmp";
File category = new File( currentZipFile, "backup" );
try {
boolean valid = chaptersController.isValid( null, null );
category.create( );
if( Writer.writeData( currentZipFile + File.separatorChar + "backup", adventureDataControl, valid ) ) {
fileSaved = true;
}
if( fileSaved ) {
String selectedPath = targetFilePath;
if( selectedPath != null ) {
java.io.File destinyFile = new File( selectedPath );
if( targetFilePath != null || isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || targetFilePath != null ) {
destinyFile.delete( );
if( Writer.export( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) )
fileSaved = true;
}
}
else
fileSaved = false;
}
}
}
catch( Exception e ) {
fileSaved = false;
}
if( category.exists( ) ) {
category.deleteAll( );
}
return fileSaved;
}
public void exportStandaloneGame( ) {
boolean exportGame = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportGame = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportGame = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportGame = false;
}
if( exportGame ) {
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new JARFileFilter());
if( completeFilePath != null ) {
if( !completeFilePath.toLowerCase( ).endsWith( ".jar" ) )
completeFilePath = completeFilePath + ".jar";
// If the file exists, ask to overwrite
java.io.File destinyFile = new File( completeFilePath );
// Check the destinyFile is not in the project folder
if( isValidTargetFile( destinyFile ) ) {
if( !destinyFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", destinyFile.getName( ) ) ) ) {
destinyFile.delete( );
// Finally, export it
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsJAR" ) );
loadingScreen.setVisible( true );
if( Writer.exportStandalone( getProjectFolder( ), destinyFile.getAbsolutePath( ) ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
loadingScreen.setVisible( false );
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( TC.get("Operation.FileNotSavedTitle"), TC.get("Operation.FileNotSavedMessage") );
}
}
public void exportToLOM( ) {
boolean exportFile = true;
try {
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.SaveChangesTitle" ), TC.get( "Operation.SaveChangesMessage" ) );
// If the data must be saved, load the new file only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exportFile = saveFile( false );
// If the data must not be saved, load the new data directly
else if( option == JOptionPane.NO_OPTION )
exportFile = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exportFile = false;
}
if( exportFile ) {
// Ask the data of the Learning Object:
ExportToLOMDialog dialog = new ExportToLOMDialog( TC.get( "Operation.ExportToLOM.DefaultValue" ) );
String loName = dialog.getLomName( );
String authorName = dialog.getAuthorName( );
String organization = dialog.getOrganizationName( );
boolean windowed = dialog.getWindowed( );
int type = dialog.getType( );
boolean validated = dialog.isValidated( );
if( type == 2 && !hasScormProfiles( SCORM12 ) ) {
// error situation: both profiles must be scorm 1.2 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM12.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM12.BadProfiles.Message" ) );
}
else if( type == 3 && !hasScormProfiles( SCORM2004 ) ) {
// error situation: both profiles must be scorm 2004 if they exist
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004.BadProfiles.Message" ) );
}
else if( type == 4 && !hasScormProfiles( AGREGA ) ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
}
//TODO comprobaciones de perfiles
// else if( type == 5 ) {
// error situation: both profiles must be scorm 2004 if they exist to export to AGREGA
// mainWindow.showErrorDialog( TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Title" ), TC.get( "Operation.ExportSCORM2004AGREGA.BadProfiles.Message" ) );
if( validated ) {
//String loName = this.showInputDialog( TextConstants.getText( "Operation.ExportToLOM.Title" ), TextConstants.getText( "Operation.ExportToLOM.Message" ), TextConstants.getText( "Operation.ExportToLOM.DefaultValue" ));
if( loName != null && !loName.equals( "" ) && !loName.contains( " " ) ) {
//Check authorName & organization
if( authorName != null && authorName.length( ) > 5 && organization != null && organization.length( ) > 5 ) {
//Ask for the name of the zip
String completeFilePath = null;
completeFilePath = mainWindow.showSaveDialog( getCurrentExportSaveFolder( ), new FileFilter( ) {
@Override
public boolean accept( java.io.File arg0 ) {
return arg0.getAbsolutePath( ).toLowerCase( ).endsWith( ".zip" ) || arg0.isDirectory( );
}
@Override
public String getDescription( ) {
return "Zip files (*.zip)";
}
} );
// If some file was selected set the new file
if( completeFilePath != null ) {
// Add the ".zip" if it is not present in the name
if( !completeFilePath.toLowerCase( ).endsWith( ".zip" ) )
completeFilePath += ".zip";
// Create a file to extract the name and path
File newFile = new File( completeFilePath );
// Check the selected file is contained in a valid folder
if( isValidTargetFile( newFile ) ) {
// If the file doesn't exist, or if the user confirms the writing in the file
if( !newFile.exists( ) || mainWindow.showStrictConfirmDialog( TC.get( "Operation.SaveFileTitle" ), TC.get( "Operation.OverwriteExistingFile", newFile.getName( ) ) ) ) {
// If the file exists, delete it so it's clean in the first save
try {
if( newFile.exists( ) )
newFile.delete( );
//LoadingScreen loadingScreen = new LoadingScreen(TextConstants.getText( "Operation.ExportProject.AsJAR" ), getLoadingImage( ), mainWindow);
loadingScreen.setMessage( TC.get( "Operation.ExportProject.AsLO" ) );
loadingScreen.setVisible( true );
this.updateLOMLanguage( );
if( type == 0 && Writer.exportAsLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 1 && Writer.exportAsWebCTObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 2 && Writer.exportAsSCORM( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 3 && Writer.exportAsSCORM2004( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 4 && Writer.exportAsAGREGA( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ) {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else if( type == 5 && Writer.exportAsLAMSLearningObject( completeFilePath, loName, authorName, organization, windowed, this.currentZipFile, adventureDataControl ) ){
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.Success.Title" ), TC.get( "Operation.ExportT.Success.Message" ) );
}
else {
mainWindow.showInformationDialog( TC.get( "Operation.ExportT.NotSuccess.Title" ), TC.get( "Operation.ExportT.NotSuccess.Message" ) );
}
//loadingScreen.close( );
loadingScreen.setVisible( false );
}
catch( Exception e ) {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
ReportDialog.GenerateErrorReport( e, true, TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ) );
}
}
}
else {
// Show error: The target dir cannot be contained
mainWindow.showErrorDialog( TC.get( "Operation.ExportT.TargetInProjectDir.Title" ), TC.get( "Operation.ExportT.TargetInProjectDir.Message" ) );
}
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Title" ), TC.get( "Operation.ExportToLOM.AuthorNameOrganizationNotValid.Message" ) );
}
}
else {
this.showErrorDialog( TC.get( "Operation.ExportToLOM.LONameNotValid.Title" ), TC.get( "Operation.ExportToLOM.LONameNotValid.Message" ) );
}
}
}
}
catch( Exception e ) {
loadingScreen.setVisible( false );
mainWindow.showErrorDialog( "Operation.FileNotSavedTitle", "Operation.FileNotSavedMessage" );
}
}
/**
* Check if assessment and adaptation profiles are both scorm 1.2 or scorm
* 2004
*
* @param scormType
* the scorm type, 1.2 or 2004
* @return
*/
private boolean hasScormProfiles( int scormType ) {
if( scormType == SCORM12 ) {
// check that adaptation and assessment profiles are scorm 1.2 profiles
return chaptersController.hasScorm12Profiles( adventureDataControl );
}
else if( scormType == SCORM2004 || scormType == AGREGA ) {
// check that adaptation and assessment profiles are scorm 2004 profiles
return chaptersController.hasScorm2004Profiles( adventureDataControl );
}
return false;
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void run( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
// First update flags
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.normalRun( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Executes the current project. Firstly, it checks that the game does not
* present any consistency errors. Then exports the project to the web dir
* as a temp .ead file and gets it running
*/
public void debugRun( ) {
stopAutoSave( );
// Check adventure consistency
if( checkAdventureConsistency( false ) ) {
this.getSelectedChapterDataControl( ).getConversationsList( ).resetAllConversationNodes( );
new Timer( ).schedule( new TimerTask( ) {
@Override
public void run( ) {
if( canBeRun( ) ) {
mainWindow.setNormalRunAvailable( false );
chaptersController.updateVarsFlagsForRunning( );
EAdventureDebug.debug( Controller.getInstance( ).adventureDataControl.getAdventureData( ), AssetsController.getInputStreamCreator( ) );
Controller.getInstance( ).startAutoSave( 15 );
mainWindow.setNormalRunAvailable( true );
}
}
}, 1000 );
}
}
/**
* Check if the current project is saved before run. If not, ask user to
* save it.
*
* @return if false is returned, the game will not be launched
*/
private boolean canBeRun( ) {
if( dataModified ) {
if( mainWindow.showStrictConfirmDialog( TC.get( "Run.CanBeRun.Title" ), TC.get( "Run.CanBeRun.Text" ) ) ) {
this.saveFile( false );
return true;
}
else
return false;
}
else
return true;
}
/**
* Determines if the target file of an exportation process is valid. The
* file cannot be located neither inside the project folder, nor inside the
* web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetFile( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ), getProjectFolderFile( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Determines if the target folder for a new project is valid. The folder
* cannot be located inside the web folder
*
* @param targetFile
* @return
*/
private boolean isValidTargetProject( java.io.File targetFile ) {
java.io.File[] forbiddenParents = new java.io.File[] { ReleaseFolders.webFolder( ), ReleaseFolders.webTempFolder( ) };
boolean isValid = true;
for( java.io.File forbiddenParent : forbiddenParents ) {
if( targetFile.getAbsolutePath( ).toLowerCase( ).startsWith( forbiddenParent.getAbsolutePath( ).toLowerCase( ) ) ) {
isValid = false;
break;
}
}
return isValid;
}
/**
* Exits from the aplication.
*/
public void exit( ) {
boolean exit = true;
// If the data was not saved, ask for an action (save, discard changes...)
if( dataModified ) {
int option = mainWindow.showConfirmDialog( TC.get( "Operation.ExitTitle" ), TC.get( "Operation.ExitMessage" ) );
// If the data must be saved, lexit only if the save was succesful
if( option == JOptionPane.YES_OPTION )
exit = saveFile( false );
// If the data must not be saved, exit directly
else if( option == JOptionPane.NO_OPTION )
exit = true;
// Cancel the action if selected
else if( option == JOptionPane.CANCEL_OPTION )
exit = false;
//if( isTempFile( ) ) {
// File file = new File( oldZipFile );
// file.deleteOnExit( );
// isTempFile = false;
//}
}
// Exit the aplication
if( exit ) {
ConfigData.storeToXML( );
ProjectConfigData.storeToXML( );
//AssetsController.cleanVideoCache( );
System.exit( 0 );
}
}
/**
* Checks if the adventure is valid or not. It shows information to the
* user, whether the data is valid or not.
*/
public boolean checkAdventureConsistency( ) {
return checkAdventureConsistency( true );
}
public boolean checkAdventureConsistency( boolean showSuccessFeedback ) {
// Create a list to store the incidences
List<String> incidences = new ArrayList<String>( );
// Check all the chapters
boolean valid = chaptersController.isValid( null, incidences );
// If the data is valid, show a dialog with the information
if( valid ) {
if( showSuccessFeedback )
mainWindow.showInformationDialog( TC.get( "Operation.AdventureConsistencyTitle" ), TC.get( "Operation.AdventureConsistentReport" ) );
// If it is not valid, show a dialog with the problems
}
else
new InvalidReportDialog( incidences, TC.get( "Operation.AdventureInconsistentReport" ) );
return valid;
}
public void checkFileConsistency( ) {
}
/**
* Shows the adventure data dialog editor.
*/
public void showAdventureDataDialog( ) {
new AdventureDataDialog( );
}
/**
* Shows the LOM data dialog editor.
*/
public void showLOMDataDialog( ) {
isLomEs = false;
new LOMDialog( adventureDataControl.getLomController( ) );
}
/**
* Shows the LOM for SCORM packages data dialog editor.
*/
public void showLOMSCORMDataDialog( ) {
isLomEs = false;
new IMSDialog( adventureDataControl.getImsController( ) );
}
/**
* Shows the LOMES for AGREGA packages data dialog editor.
*/
public void showLOMESDataDialog( ) {
isLomEs = true;
new LOMESDialog( adventureDataControl.getLOMESController( ) );
}
/**
* Shows the GUI style selection dialog.
*/
public void showGUIStylesDialog( ) {
adventureDataControl.showGUIStylesDialog( );
}
public void changeToolGUIStyleDialog( int optionSelected ){
if (optionSelected != 1){
adventureDataControl.setGUIStyleDialog( optionSelected );
}
}
/**
* Asks for confirmation and then deletes all unreferenced assets. Checks
* for animations indirectly referenced assets.
*/
public void deleteUnsuedAssets( ) {
if( !this.showStrictConfirmDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.Warning" ) ) )
return;
int deletedAssetCount = 0;
ArrayList<String> assets = new ArrayList<String>( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BACKGROUND ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_VIDEO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_CURSOR ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_BUTTON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ICON ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_STYLED_TEXT ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ARROW_BOOK ) )
if( !assets.contains( temp ) )
assets.add( temp );
/* assets.remove( "gui/cursors/arrow_left.png" );
assets.remove( "gui/cursors/arrow_right.png" ); */
for( String temp : assets ) {
int references = 0;
references = countAssetReferences( temp );
if( references == 0 ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp ).delete( );
deletedAssetCount++;
}
}
assets.clear( );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_AUDIO ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION_IMAGE ) )
if( !assets.contains( temp ) )
assets.add( temp );
for( String temp : AssetsController.getAssetsList( AssetsController.CATEGORY_ANIMATION ) )
if( !assets.contains( temp ) )
assets.add( temp );
int i = 0;
while( i < assets.size( ) ) {
String temp = assets.get( i );
if( countAssetReferences( AssetsController.removeSuffix( temp ) ) != 0 ) {
assets.remove( temp );
if( temp.endsWith( "eaa" ) ) {
Animation a = Loader.loadAnimation( AssetsController.getInputStreamCreator( ), temp, new EditorImageLoader( ) );
for( Frame f : a.getFrames( ) ) {
if( f.getUri( ) != null && assets.contains( f.getUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
if( f.getSoundUri( ) != null && assets.contains( f.getSoundUri( ) ) ) {
for( int j = 0; j < assets.size( ); j++ ) {
if( assets.get( j ).equals( f.getSoundUri( ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
}
}
}
}
else {
int j = 0;
while( j < assets.size( ) ) {
if( assets.get( j ).startsWith( AssetsController.removeSuffix( temp ) ) ) {
if( j < i )
i--;
assets.remove( j );
}
else
j++;
}
}
}
else {
i++;
}
}
for( String temp2 : assets ) {
new File( Controller.getInstance( ).getProjectFolder( ), temp2 ).delete( );
deletedAssetCount++;
}
if( deletedAssetCount != 0 )
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.AssetsDeleted", new String[] { String.valueOf( deletedAssetCount ) } ) );
else
mainWindow.showInformationDialog( TC.get( "DeleteUnusedAssets.Title" ), TC.get( "DeleteUnusedAssets.NoUnsuedAssetsFound" ) );
}
/**
* Shows the flags dialog.
*/
public void showEditFlagDialog( ) {
new VarsFlagsDialog( new VarFlagsController( getVarFlagSummary( ) ) );
}
/**
* Sets a new selected chapter with the given index.
*
* @param selectedChapter
* Index of the new selected chapter
*/
public void setSelectedChapter( int selectedChapter ) {
chaptersController.setSelectedChapterInternal( selectedChapter );
mainWindow.reloadData( );
}
public void updateVarFlagSummary( ) {
chaptersController.updateVarFlagSummary( );
}
/**
* Adds a new chapter to the adventure. This method asks for the title of
* the chapter to the user, and updates the view of the application if a new
* chapter was added.
*/
public void addChapter( ) {
addTool( new AddChapterTool( chaptersController ) );
}
/**
* Deletes the selected chapter from the adventure. This method asks the
* user for confirmation, and updates the view if needed.
*/
public void deleteChapter( ) {
addTool( new DeleteChapterTool( chaptersController ) );
}
/**
* Moves the selected chapter to the previous position of the chapter's
* list.
*/
public void moveChapterUp( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_UP, chaptersController ) );
}
/**
* Moves the selected chapter to the next position of the chapter's list.
*
*/
public void moveChapterDown( ) {
addTool( new MoveChapterTool( MoveChapterTool.MODE_DOWN, chaptersController ) );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods to edit and get the adventure general data (title and description)
/**
* Returns the title of the adventure.
*
* @return Adventure's title
*/
public String getAdventureTitle( ) {
return adventureDataControl.getTitle( );
}
/**
* Returns the description of the adventure.
*
* @return Adventure's description
*/
public String getAdventureDescription( ) {
return adventureDataControl.getDescription( );
}
/**
* Returns the LOM controller.
*
* @return Adventure LOM controller.
*
*/
public LOMDataControl getLOMDataControl( ) {
return adventureDataControl.getLomController( );
}
/**
* Sets the new title of the adventure.
*
* @param title
* Title of the adventure
*/
public void setAdventureTitle( String title ) {
// If the value is different
if( !title.equals( adventureDataControl.getTitle( ) ) ) {
// Set the new title and modify the data
adventureDataControl.setTitle( title );
}
}
/**
* Sets the new description of the adventure.
*
* @param description
* Description of the adventure
*/
public void setAdventureDescription( String description ) {
// If the value is different
if( !description.equals( adventureDataControl.getDescription( ) ) ) {
// Set the new description and modify the data
adventureDataControl.setDescription( description );
}
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods that perform specific tasks for the microcontrollers
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId ) {
return isElementIdValid( elementId, true );
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user
* if showError is true
*
* @param elementId
* Element identifier to be checked
* @param showError
* True if the error message must be shown
* @return True if the identifier is valid, false otherwise
*/
public boolean isElementIdValid( String elementId, boolean showError ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) && !elementId.contains( "'" )) {
// If the identifier doesn't exist already
if( !getIdentifierSummary( ).existsId( elementId ) ) {
// If the identifier is not a reserved identifier
if( !elementId.equals( Player.IDENTIFIER ) && !elementId.equals( TC.get( "ConversationLine.PlayerName" ) ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) ){
elementIdValid = isCharacterValid(elementId);
if (!elementIdValid)
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorCharacter" ) );
}
// Show non-letter first character error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show invalid identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorReservedIdentifier", elementId ) );
}
// Show repeated identifier error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorAlreadyUsed" ) );
}
// Show blank spaces error
else if( showError )
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
public boolean isCharacterValid(String elementId){
Character chId;
boolean isValid = true;
int i=1;
while (i < elementId.length( ) && isValid) {
chId = elementId.charAt( i );
isValid = Character.isLetterOrDigit( chId );
i++;
}
return isValid;
}
/**
* Returns whether the given identifier is valid or not. If the element
* identifier is not valid, this method shows an error message to the user.
*
* @param elementId
* Element identifier to be checked
* @return True if the identifier is valid, false otherwise
*/
public boolean isPropertyIdValid( String elementId ) {
boolean elementIdValid = false;
// Check if the identifier has no spaces
if( !elementId.contains( " " ) ) {
// If the first character is a letter
if( Character.isLetter( elementId.charAt( 0 ) ) )
elementIdValid = true;
// Show non-letter first character error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorFirstCharacter" ) );
}
// Show blank spaces error
else
mainWindow.showErrorDialog( TC.get( "Operation.IdErrorTitle" ), TC.get( "Operation.IdErrorBlankSpaces" ) );
return elementIdValid;
}
/**
* This method returns the absolute path of the background image of the
* given scene.
*
* @param sceneId
* Scene id
* @return Path to the background image, null if it was not found
*/
public String getSceneImagePath( String sceneId ) {
String sceneImagePath = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) )
sceneImagePath = scene.getPreviewBackground( );
return sceneImagePath;
}
/**
* This method returns the trajectory of a scene from its id.
*
* @param sceneId
* Scene id
* @return Trajectory of the scene, null if it was not found
*/
public Trajectory getSceneTrajectory( String sceneId ) {
Trajectory trajectory = null;
// Search for the image in the list, comparing the identifiers
for( SceneDataControl scene : getSelectedChapterDataControl( ).getScenesList( ).getScenes( ) )
if( sceneId.equals( scene.getId( ) ) && scene.getTrajectory( ).hasTrajectory( ) )
trajectory = (Trajectory) scene.getTrajectory( ).getContent( );
return trajectory;
}
/**
* This method returns the absolute path of the default image of the player.
*
* @return Default image of the player
*/
public String getPlayerImagePath( ) {
if( getSelectedChapterDataControl( ) != null )
return getSelectedChapterDataControl( ).getPlayer( ).getPreviewImage( );
else
return null;
}
/**
* Returns the player
*/
public Player getPlayer(){
return (Player)getSelectedChapterDataControl( ).getPlayer( ).getContent( );
}
/**
* This method returns the absolute path of the default image of the given
* element (item or character).
*
* @param elementId
* Id of the element
* @return Default image of the requested element
*/
public String getElementImagePath( String elementId ) {
String elementImage = null;
// Search for the image in the items, comparing the identifiers
for( ItemDataControl item : getSelectedChapterDataControl( ).getItemsList( ).getItems( ) )
if( elementId.equals( item.getId( ) ) )
elementImage = item.getPreviewImage( );
// Search for the image in the characters, comparing the identifiers
for( NPCDataControl npc : getSelectedChapterDataControl( ).getNPCsList( ).getNPCs( ) )
if( elementId.equals( npc.getId( ) ) )
elementImage = npc.getPreviewImage( );
// Search for the image in the items, comparing the identifiers
for( AtrezzoDataControl atrezzo : getSelectedChapterDataControl( ).getAtrezzoList( ).getAtrezzoList( ) )
if( elementId.equals( atrezzo.getId( ) ) )
elementImage = atrezzo.getPreviewImage( );
return elementImage;
}
/**
* Counts all the references to a given asset in the entire script.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
* @return Number of references to the given asset
*/
public int countAssetReferences( String assetPath ) {
return adventureDataControl.countAssetReferences( assetPath ) + chaptersController.countAssetReferences( assetPath );
}
/**
* Gets a list with all the assets referenced in the chapter along with the
* types of those assets
*
* @param assetPaths
* @param assetTypes
*/
public void getAssetReferences( List<String> assetPaths, List<Integer> assetTypes ) {
adventureDataControl.getAssetReferences( assetPaths, assetTypes );
chaptersController.getAssetReferences( assetPaths, assetTypes );
}
/**
* Deletes a given asset from the script, removing all occurrences.
*
* @param assetPath
* Path of the asset (relative to the ZIP), without suffix in
* case of an animation or set of slides
*/
public void deleteAssetReferences( String assetPath ) {
adventureDataControl.deleteAssetReferences( assetPath );
chaptersController.deleteAssetReferences( assetPath );
}
/**
* Counts all the references to a given identifier in the entire script.
*
* @param id
* Identifier to which the references must be found
* @return Number of references to the given identifier
*/
public int countIdentifierReferences( String id ) {
return getSelectedChapterDataControl( ).countIdentifierReferences( id );
}
/**
* Deletes a given identifier from the script, removing all occurrences.
*
* @param id
* Identifier to be deleted
*/
public void deleteIdentifierReferences( String id ) {
chaptersController.deleteIdentifierReferences( id );
}
/**
* Replaces a given identifier with another one, in all the occurrences in
* the script.
*
* @param oldId
* Old identifier to be replaced
* @param newId
* New identifier to replace the old one
*/
public void replaceIdentifierReferences( String oldId, String newId ) {
getSelectedChapterDataControl( ).replaceIdentifierReferences( oldId, newId );
}
// ///////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods linked with the GUI
/**
* Updates the chapter menu with the new names of the chapters.
*/
public void updateChapterMenu( ) {
mainWindow.updateChapterMenu( );
}
/**
* Updates the tree of the main window.
*/
public void updateStructure( ) {
mainWindow.updateStructure( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadPanel( ) {
mainWindow.reloadPanel( );
}
public void updatePanel( ) {
mainWindow.updatePanel( );
}
/**
* Reloads the panel of the main window currently being used.
*/
public void reloadData( ) {
mainWindow.reloadData( );
}
/**
* Returns the last window opened by the application.
*
* @return Last window opened
*/
public Window peekWindow( ) {
return mainWindow.peekWindow( );
}
/**
* Pushes a new window in the windows stack.
*
* @param window
* Window to push
*/
public void pushWindow( Window window ) {
mainWindow.pushWindow( window );
}
/**
* Pops the last window pushed into the stack.
*/
public void popWindow( ) {
mainWindow.popWindow( );
}
/**
* Shows a load dialog to select multiple files.
*
* @param filter
* File filter for the dialog
* @return Full path of the selected files, null if no files were selected
*/
public String[] showMultipleSelectionLoadDialog( FileFilter filter ) {
return mainWindow.showMultipleSelectionLoadDialog( currentZipPath, filter );
}
/**
* Shows a dialog with the options "Yes" and "No", with the given title and
* text.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @return True if the "Yes" button was pressed, false otherwise
*/
public boolean showStrictConfirmDialog( String title, String message ) {
return mainWindow.showStrictConfirmDialog( title, message );
}
/**
* Shows a dialog with the given set of options.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param options
* Array of strings containing the options of the dialog
* @return The index of the option selected, JOptionPane.CLOSED_OPTION if
* the dialog was closed.
*/
public int showOptionDialog( String title, String message, String[] options ) {
return mainWindow.showOptionDialog( title, message, options );
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param defaultValue
* Default value of the dialog
* @return String typed in the dialog, null if the cancel button was pressed
*/
public String showInputDialog( String title, String message, String defaultValue ) {
return mainWindow.showInputDialog( title, message, defaultValue );
}
public String showInputDialog( String title, String message) {
return mainWindow.showInputDialog( title, message);
}
/**
* Uses the GUI to show an input dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
* @param selectionValues
* Possible selection values of the dialog
* @return Option selected in the dialog, null if the cancel button was
* pressed
*/
public String showInputDialog( String title, String message, Object[] selectionValues ) {
return mainWindow.showInputDialog( title, message, selectionValues );
}
/**
* Uses the GUI to show an error dialog.
*
* @param title
* Title of the dialog
* @param message
* Message of the dialog
*/
public void showErrorDialog( String title, String message ) {
mainWindow.showErrorDialog( title, message );
}
public void showCustomizeGUIDialog( ) {
new CustomizeGUIDialog( this.adventureDataControl );
}
public boolean isFolderLoaded( ) {
return chaptersController.isAnyChapterSelected( );
}
public String getEditorMinVersion( ) {
return "1.0b";
}
public String getEditorVersion( ) {
return "1.0b";
}
public void updateLOMLanguage( ) {
this.adventureDataControl.getLomController( ).updateLanguage( );
}
public void updateIMSLanguage( ) {
this.adventureDataControl.getImsController( ).updateLanguage( );
}
public void showAboutDialog( ) {
try {
JDialog dialog = new JDialog( Controller.getInstance( ).peekWindow( ), TC.get( "About" ), Dialog.ModalityType.TOOLKIT_MODAL );
dialog.getContentPane( ).setLayout( new BorderLayout( ) );
JPanel panel = new JPanel();
panel.setLayout( new BorderLayout() );
File file = new File( ConfigData.getAboutFile( ) );
if( file.exists( ) ) {
JEditorPane pane = new JEditorPane( );
pane.setPage( file.toURI( ).toURL( ) );
pane.setEditable( false );
panel.add( pane, BorderLayout.CENTER );
}
JPanel version = new JPanel();
version.setLayout( new BorderLayout() );
JButton checkVersion = new JButton(TC.get( "About.CheckNewVersion" ));
version.add(checkVersion, BorderLayout. CENTER);
final JLabel label = new JLabel("");
version.add(label, BorderLayout.SOUTH);
checkVersion.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
java.io.BufferedInputStream in = null;
try {
in = new java.io.BufferedInputStream(new java.net.URL("http://e-adventure.e-ucm.es/files/version").openStream());
byte data[] = new byte[1024];
int bytes = 0;
String a = null;
while((bytes = in.read(data,0,1024)) >= 0)
{
a = new String(data, 0, bytes);
}
a = a.substring( 0, a.length( ) - 1 );
System.out.println(getCurrentVersion().split( "-" )[0] + " " + a);
if (getCurrentVersion().split( "-" )[0].equals( a )) {
label.setText(TC.get( "About.LatestRelease" ));
} else {
label.setText( TC.get("About.NewReleaseAvailable"));
}
label.updateUI( );
in.close();
}
catch( IOException e1 ) {
label.setText( TC.get( "About.LatestRelease" ) );
label.updateUI( );
}
}
});
panel.add( version, BorderLayout.NORTH );
dialog.getContentPane( ).add( panel, BorderLayout.CENTER );
dialog.setSize( 275, 560 );
Dimension screenSize = Toolkit.getDefaultToolkit( ).getScreenSize( );
dialog.setLocation( ( screenSize.width - dialog.getWidth( ) ) / 2, ( screenSize.height - dialog.getHeight( ) ) / 2 );
dialog.setVisible( true );
}
catch( IOException e ) {
ReportDialog.GenerateErrorReport( e, true, "UNKNOWERROR" );
}
}
private String getCurrentVersion() {
File moreinfo = new File( "RELEASE" );
String release = null;
if( moreinfo.exists( ) ) {
try {
FileInputStream fis = new FileInputStream( moreinfo );
BufferedInputStream bis = new BufferedInputStream( fis );
int nextChar = -1;
while( ( nextChar = bis.read( ) ) != -1 ) {
if( release == null )
release = "" + (char) nextChar;
else
release += (char) nextChar;
}
if( release != null ) {
return release;
}
}
catch( Exception ex ) {
}
}
return "NOVERSION";
}
public AssessmentProfilesDataControl getAssessmentController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAssessmentProfilesDataControl( );
}
public AdaptationProfilesDataControl getAdaptationController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdaptationProfilesDataControl( );
}
public boolean isCommentaries( ) {
return this.adventureDataControl.isCommentaries( );
}
public void setCommentaries( boolean b ) {
this.adventureDataControl.setCommentaries( b );
}
public boolean isKeepShowing( ) {
return this.adventureDataControl.isKeepShowing( );
}
public void setKeepShowing( boolean b ) {
this.adventureDataControl.setKeepShowing( b );
}
/**
* Returns an int value representing the current language used to display
* the editor
*
* @return
*/
public String getLanguage( ) {
return this.languageFile;
}
/**
* Get the default lenguage
* @return name of default language in standard internationalization
*/
public String getDefaultLanguage( ) {
return ReleaseFolders.LANGUAGE_DEFAULT;
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window always
*
* @param language
*/
public void setLanguage( String language ) {
setLanguage( language, true );
}
/**
* Sets the current language of the editor. Accepted values are
* {@value #LANGUAGE_ENGLISH} & {@value #LANGUAGE_ENGLISH}. This method
* automatically updates the about, language strings, and loading image
* parameters.
*
* The method will reload the main window if reloadData is true
*
* @param language
*/
public void setLanguage( String language, boolean reloadData ) {
// image loading route
String dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + language + "/Editor2D-Loading.png";
// if there isn't file, load the default file
File fichero = new File(dirImageLoading);
if (!fichero.exists( ))
dirImageLoading = ReleaseFolders.IMAGE_LOADING_DIR + "/" + getDefaultLanguage( ) + "/Editor2D-Loading.png";
//about file route
String dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getAboutFilePath( language );
File fichero2 = new File(dirAboutFile);
if (!fichero2.exists( ))
dirAboutFile = ReleaseFolders.LANGUAGE_DIR_EDITOR + "/" + ReleaseFolders.getDefaultAboutFilePath( );
ConfigData.setLanguangeFile( ReleaseFolders.getLanguageFilePath( language ), dirAboutFile, dirImageLoading );
languageFile = language;
TC.loadStrings( ReleaseFolders.getLanguageFilePath4Editor( true, languageFile ) );
TC.appendStrings( ReleaseFolders.getLanguageFilePath4Editor( false, languageFile ) );
loadingScreen.setImage( getLoadingImage( ) );
if( reloadData )
mainWindow.reloadData( );
}
public String getLoadingImage( ) {
return ConfigData.getLoadingImage( );
}
public void showGraphicConfigDialog( ) {
// Show the dialog
// GraphicConfigDialog guiStylesDialog = new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
new GraphicConfigDialog( adventureDataControl.getGraphicConfig( ) );
// If the new GUI style is different from the current, and valid, change the value
/* int optionSelected = guiStylesDialog.getOptionSelected( );
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
adventureDataControl.setGraphicConfig( optionSelected );
}*/
}
public void changeToolGraphicConfig( int optionSelected ) {
if( optionSelected != -1 && this.adventureDataControl.getGraphicConfig( ) != optionSelected ) {
// this.grafhicDialog.cambiarCheckBox( );
adventureDataControl.setGraphicConfig( optionSelected );
}
}
// METHODS TO MANAGE UNDO/REDO
public boolean addTool( Tool tool ) {
boolean added = chaptersController.addTool( tool );
//tsd.update();
return added;
}
public void undoTool( ) {
chaptersController.undoTool( );
//tsd.update();
}
public void redoTool( ) {
chaptersController.redoTool( );
//tsd.update();
}
public void pushLocalToolManager( ) {
chaptersController.pushLocalToolManager( );
}
public void popLocalToolManager( ) {
chaptersController.popLocalToolManager( );
}
public void search( ) {
new SearchDialog( );
}
public boolean getAutoSaveEnabled( ) {
if( ProjectConfigData.existsKey( "autosave" ) ) {
String temp = ProjectConfigData.getProperty( "autosave" );
if( temp.equals( "yes" ) ) {
return true;
}
else {
return false;
}
}
return true;
}
public void setAutoSaveEnabled( boolean selected ) {
if( selected != getAutoSaveEnabled( ) ) {
ProjectConfigData.setProperty( "autosave", ( selected ? "yes" : "no" ) );
startAutoSave( 15 );
}
}
/**
* @return the isLomEs
*/
public boolean isLomEs( ) {
return isLomEs;
}
public int getGUIConfigConfiguration(){
return this.adventureDataControl.getGraphicConfig( );
}
public String getDefaultExitCursorPath( ) {
String temp = this.adventureDataControl.getCursorPath( "exit" );
if( temp != null && temp.length( ) > 0 )
return temp;
else
return "gui/cursors/exit.png";
}
public AdvancedFeaturesDataControl getAdvancedFeaturesController( ) {
return this.chaptersController.getSelectedChapterDataControl( ).getAdvancedFeaturesController( );
}
public static Color generateColor( int i ) {
int r = ( i * 180 ) % 256;
int g = ( ( i + 4 ) * 130 ) % 256;
int b = ( ( i + 2 ) * 155 ) % 256;
if( r > 250 && g > 250 && b > 250 ) {
r = 0;
g = 0;
b = 0;
}
return new Color( r, g, b );
}
private static final Runnable gc = new Runnable() { public void run() { System.gc( );} };
/**
* Public method to perform garbage collection on a different thread.
*/
public static void gc() {
new Thread(gc).start( );
}
public static java.io.File createTempDirectory() throws IOException
{
final java.io.File temp;
temp = java.io.File.createTempFile("temp", Long.toString(System.nanoTime()));
if(!(temp.delete()))
throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());
if(!(temp.mkdir()))
throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());
return (temp);
}
public DefaultClickAction getDefaultCursorAction( ) {
return this.adventureDataControl.getDefaultClickAction( );
}
public void setDefaultCursorAction( DefaultClickAction defaultClickAction ) {
this.adventureDataControl.setDefaultClickAction(defaultClickAction);
}
public Perspective getPerspective() {
return this.adventureDataControl.getPerspective( );
}
public void setPerspective( Perspective perspective ) {
this.adventureDataControl.setPerspective( perspective );
}
}
|
diff --git a/org.xpect/src/org/xpect/model/XjmMethodImplCustom.java b/org.xpect/src/org/xpect/model/XjmMethodImplCustom.java
index 726a185..00eb9a7 100644
--- a/org.xpect/src/org/xpect/model/XjmMethodImplCustom.java
+++ b/org.xpect/src/org/xpect/model/XjmMethodImplCustom.java
@@ -1,32 +1,31 @@
package org.xpect.model;
import java.lang.reflect.Method;
import org.eclipse.xtext.common.types.JvmOperation;
import org.xpect.util.IJavaReflectAccess;
public class XjmMethodImplCustom extends XjmMethodImpl {
@Override
public String getName() {
return getJvmMethod().getSimpleName();
}
@Override
public void setJvmMethod(JvmOperation newJvmMethod) {
super.javaMethod = null;
super.setJvmMethod(newJvmMethod);
}
@Override
public Method getJavaMethod() {
Method result = super.getJavaMethod();
if (result != null)
return result;
JvmOperation jvmOperation = super.getJvmMethod();
if (jvmOperation == null || jvmOperation.eIsProxy())
return null;
- super.javaMethod = IJavaReflectAccess.INSTANCE.getMethod(jvmOperation);
- return result;
+ return super.javaMethod = IJavaReflectAccess.INSTANCE.getMethod(jvmOperation);
}
}
| true | true | public Method getJavaMethod() {
Method result = super.getJavaMethod();
if (result != null)
return result;
JvmOperation jvmOperation = super.getJvmMethod();
if (jvmOperation == null || jvmOperation.eIsProxy())
return null;
super.javaMethod = IJavaReflectAccess.INSTANCE.getMethod(jvmOperation);
return result;
}
| public Method getJavaMethod() {
Method result = super.getJavaMethod();
if (result != null)
return result;
JvmOperation jvmOperation = super.getJvmMethod();
if (jvmOperation == null || jvmOperation.eIsProxy())
return null;
return super.javaMethod = IJavaReflectAccess.INSTANCE.getMethod(jvmOperation);
}
|
diff --git a/src/main/java/net/larry1123/fly/commands/CFly.java b/src/main/java/net/larry1123/fly/commands/CFly.java
index 8947eee..386b27b 100644
--- a/src/main/java/net/larry1123/fly/commands/CFly.java
+++ b/src/main/java/net/larry1123/fly/commands/CFly.java
@@ -1,344 +1,348 @@
package net.larry1123.fly.commands;
import net.canarymod.Canary;
import net.canarymod.Translator;
import net.canarymod.api.GameMode;
import net.canarymod.api.Server;
import net.canarymod.api.entity.living.humanoid.HumanCapabilities;
import net.canarymod.api.entity.living.humanoid.Player;
import net.canarymod.api.world.blocks.CommandBlock;
import net.canarymod.api.world.position.Location;
import net.canarymod.chat.MessageReceiver;
import net.canarymod.hook.player.TeleportHook;
import net.larry1123.fly.permissions.PermissionsMan;
import net.larry1123.fly.task.FlyTime;
import net.larry1123.util.api.chat.FontTools;
import net.larry1123.util.api.plugin.commands.Command;
import net.larry1123.util.api.plugin.commands.CommandData;
import net.larry1123.util.api.time.StringTime;
import net.visualillusionsent.utils.LocaleHelper;
public class CFly implements Command {
private final CommandData command;
private final CommandMan commandman;
private boolean loaded = false;
// This is to save servers! Warning do not set speed too high in anyway!
private static float maxSpeed;
public CFly(CommandMan commandman, String[] aliases) {
maxSpeed = commandman.getPlugin().getConfigMan().getMainConfig().getMaxSpeed();
this.commandman = commandman;
command = new CommandData( //
aliases, //
new String[]{PermissionsMan.commandNode,}, //
"Allows you or someone else to fly!", //
/**
* fly
* fly Speed
* fly Player
* fly Player Time
* fly Player Speed
* fly Player Speed Time
*/
"/fly [Player|Speed] [Speed|Time] [Time]" //
);
command.setMax(4);
}
@Override
public void execute(MessageReceiver caller, String[] parameters) {
if ((caller instanceof Server || caller instanceof CommandBlock) && parameters.length == 1) {
// Makes sure Server commands and CommandBlock commands at lest have one parameter
caller.message("Must Provide Player");
return;
}
Player player;
float speed = 0;
long time = 0;
if (caller instanceof Player) {
if (parameters.length == 1) {
// fly
player = (Player) caller;
if (!player.getCapabilities().mayFly()) {
speed = (float) 0.05;
} else {
- speed = 0;
+ if (player.getMode().equals(GameMode.CREATIVE)) {
+ speed = player.getCapabilities().getFlySpeed();
+ } else {
+ speed = 0;
+ }
}
} else if (parameters.length == 2) {
if (Canary.getServer().getPlayer(parameters[1]) != null) {
// fly Player
player = Canary.getServer().getPlayer(parameters[1]);
if (!player.getCapabilities().mayFly()) {
speed = (float) 0.05;
} else {
speed = 0;
}
} else {
// fly Speed
player = (Player) caller;
try {
if (parameters[1].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[1]);
} catch (NumberFormatException e) {
String[] parts = new String[]{parameters[1]};
time = StringTime.millisecondsFromString(parts);
if (time != 0) {
speed = (float) 0.05;
caller.message(FontTools.RED + "Given Speed is NaN!");
}
}
}
} else {
if (Canary.getServer().getPlayer(parameters[1]) != null) {
player = Canary.getServer().getPlayer(parameters[1]);
try {
if (parameters[2].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[2]);
} catch (NumberFormatException e) {
//
}
} else {
player = (Player) caller;
try {
if (parameters[1].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[1]);
} catch (NumberFormatException e) {
//
}
}
boolean speeded = false;
try {
// fly Player Speed
if (parameters[2].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[2]);
speeded = true;
} catch (NumberFormatException e) {
speed = (float) 0.05;
// fly Player Time
// We know that it is only Time stuff left, or well we can hope
String[] parts = new String[parameters.length - 2];
int y = 0;
for (int i = 2; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
if (speeded) {
// fly Player Speed Time
String[] parts = new String[parameters.length - 3];
int y = 0;
for (int i = 3; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
}
} else {
player = Canary.getServer().getPlayer(parameters[1]);
if (parameters.length >= 3) {
boolean speeded = false;
try {
if (parameters[2].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[2]);
speeded = true;
} catch (NumberFormatException e) {
speed = (float) 0.05;
if (parameters.length != 4) {
caller.message(FontTools.RED + "Given Speed is NaN!");
} else {
// fly Player Time
// We know that it is only Time stuff left, or well we can hope
String[] parts = new String[parameters.length - 2];
int y = 0;
for (int i = 2; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
}
if (speeded) {
// fly Player Speed Time
String[] parts = new String[parameters.length - 3];
int y = 0;
for (int i = 3; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
}
}
if (player == null) {
caller.message(FontTools.RED + "Player not found!");
return;
}
if (caller != player) {
// Stop people from controlling and admin, but allow other admins to troll
if (player.isAdmin()) {
if (caller instanceof Server) {
// Yes server we fallow you!
} else if (caller instanceof CommandBlock) {
// Stop here admin is being let out
// TODO add way for admins to toggle this
return;
} else if (caller instanceof Player) {
if (!((Player) caller).isAdmin()) {
caller.message(FontTools.RED + "You can not affect an Admin!!!");
}
}
}
if (!PermissionsMan.allowFlyOther(caller)) {
caller.message(FontTools.RED + "You do not have Permission to allow others to fly!");
return;
}
}
if (!PermissionsMan.canFly(player)) {
String message = " not allowed to fly";
if (caller != player) {
if (caller instanceof Player) {
if (PermissionsMan.allowFlyOtherOverRide(caller)) {
caller.message(player.getName() + message + ", but you can still affect this player.");
} else {
caller.message(FontTools.RED + player.getName() + " is" + message);
return;
}
} else {
if (caller instanceof Server) {
caller.message(player.getName() + " may not fly! But Oh Mighty Server you may still affect this player.");
}
}
} else {
caller.message(FontTools.RED + "You are" + message);
return;
}
}
// Limit to at lest Maxspeed for Safety
if (speed > maxSpeed) {
speed = maxSpeed;
// No one is allowed over the max not even admins!
}
// Limit speed to the max the player can go.
float playerMaxSpeed = PermissionsMan.getMaxSpeedByCaller(player);
if (speed > playerMaxSpeed) {
if (!PermissionsMan.allowFlyOtherOverRide(caller)) {
if (caller instanceof Player) {
speed = playerMaxSpeed;
if (caller != player) {
caller.message(player.getName() + " can not fly that fast. Setting Speed to " + speed);
} else {
caller.message("You can not fly that fast. Setting Speed to " + speed);
}
}
// Need to limit speed to what the Caller can set
if (speed > PermissionsMan.getMaxSpeedByCaller(caller)) {
speed = PermissionsMan.getMaxSpeedByCaller(caller);
if (caller != player) {
caller.message("You can not let others fly that fast. Setting Speed to " + speed);
}
}
} else {
if (caller != player) {
caller.message("Please know that " + speed + " is faster then what this player is allowed, " + playerMaxSpeed + " is this player's max");
// Allow some people to have full power!
}
}
}
// SetUp Done
HumanCapabilities capabilities = player.getCapabilities();
if (!capabilities.mayFly()) {
if (speed == 0) {
// TODO add way for up/down flying?
return;
}
if (!player.getMode().equals(GameMode.CREATIVE)) {
// Starts flying if not Flying and not in Creative
capabilities.setMayFly(true);
capabilities.setFlying(true);
capabilities.setFlySpeed(speed);
player.updateCapabilities();
String message;
if (speed > 0.5) {
message = " may fly now, with the speed of " + FontTools.RED + capabilities.getFlySpeed();
} else {
message = " may fly now, with the speed of " + capabilities.getFlySpeed();
}
if (time > 0) {
message += FontTools.RESET + ", for " + time;
}
player.message("You" + message);
if (caller != player) {
caller.message(player.getName() + message);
}
FlyTime.addPlayerFor(player, time);
}
} else {
if (!player.getMode().equals(GameMode.CREATIVE) && speed == 0) {
capabilities.setFlying(false);
capabilities.setMayFly(false);
capabilities.setFlySpeed((float) 0.05);
player.updateCapabilities();
Location loc = player.getLocation();
loc.setY(player.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()) + 1);
player.teleportTo(loc, TeleportHook.TeleportCause.MOVEMENT);
String message = " may no longer fly.";
player.message("You" + message);
if (caller != player) {
caller.message(player.getName() + message);
}
FlyTime.removePlayer(player);
} else if (player.getMode().equals(GameMode.CREATIVE) || speed != 0) {
// Sets the Speed a Creative Player is flying at
if (speed == capabilities.getFlySpeed()) return;
capabilities.setFlySpeed(speed);
player.updateCapabilities();
String message;
if (speed > 0.5) {
message = " flight speed is now " + FontTools.RED + capabilities.getFlySpeed();
} else {
message = " flight speed is now " + capabilities.getFlySpeed();
}
player.message("Your" + message);
if (caller != player) {
player.message(player.getName() + message);
}
}
}
}
@Override
public CommandData getCommandData() {
return command;
}
@Override
public LocaleHelper getTranslator() {
return Translator.getInstance();
}
@Override
public boolean isForced() {
return false;
}
@Override
public boolean isloaded() {
return loaded;
}
@Override
public void setloadded(boolean loadedness) {
loaded = loadedness;
}
}
| true | true | public void execute(MessageReceiver caller, String[] parameters) {
if ((caller instanceof Server || caller instanceof CommandBlock) && parameters.length == 1) {
// Makes sure Server commands and CommandBlock commands at lest have one parameter
caller.message("Must Provide Player");
return;
}
Player player;
float speed = 0;
long time = 0;
if (caller instanceof Player) {
if (parameters.length == 1) {
// fly
player = (Player) caller;
if (!player.getCapabilities().mayFly()) {
speed = (float) 0.05;
} else {
speed = 0;
}
} else if (parameters.length == 2) {
if (Canary.getServer().getPlayer(parameters[1]) != null) {
// fly Player
player = Canary.getServer().getPlayer(parameters[1]);
if (!player.getCapabilities().mayFly()) {
speed = (float) 0.05;
} else {
speed = 0;
}
} else {
// fly Speed
player = (Player) caller;
try {
if (parameters[1].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[1]);
} catch (NumberFormatException e) {
String[] parts = new String[]{parameters[1]};
time = StringTime.millisecondsFromString(parts);
if (time != 0) {
speed = (float) 0.05;
caller.message(FontTools.RED + "Given Speed is NaN!");
}
}
}
} else {
if (Canary.getServer().getPlayer(parameters[1]) != null) {
player = Canary.getServer().getPlayer(parameters[1]);
try {
if (parameters[2].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[2]);
} catch (NumberFormatException e) {
//
}
} else {
player = (Player) caller;
try {
if (parameters[1].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[1]);
} catch (NumberFormatException e) {
//
}
}
boolean speeded = false;
try {
// fly Player Speed
if (parameters[2].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[2]);
speeded = true;
} catch (NumberFormatException e) {
speed = (float) 0.05;
// fly Player Time
// We know that it is only Time stuff left, or well we can hope
String[] parts = new String[parameters.length - 2];
int y = 0;
for (int i = 2; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
if (speeded) {
// fly Player Speed Time
String[] parts = new String[parameters.length - 3];
int y = 0;
for (int i = 3; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
}
} else {
player = Canary.getServer().getPlayer(parameters[1]);
if (parameters.length >= 3) {
boolean speeded = false;
try {
if (parameters[2].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[2]);
speeded = true;
} catch (NumberFormatException e) {
speed = (float) 0.05;
if (parameters.length != 4) {
caller.message(FontTools.RED + "Given Speed is NaN!");
} else {
// fly Player Time
// We know that it is only Time stuff left, or well we can hope
String[] parts = new String[parameters.length - 2];
int y = 0;
for (int i = 2; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
}
if (speeded) {
// fly Player Speed Time
String[] parts = new String[parameters.length - 3];
int y = 0;
for (int i = 3; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
}
}
if (player == null) {
caller.message(FontTools.RED + "Player not found!");
return;
}
if (caller != player) {
// Stop people from controlling and admin, but allow other admins to troll
if (player.isAdmin()) {
if (caller instanceof Server) {
// Yes server we fallow you!
} else if (caller instanceof CommandBlock) {
// Stop here admin is being let out
// TODO add way for admins to toggle this
return;
} else if (caller instanceof Player) {
if (!((Player) caller).isAdmin()) {
caller.message(FontTools.RED + "You can not affect an Admin!!!");
}
}
}
if (!PermissionsMan.allowFlyOther(caller)) {
caller.message(FontTools.RED + "You do not have Permission to allow others to fly!");
return;
}
}
if (!PermissionsMan.canFly(player)) {
String message = " not allowed to fly";
if (caller != player) {
if (caller instanceof Player) {
if (PermissionsMan.allowFlyOtherOverRide(caller)) {
caller.message(player.getName() + message + ", but you can still affect this player.");
} else {
caller.message(FontTools.RED + player.getName() + " is" + message);
return;
}
} else {
if (caller instanceof Server) {
caller.message(player.getName() + " may not fly! But Oh Mighty Server you may still affect this player.");
}
}
} else {
caller.message(FontTools.RED + "You are" + message);
return;
}
}
// Limit to at lest Maxspeed for Safety
if (speed > maxSpeed) {
speed = maxSpeed;
// No one is allowed over the max not even admins!
}
// Limit speed to the max the player can go.
float playerMaxSpeed = PermissionsMan.getMaxSpeedByCaller(player);
if (speed > playerMaxSpeed) {
if (!PermissionsMan.allowFlyOtherOverRide(caller)) {
if (caller instanceof Player) {
speed = playerMaxSpeed;
if (caller != player) {
caller.message(player.getName() + " can not fly that fast. Setting Speed to " + speed);
} else {
caller.message("You can not fly that fast. Setting Speed to " + speed);
}
}
// Need to limit speed to what the Caller can set
if (speed > PermissionsMan.getMaxSpeedByCaller(caller)) {
speed = PermissionsMan.getMaxSpeedByCaller(caller);
if (caller != player) {
caller.message("You can not let others fly that fast. Setting Speed to " + speed);
}
}
} else {
if (caller != player) {
caller.message("Please know that " + speed + " is faster then what this player is allowed, " + playerMaxSpeed + " is this player's max");
// Allow some people to have full power!
}
}
}
// SetUp Done
HumanCapabilities capabilities = player.getCapabilities();
if (!capabilities.mayFly()) {
if (speed == 0) {
// TODO add way for up/down flying?
return;
}
if (!player.getMode().equals(GameMode.CREATIVE)) {
// Starts flying if not Flying and not in Creative
capabilities.setMayFly(true);
capabilities.setFlying(true);
capabilities.setFlySpeed(speed);
player.updateCapabilities();
String message;
if (speed > 0.5) {
message = " may fly now, with the speed of " + FontTools.RED + capabilities.getFlySpeed();
} else {
message = " may fly now, with the speed of " + capabilities.getFlySpeed();
}
if (time > 0) {
message += FontTools.RESET + ", for " + time;
}
player.message("You" + message);
if (caller != player) {
caller.message(player.getName() + message);
}
FlyTime.addPlayerFor(player, time);
}
} else {
if (!player.getMode().equals(GameMode.CREATIVE) && speed == 0) {
capabilities.setFlying(false);
capabilities.setMayFly(false);
capabilities.setFlySpeed((float) 0.05);
player.updateCapabilities();
Location loc = player.getLocation();
loc.setY(player.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()) + 1);
player.teleportTo(loc, TeleportHook.TeleportCause.MOVEMENT);
String message = " may no longer fly.";
player.message("You" + message);
if (caller != player) {
caller.message(player.getName() + message);
}
FlyTime.removePlayer(player);
} else if (player.getMode().equals(GameMode.CREATIVE) || speed != 0) {
// Sets the Speed a Creative Player is flying at
if (speed == capabilities.getFlySpeed()) return;
capabilities.setFlySpeed(speed);
player.updateCapabilities();
String message;
if (speed > 0.5) {
message = " flight speed is now " + FontTools.RED + capabilities.getFlySpeed();
} else {
message = " flight speed is now " + capabilities.getFlySpeed();
}
player.message("Your" + message);
if (caller != player) {
player.message(player.getName() + message);
}
}
}
}
| public void execute(MessageReceiver caller, String[] parameters) {
if ((caller instanceof Server || caller instanceof CommandBlock) && parameters.length == 1) {
// Makes sure Server commands and CommandBlock commands at lest have one parameter
caller.message("Must Provide Player");
return;
}
Player player;
float speed = 0;
long time = 0;
if (caller instanceof Player) {
if (parameters.length == 1) {
// fly
player = (Player) caller;
if (!player.getCapabilities().mayFly()) {
speed = (float) 0.05;
} else {
if (player.getMode().equals(GameMode.CREATIVE)) {
speed = player.getCapabilities().getFlySpeed();
} else {
speed = 0;
}
}
} else if (parameters.length == 2) {
if (Canary.getServer().getPlayer(parameters[1]) != null) {
// fly Player
player = Canary.getServer().getPlayer(parameters[1]);
if (!player.getCapabilities().mayFly()) {
speed = (float) 0.05;
} else {
speed = 0;
}
} else {
// fly Speed
player = (Player) caller;
try {
if (parameters[1].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[1]);
} catch (NumberFormatException e) {
String[] parts = new String[]{parameters[1]};
time = StringTime.millisecondsFromString(parts);
if (time != 0) {
speed = (float) 0.05;
caller.message(FontTools.RED + "Given Speed is NaN!");
}
}
}
} else {
if (Canary.getServer().getPlayer(parameters[1]) != null) {
player = Canary.getServer().getPlayer(parameters[1]);
try {
if (parameters[2].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[2]);
} catch (NumberFormatException e) {
//
}
} else {
player = (Player) caller;
try {
if (parameters[1].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[1]);
} catch (NumberFormatException e) {
//
}
}
boolean speeded = false;
try {
// fly Player Speed
if (parameters[2].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[2]);
speeded = true;
} catch (NumberFormatException e) {
speed = (float) 0.05;
// fly Player Time
// We know that it is only Time stuff left, or well we can hope
String[] parts = new String[parameters.length - 2];
int y = 0;
for (int i = 2; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
if (speeded) {
// fly Player Speed Time
String[] parts = new String[parameters.length - 3];
int y = 0;
for (int i = 3; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
}
} else {
player = Canary.getServer().getPlayer(parameters[1]);
if (parameters.length >= 3) {
boolean speeded = false;
try {
if (parameters[2].toLowerCase().endsWith("D".toLowerCase())) {
throw new NumberFormatException();
}
speed = Float.parseFloat(parameters[2]);
speeded = true;
} catch (NumberFormatException e) {
speed = (float) 0.05;
if (parameters.length != 4) {
caller.message(FontTools.RED + "Given Speed is NaN!");
} else {
// fly Player Time
// We know that it is only Time stuff left, or well we can hope
String[] parts = new String[parameters.length - 2];
int y = 0;
for (int i = 2; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
}
if (speeded) {
// fly Player Speed Time
String[] parts = new String[parameters.length - 3];
int y = 0;
for (int i = 3; i <= parameters.length - 1; i++) {
parts[y++] = parameters[i];
}
time = StringTime.millisecondsFromString(parts);
}
}
}
if (player == null) {
caller.message(FontTools.RED + "Player not found!");
return;
}
if (caller != player) {
// Stop people from controlling and admin, but allow other admins to troll
if (player.isAdmin()) {
if (caller instanceof Server) {
// Yes server we fallow you!
} else if (caller instanceof CommandBlock) {
// Stop here admin is being let out
// TODO add way for admins to toggle this
return;
} else if (caller instanceof Player) {
if (!((Player) caller).isAdmin()) {
caller.message(FontTools.RED + "You can not affect an Admin!!!");
}
}
}
if (!PermissionsMan.allowFlyOther(caller)) {
caller.message(FontTools.RED + "You do not have Permission to allow others to fly!");
return;
}
}
if (!PermissionsMan.canFly(player)) {
String message = " not allowed to fly";
if (caller != player) {
if (caller instanceof Player) {
if (PermissionsMan.allowFlyOtherOverRide(caller)) {
caller.message(player.getName() + message + ", but you can still affect this player.");
} else {
caller.message(FontTools.RED + player.getName() + " is" + message);
return;
}
} else {
if (caller instanceof Server) {
caller.message(player.getName() + " may not fly! But Oh Mighty Server you may still affect this player.");
}
}
} else {
caller.message(FontTools.RED + "You are" + message);
return;
}
}
// Limit to at lest Maxspeed for Safety
if (speed > maxSpeed) {
speed = maxSpeed;
// No one is allowed over the max not even admins!
}
// Limit speed to the max the player can go.
float playerMaxSpeed = PermissionsMan.getMaxSpeedByCaller(player);
if (speed > playerMaxSpeed) {
if (!PermissionsMan.allowFlyOtherOverRide(caller)) {
if (caller instanceof Player) {
speed = playerMaxSpeed;
if (caller != player) {
caller.message(player.getName() + " can not fly that fast. Setting Speed to " + speed);
} else {
caller.message("You can not fly that fast. Setting Speed to " + speed);
}
}
// Need to limit speed to what the Caller can set
if (speed > PermissionsMan.getMaxSpeedByCaller(caller)) {
speed = PermissionsMan.getMaxSpeedByCaller(caller);
if (caller != player) {
caller.message("You can not let others fly that fast. Setting Speed to " + speed);
}
}
} else {
if (caller != player) {
caller.message("Please know that " + speed + " is faster then what this player is allowed, " + playerMaxSpeed + " is this player's max");
// Allow some people to have full power!
}
}
}
// SetUp Done
HumanCapabilities capabilities = player.getCapabilities();
if (!capabilities.mayFly()) {
if (speed == 0) {
// TODO add way for up/down flying?
return;
}
if (!player.getMode().equals(GameMode.CREATIVE)) {
// Starts flying if not Flying and not in Creative
capabilities.setMayFly(true);
capabilities.setFlying(true);
capabilities.setFlySpeed(speed);
player.updateCapabilities();
String message;
if (speed > 0.5) {
message = " may fly now, with the speed of " + FontTools.RED + capabilities.getFlySpeed();
} else {
message = " may fly now, with the speed of " + capabilities.getFlySpeed();
}
if (time > 0) {
message += FontTools.RESET + ", for " + time;
}
player.message("You" + message);
if (caller != player) {
caller.message(player.getName() + message);
}
FlyTime.addPlayerFor(player, time);
}
} else {
if (!player.getMode().equals(GameMode.CREATIVE) && speed == 0) {
capabilities.setFlying(false);
capabilities.setMayFly(false);
capabilities.setFlySpeed((float) 0.05);
player.updateCapabilities();
Location loc = player.getLocation();
loc.setY(player.getWorld().getHighestBlockAt(loc.getBlockX(), loc.getBlockZ()) + 1);
player.teleportTo(loc, TeleportHook.TeleportCause.MOVEMENT);
String message = " may no longer fly.";
player.message("You" + message);
if (caller != player) {
caller.message(player.getName() + message);
}
FlyTime.removePlayer(player);
} else if (player.getMode().equals(GameMode.CREATIVE) || speed != 0) {
// Sets the Speed a Creative Player is flying at
if (speed == capabilities.getFlySpeed()) return;
capabilities.setFlySpeed(speed);
player.updateCapabilities();
String message;
if (speed > 0.5) {
message = " flight speed is now " + FontTools.RED + capabilities.getFlySpeed();
} else {
message = " flight speed is now " + capabilities.getFlySpeed();
}
player.message("Your" + message);
if (caller != player) {
player.message(player.getName() + message);
}
}
}
}
|
diff --git a/servicemix-common/src/main/java/org/apache/servicemix/common/ManagementSupport.java b/servicemix-common/src/main/java/org/apache/servicemix/common/ManagementSupport.java
index 1aed42cba..e8d64c36d 100644
--- a/servicemix-common/src/main/java/org/apache/servicemix/common/ManagementSupport.java
+++ b/servicemix-common/src/main/java/org/apache/servicemix/common/ManagementSupport.java
@@ -1,169 +1,169 @@
/*
* Copyright 2005-2006 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.servicemix.common;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* ManagementMessageHelper is a class that ease the building of management messages.
*/
public class ManagementSupport {
private static final Log logger = LogFactory.getLog(ManagementSupport.class);
public static class Message {
private String task;
private String component;
private String result;
private Exception exception;
private String type;
private String message;
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public Exception getException() {
return exception;
}
public void setException(Exception exception) {
this.exception = exception;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public static String createComponentMessage(Message msg) {
try {
StringBuffer sw = new StringBuffer();
// component-task-result
sw.append("<component-task-result ");
- sw.append("xmlns=\"http://java.sun.com/xml/ns/jbi/management-message\"");
+ sw.append("xmlns=\"http://java.sun.com/xml/ns/jbi/management-message\">");
sw.append("\n\t");
// component-name
sw.append("<component-name>");
sw.append(msg.getComponent());
sw.append("</component-name>");
// component-task-result-details
sw.append("\n\t");
sw.append("<component-task-result-details>");
// task-result-details
sw.append("\n\t\t");
sw.append("<task-result-details>");
// task-id
sw.append("\n\t\t\t");
sw.append("<task-id>");
sw.append(msg.getTask());
sw.append("</task-id>");
// task-result
sw.append("\n\t\t\t");
sw.append("<task-result>");
sw.append(msg.getResult());
sw.append("</task-result>");
// message-type
if (msg.getType() != null) {
sw.append("\n\t\t\t");
sw.append("<message-type>");
sw.append(msg.getType());
sw.append("</message-type>");
}
// task-status-message
if (msg.getMessage() != null) {
sw.append("\n\t\t\t");
sw.append("<task-status-message>");
sw.append("<msg-loc-info>");
sw.append("<loc-token/>");
sw.append("<loc-message>");
sw.append(msg.getMessage());
sw.append("</loc-message>");
sw.append("</msg-loc-info>");
sw.append("</task-status-message>");
}
// exception-info
if (msg.getException() != null) {
sw.append("\n\t\t\t");
sw.append("<exception-info>");
sw.append("\n\t\t\t\t");
sw.append("<nesting-level>1</nesting-level>");
sw.append("\n\t\t\t\t");
sw.append("<msg-loc-info>");
sw.append("\n\t\t\t\t\t");
sw.append("<loc-token />");
sw.append("\n\t\t\t\t\t");
sw.append("<loc-message>");
sw.append(msg.getException().getMessage());
sw.append("</loc-message>");
sw.append("\n\t\t\t\t\t");
sw.append("<stack-trace>");
StringWriter sw2 = new StringWriter();
PrintWriter pw = new PrintWriter(sw2);
msg.getException().printStackTrace(pw);
pw.close();
sw.append("<[CDATA[");
sw.append(sw2.toString());
sw.append("]]>");
sw.append("</stack-trace>");
sw.append("\n\t\t\t\t");
sw.append("</msg-loc-info>");
sw.append("\n\t\t\t");
sw.append("</exception-info>");
}
// end: task-result-details
sw.append("\n\t\t");
sw.append("</task-result-details>");
// end: component-task-result-details
sw.append("\n\t");
sw.append("</component-task-result-details>");
// end: component-task-result
sw.append("\n");
sw.append("</component-task-result>");
// return result
return sw.toString();
} catch (Exception e) {
logger.warn("Error generating component management message", e);
return null;
}
}
}
| true | true | public static String createComponentMessage(Message msg) {
try {
StringBuffer sw = new StringBuffer();
// component-task-result
sw.append("<component-task-result ");
sw.append("xmlns=\"http://java.sun.com/xml/ns/jbi/management-message\"");
sw.append("\n\t");
// component-name
sw.append("<component-name>");
sw.append(msg.getComponent());
sw.append("</component-name>");
// component-task-result-details
sw.append("\n\t");
sw.append("<component-task-result-details>");
// task-result-details
sw.append("\n\t\t");
sw.append("<task-result-details>");
// task-id
sw.append("\n\t\t\t");
sw.append("<task-id>");
sw.append(msg.getTask());
sw.append("</task-id>");
// task-result
sw.append("\n\t\t\t");
sw.append("<task-result>");
sw.append(msg.getResult());
sw.append("</task-result>");
// message-type
if (msg.getType() != null) {
sw.append("\n\t\t\t");
sw.append("<message-type>");
sw.append(msg.getType());
sw.append("</message-type>");
}
// task-status-message
if (msg.getMessage() != null) {
sw.append("\n\t\t\t");
sw.append("<task-status-message>");
sw.append("<msg-loc-info>");
sw.append("<loc-token/>");
sw.append("<loc-message>");
sw.append(msg.getMessage());
sw.append("</loc-message>");
sw.append("</msg-loc-info>");
sw.append("</task-status-message>");
}
// exception-info
if (msg.getException() != null) {
sw.append("\n\t\t\t");
sw.append("<exception-info>");
sw.append("\n\t\t\t\t");
sw.append("<nesting-level>1</nesting-level>");
sw.append("\n\t\t\t\t");
sw.append("<msg-loc-info>");
sw.append("\n\t\t\t\t\t");
sw.append("<loc-token />");
sw.append("\n\t\t\t\t\t");
sw.append("<loc-message>");
sw.append(msg.getException().getMessage());
sw.append("</loc-message>");
sw.append("\n\t\t\t\t\t");
sw.append("<stack-trace>");
StringWriter sw2 = new StringWriter();
PrintWriter pw = new PrintWriter(sw2);
msg.getException().printStackTrace(pw);
pw.close();
sw.append("<[CDATA[");
sw.append(sw2.toString());
sw.append("]]>");
sw.append("</stack-trace>");
sw.append("\n\t\t\t\t");
sw.append("</msg-loc-info>");
sw.append("\n\t\t\t");
sw.append("</exception-info>");
}
// end: task-result-details
sw.append("\n\t\t");
sw.append("</task-result-details>");
// end: component-task-result-details
sw.append("\n\t");
sw.append("</component-task-result-details>");
// end: component-task-result
sw.append("\n");
sw.append("</component-task-result>");
// return result
return sw.toString();
} catch (Exception e) {
logger.warn("Error generating component management message", e);
return null;
}
}
| public static String createComponentMessage(Message msg) {
try {
StringBuffer sw = new StringBuffer();
// component-task-result
sw.append("<component-task-result ");
sw.append("xmlns=\"http://java.sun.com/xml/ns/jbi/management-message\">");
sw.append("\n\t");
// component-name
sw.append("<component-name>");
sw.append(msg.getComponent());
sw.append("</component-name>");
// component-task-result-details
sw.append("\n\t");
sw.append("<component-task-result-details>");
// task-result-details
sw.append("\n\t\t");
sw.append("<task-result-details>");
// task-id
sw.append("\n\t\t\t");
sw.append("<task-id>");
sw.append(msg.getTask());
sw.append("</task-id>");
// task-result
sw.append("\n\t\t\t");
sw.append("<task-result>");
sw.append(msg.getResult());
sw.append("</task-result>");
// message-type
if (msg.getType() != null) {
sw.append("\n\t\t\t");
sw.append("<message-type>");
sw.append(msg.getType());
sw.append("</message-type>");
}
// task-status-message
if (msg.getMessage() != null) {
sw.append("\n\t\t\t");
sw.append("<task-status-message>");
sw.append("<msg-loc-info>");
sw.append("<loc-token/>");
sw.append("<loc-message>");
sw.append(msg.getMessage());
sw.append("</loc-message>");
sw.append("</msg-loc-info>");
sw.append("</task-status-message>");
}
// exception-info
if (msg.getException() != null) {
sw.append("\n\t\t\t");
sw.append("<exception-info>");
sw.append("\n\t\t\t\t");
sw.append("<nesting-level>1</nesting-level>");
sw.append("\n\t\t\t\t");
sw.append("<msg-loc-info>");
sw.append("\n\t\t\t\t\t");
sw.append("<loc-token />");
sw.append("\n\t\t\t\t\t");
sw.append("<loc-message>");
sw.append(msg.getException().getMessage());
sw.append("</loc-message>");
sw.append("\n\t\t\t\t\t");
sw.append("<stack-trace>");
StringWriter sw2 = new StringWriter();
PrintWriter pw = new PrintWriter(sw2);
msg.getException().printStackTrace(pw);
pw.close();
sw.append("<[CDATA[");
sw.append(sw2.toString());
sw.append("]]>");
sw.append("</stack-trace>");
sw.append("\n\t\t\t\t");
sw.append("</msg-loc-info>");
sw.append("\n\t\t\t");
sw.append("</exception-info>");
}
// end: task-result-details
sw.append("\n\t\t");
sw.append("</task-result-details>");
// end: component-task-result-details
sw.append("\n\t");
sw.append("</component-task-result-details>");
// end: component-task-result
sw.append("\n");
sw.append("</component-task-result>");
// return result
return sw.toString();
} catch (Exception e) {
logger.warn("Error generating component management message", e);
return null;
}
}
|
diff --git a/src/main/java/com/finance/controller/FinanceStatsController.java b/src/main/java/com/finance/controller/FinanceStatsController.java
index 318338c..9b1ae23 100644
--- a/src/main/java/com/finance/controller/FinanceStatsController.java
+++ b/src/main/java/com/finance/controller/FinanceStatsController.java
@@ -1,191 +1,191 @@
package com.finance.controller;
import com.common.Util;
import com.finance.dao.EntryDao;
import com.finance.model.EntryCommand;
import com.highchart.AxisData;
import com.highchart.GraphData;
import com.highchart.PieData;
import com.highchart.Series;
import com.security.MyUserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
/**
* User: jitse
* Date: 8/4/13
* Time: 3:26 PM
*/
@Controller
@RequestMapping("/finance/stats")
public class FinanceStatsController {
@Autowired
EntryDao entryDao;
@Autowired
private MyUserContext myUserContext;
@RequestMapping(method = RequestMethod.GET)
public @ResponseBody
ModelAndView stats () {
return new ModelAndView("finance/stats");
}
@RequestMapping(value="expenseByPayee", method = RequestMethod.GET)
public @ResponseBody
PieData expenseByPayee () {
- List<EntryCommand> entries = entryDao.getEntriesByUserIdSortByDate(myUserContext.getCurrentUser().getId());
+ List<EntryCommand> entries = entryDao.getEntriesByUserId(myUserContext.getCurrentUser().getId());
List<List<Object>> pieData = new ArrayList<List<Object>>();
//the data is assumed to be sorted by payee.
String payee = entries.get(0).getPayee().getName();
double grandTotal = 0;
double runningSum = 0;
for (EntryCommand entry : entries) {
if (entry.getPayee().getName().equals(payee)) {
runningSum += Double.parseDouble(entry.getAmount());
} else {
//save the data from the previous payee;
List<Object> series = new ArrayList<Object>();
series.add(payee);
series.add(new Double(runningSum).intValue());
pieData.add(series);
//initializing a new payee
grandTotal += runningSum;
runningSum = Double.parseDouble(entry.getAmount());
payee = entry.getPayee().getName();
}
}
grandTotal += runningSum;
//add the last batch onto the list
List<Object> series = new ArrayList<Object>();
series.add(payee);
series.add(new Double(runningSum).intValue());
pieData.add(series);
PieData rval = new PieData();
rval.setData(pieData);
rval.setName("Amount Spent");
rval.setTitle("Total Amount Spent: $" + grandTotal);
return rval;
}
@RequestMapping(value="monthlyExpense", method = RequestMethod.GET)
public @ResponseBody
GraphData monthlyExpense () {
List<EntryCommand> entries = entryDao.getEntriesByUserIdSortByDate(myUserContext.getCurrentUser().getId());
if (entries == null || entries.isEmpty()) {
return new GraphData();
}
List<String> monthList = getMonthList(entries);
AxisData axisData = new AxisData();
axisData.setData(monthList);
Series series = new Series();
series.setName("Monthly Expense");
series.setMyData(getMonthlyTotal(entries));
List<Series> seriesList = new ArrayList<Series>();
seriesList.add(series);
GraphData data = new GraphData();
data.setyTitle("Amount Spent");
data.setxAxis(axisData);
data.setSeries(seriesList);
data.setChartTitle("Monthly Expenses");
data.setPieData(getPieDataSeries(entries));
return data;
}
private PieData getPieDataSeries(List<EntryCommand> entries) {
PieData rval = new PieData();
double runningSum = 0.0;
for (EntryCommand entry : entries) {
runningSum += Double.parseDouble(entry.getAmount());
}
List<List<Object>> data = new ArrayList<List<Object>>();
List<Object> series1 = new ArrayList<Object>();
series1.add("Total Expense");
series1.add(new Double(runningSum).intValue());
data.add(series1);
rval.setData(data);
rval.setName("");
rval.setTitle("");
return rval;
}
private List<Integer> getMonthlyTotal(List<EntryCommand> entries) {
List<Integer> rval = new ArrayList<Integer>();
//the data is assumed to be sorted by date.
int curMonth = entries.get(0).getDate().getMonth();
double runningSum = 0;
for (EntryCommand entry : entries) {
if (entry.getDate().getMonth() == curMonth) {
runningSum += Double.parseDouble(entry.getAmount());
} else {
//save the data from the previous month
rval.add(new Double(runningSum).intValue());
//if there are gaps in months between games, we want to fill that with 0s
curMonth++;
while (curMonth != entry.getDate().getMonth()) {
rval.add(0);
curMonth++;
if (curMonth > 15) {
throw new RuntimeException("Something went wrong, terminating to save itself");
}
}
//initializing a new month
runningSum = Double.parseDouble(entry.getAmount());
}
}
//add the last batch onto the list
rval.add(new Double(runningSum).intValue());
return rval;
}
private List<String> getMonthList(List<EntryCommand> entries) {
int minMonth = 15;
int maxMonth = -1;
for (EntryCommand entry : entries) {
if (entry.getDate().getMonth() < minMonth) {
minMonth = entry.getDate().getMonth();
}
if (entry.getDate().getMonth() > maxMonth) {
maxMonth = entry.getDate().getMonth();
}
}
return Util.getMonthList(minMonth, maxMonth);
}
}
| true | true | PieData expenseByPayee () {
List<EntryCommand> entries = entryDao.getEntriesByUserIdSortByDate(myUserContext.getCurrentUser().getId());
List<List<Object>> pieData = new ArrayList<List<Object>>();
//the data is assumed to be sorted by payee.
String payee = entries.get(0).getPayee().getName();
double grandTotal = 0;
double runningSum = 0;
for (EntryCommand entry : entries) {
if (entry.getPayee().getName().equals(payee)) {
runningSum += Double.parseDouble(entry.getAmount());
} else {
//save the data from the previous payee;
List<Object> series = new ArrayList<Object>();
series.add(payee);
series.add(new Double(runningSum).intValue());
pieData.add(series);
//initializing a new payee
grandTotal += runningSum;
runningSum = Double.parseDouble(entry.getAmount());
payee = entry.getPayee().getName();
}
}
grandTotal += runningSum;
//add the last batch onto the list
List<Object> series = new ArrayList<Object>();
series.add(payee);
series.add(new Double(runningSum).intValue());
pieData.add(series);
PieData rval = new PieData();
rval.setData(pieData);
rval.setName("Amount Spent");
rval.setTitle("Total Amount Spent: $" + grandTotal);
return rval;
}
| PieData expenseByPayee () {
List<EntryCommand> entries = entryDao.getEntriesByUserId(myUserContext.getCurrentUser().getId());
List<List<Object>> pieData = new ArrayList<List<Object>>();
//the data is assumed to be sorted by payee.
String payee = entries.get(0).getPayee().getName();
double grandTotal = 0;
double runningSum = 0;
for (EntryCommand entry : entries) {
if (entry.getPayee().getName().equals(payee)) {
runningSum += Double.parseDouble(entry.getAmount());
} else {
//save the data from the previous payee;
List<Object> series = new ArrayList<Object>();
series.add(payee);
series.add(new Double(runningSum).intValue());
pieData.add(series);
//initializing a new payee
grandTotal += runningSum;
runningSum = Double.parseDouble(entry.getAmount());
payee = entry.getPayee().getName();
}
}
grandTotal += runningSum;
//add the last batch onto the list
List<Object> series = new ArrayList<Object>();
series.add(payee);
series.add(new Double(runningSum).intValue());
pieData.add(series);
PieData rval = new PieData();
rval.setData(pieData);
rval.setName("Amount Spent");
rval.setTitle("Total Amount Spent: $" + grandTotal);
return rval;
}
|
diff --git a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ExtensionsRegistry.java b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ExtensionsRegistry.java
index c4d18d4de..a39da5226 100644
--- a/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ExtensionsRegistry.java
+++ b/org.eclipse.core.filebuffers/src/org/eclipse/core/internal/filebuffers/ExtensionsRegistry.java
@@ -1,556 +1,556 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.internal.filebuffers;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionPoint;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.core.runtime.content.IContentTypeManager;
import org.eclipse.core.filebuffers.FileBuffers;
import org.eclipse.core.filebuffers.IAnnotationModelFactory;
import org.eclipse.core.filebuffers.IDocumentFactory;
import org.eclipse.core.filebuffers.IDocumentSetupParticipant;
import org.eclipse.jface.text.Assert;
/**
* This registry manages sharable document factories. Document factories are specified
* in <code>plugin.xml</code> per file name extension.
*/
public class ExtensionsRegistry {
/**
* Adapts IContentType with the ability to check
* equality. This allows to use them in a collection.
*/
private static class ContentTypeAdapter {
/** The adapted content type. */
private IContentType fContentType;
/**
* Creates a new content type adapter for the
* given content type.
*
* @param contentType the content type to be adapted
*/
public ContentTypeAdapter(IContentType contentType) {
Assert.isNotNull(contentType);
fContentType= contentType;
}
/**
* Return the adapted content type.
*
* @return the content type
*/
public IContentType getContentType() {
return fContentType;
}
/**
* Return the Id of the adapted content type.
*
* @return the Id
*/
public String getId() {
return fContentType.getId();
}
/*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj) {
return obj instanceof ContentTypeAdapter && fContentType.getId().equals(((ContentTypeAdapter)obj).getId());
}
/*
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
return fContentType.getId().hashCode();
}
}
private final static String WILDCARD= "*"; //$NON-NLS-1$
/** The mapping between file attributes and configuration elements describing document factories. */
private Map fFactoryDescriptors= new HashMap();
/** The mapping between configuration elements for document factories and instantiated document factories. */
private Map fFactories= new HashMap();
/** The mapping between file attributes and configuration elements describing document setup participants. */
private Map fSetupParticipantDescriptors= new HashMap();
/** The mapping between configuration elements for setup participants and instantiated setup participants. */
private Map fSetupParticipants= new HashMap();
/** The mapping between file attributes and configuration elements describing annotation model factories. */
private Map fAnnotationModelFactoryDescriptors= new HashMap();
/** The mapping between configuration elements for annotation model factories */
private Map fAnnotationModelFactories= new HashMap();
/** The content type manager. */
private IContentTypeManager fContentTypeManager= Platform.getContentTypeManager();
/**
* Creates a new document factory registry and initializes it with the information
* found in the plug-in registry.
*/
public ExtensionsRegistry() {
initialize("documentCreation", "contentTypeId", true, fFactoryDescriptors); //$NON-NLS-1$ //$NON-NLS-2$
initialize("documentCreation", "fileNames", false, fFactoryDescriptors); //$NON-NLS-1$ //$NON-NLS-2$
initialize("documentCreation", "extensions", false, fFactoryDescriptors); //$NON-NLS-1$ //$NON-NLS-2$
initialize("documentSetup", "contentTypeId", true, fSetupParticipantDescriptors); //$NON-NLS-1$ //$NON-NLS-2$
initialize("documentSetup", "fileNames", false, fSetupParticipantDescriptors); //$NON-NLS-1$ //$NON-NLS-2$
initialize("documentSetup", "extensions", false, fSetupParticipantDescriptors); //$NON-NLS-1$ //$NON-NLS-2$
initialize("annotationModelCreation", "contentTypeId", true, fAnnotationModelFactoryDescriptors); //$NON-NLS-1$ //$NON-NLS-2$
initialize("annotationModelCreation", "fileNames", false, fAnnotationModelFactoryDescriptors); //$NON-NLS-1$ //$NON-NLS-2$
initialize("annotationModelCreation", "extensions", false, fAnnotationModelFactoryDescriptors); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* Reads the comma-separated value from the given configuration element for the given attribute name and remembers
* the configuration element in the given map under the individual tokens of the attribute value.
*
* @param attributeName the name of the attribute
* @param element the configuration element
* @param map the map which remembers the configuration element
*/
private void read(String attributeName, IConfigurationElement element, Map map) {
String value= element.getAttribute(attributeName);
if (value != null) {
StringTokenizer tokenizer= new StringTokenizer(value, ","); //$NON-NLS-1$
while (tokenizer.hasMoreTokens()) {
String token= tokenizer.nextToken().trim();
Set s= (Set) map.get(token);
if (s == null) {
s= new HashSet();
map.put(token, s);
}
s.add(element);
}
}
}
/**
* Reads the value from the given configuration element for the given attribute name and remembers
* the configuration element in the given map under the individual content type of the attribute value.
*
* @param attributeName the name of the attribute
* @param element the configuration element
* @param map the map which remembers the configuration element
*/
private void readContentType(String attributeName, IConfigurationElement element, Map map) {
String value= element.getAttribute(attributeName);
if (value != null) {
IContentType contentType= fContentTypeManager.getContentType(value);
if (contentType == null) {
log(new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, 0, NLSUtility.format(FileBuffersMessages.ExtensionsRegistry_error_contentTypeDoesNotExist, new Object[] { value }), null));
return;
}
ContentTypeAdapter adapter= new ContentTypeAdapter(contentType);
Set s= (Set) map.get(adapter);
if (s == null) {
s= new HashSet();
map.put(adapter, s);
}
s.add(element);
}
}
/**
* Adds an entry to the log of this plug-in for the given status
* @param status the status to log
*/
private void log(IStatus status) {
ILog log= FileBuffersPlugin.getDefault().getLog();
log.log(status);
}
/**
* Initializes this registry. It retrieves all implementers of the given
* extension point and remembers those implementers based on the
* file name extensions in the given map.
*
* @param extensionPointName the name of the extension point
* @param childElementName the name of the child elements
* @param isContentTypeId the child element is a content type id
* @param descriptors the map to be filled
*/
private void initialize(String extensionPointName, String childElementName, boolean isContentTypeId, Map descriptors) {
IExtensionPoint extensionPoint= Platform.getExtensionRegistry().getExtensionPoint(FileBuffersPlugin.PLUGIN_ID, extensionPointName);
if (extensionPoint == null) {
log(new Status(IStatus.ERROR, FileBuffersPlugin.PLUGIN_ID, 0, NLSUtility.format(FileBuffersMessages.ExtensionsRegistry_error_extensionPointNotFound, new Object[] { extensionPointName}), null));
return;
}
IConfigurationElement[] elements= extensionPoint.getConfigurationElements();
for (int i= 0; i < elements.length; i++) {
if (isContentTypeId)
readContentType(childElementName, elements[i], descriptors);
else
read(childElementName, elements[i], descriptors);
}
}
/**
* Returns the executable extension for the given configuration element.
* If there is no instantiated extension remembered for this
* element, a new extension is created and put into the cache if it is of the requested type.
*
* @param entry the configuration element
* @param extensions the map of instantiated extensions
* @param extensionType the requested result type
* @return the executable extension for the given configuration element.
*/
private Object getExtension(IConfigurationElement entry, Map extensions, Class extensionType) {
Object extension= extensions.get(entry);
if (extension != null)
return extension;
try {
extension= entry.createExecutableExtension("class"); //$NON-NLS-1$
} catch (CoreException x) {
log(x.getStatus());
}
if (extensionType.isInstance(extension)) {
extensions.put(entry, extension);
return extension;
}
return null;
}
/**
* Returns the first enumerated element of the given set.
*
* @param set the set from which to choose
* @return the selected configuration element
*/
private IConfigurationElement selectConfigurationElement(Set set) {
if (set != null && !set.isEmpty()) {
Iterator e= set.iterator();
return (IConfigurationElement) e.next();
}
return null;
}
/**
* Returns a sharable document factory for the given file name or file extension.
*
* @param nameOrExtension the name or extension to be used for lookup
* @return the sharable document factory or <code>null</code>
*/
private IDocumentFactory getDocumentFactory(String nameOrExtension) {
Set set= (Set) fFactoryDescriptors.get(nameOrExtension);
if (set != null) {
IConfigurationElement entry= selectConfigurationElement(set);
return (IDocumentFactory) getExtension(entry, fFactories, IDocumentFactory.class);
}
return null;
}
/**
* Returns a sharable document factory for the given content types.
*
* @param contentTypes the content types used to find the factory
* @return the sharable document factory or <code>null</code>
*/
private IDocumentFactory doGetDocumentFactory(IContentType[] contentTypes) {
Set set= null;
int i= 0;
while (i < contentTypes.length && set == null) {
set= (Set) fFactoryDescriptors.get(new ContentTypeAdapter(contentTypes[i++]));
}
if (set != null) {
IConfigurationElement entry= selectConfigurationElement(set);
return (IDocumentFactory) getExtension(entry, fFactories, IDocumentFactory.class);
}
return null;
}
/**
* Returns a sharable document factory for the given content types. This
* method considers the base content types of the given set of content
* types.
*
* @param contentTypes the content types used to find the factory
* @return the sharable document factory or <code>null</code>
*/
private IDocumentFactory getDocumentFactory(IContentType[] contentTypes) {
IDocumentFactory factory= doGetDocumentFactory(contentTypes);
while (factory == null) {
contentTypes= computeBaseContentTypes(contentTypes);
if (contentTypes == null)
break;
factory= doGetDocumentFactory(contentTypes);
}
return factory;
}
/**
* Returns the set of setup participants for the given file name or extension.
*
* @param nameOrExtension the name or extension to be used for lookup
* @return the sharable set of document setup participants
*/
private List getDocumentSetupParticipants(String nameOrExtension) {
Set set= (Set) fSetupParticipantDescriptors.get(nameOrExtension);
if (set == null)
return null;
List participants= new ArrayList();
Iterator e= set.iterator();
while (e.hasNext()) {
IConfigurationElement entry= (IConfigurationElement) e.next();
Object participant= getExtension(entry, fSetupParticipants, IDocumentSetupParticipant.class);
if (participant != null)
participants.add(participant);
}
return participants;
}
/**
* Returns the set of setup participants for the given content types.
*
* @param contentTypes the contentTypes to be used for lookup
* @return the sharable set of document setup participants
*/
private List doGetDocumentSetupParticipants(IContentType[] contentTypes) {
Set resultSet= new HashSet();
int i= 0;
while (i < contentTypes.length) {
Set set= (Set) fSetupParticipantDescriptors.get(new ContentTypeAdapter(contentTypes[i++]));
if (set != null)
resultSet.addAll(set);
}
List participants= new ArrayList();
Iterator e= resultSet.iterator();
while (e.hasNext()) {
IConfigurationElement entry= (IConfigurationElement) e.next();
Object participant= getExtension(entry, fSetupParticipants, IDocumentSetupParticipant.class);
if (participant != null)
participants.add(participant);
}
return participants.isEmpty() ? null : participants;
}
/**
* Returns the set of setup participants for the given content types. This
* method considers the base content types of the given set of content
* types.
*
* @param contentTypes the contentTypes to be used for lookup
* @return the sharable set of document setup participants
*/
private List getDocumentSetupParticipants(IContentType[] contentTypes) {
List participants= doGetDocumentSetupParticipants(contentTypes);
while (participants == null) {
contentTypes= computeBaseContentTypes(contentTypes);
if (contentTypes == null)
break;
participants= doGetDocumentSetupParticipants(contentTypes);
}
return participants;
}
/**
* Returns a sharable annotation model factory for the given content types.
*
* @param contentTypes the content types used to find the factory
* @return the sharable annotation model factory or <code>null</code>
*/
private IAnnotationModelFactory doGetAnnotationModelFactory(IContentType[] contentTypes) {
Set set= null;
int i= 0;
while (i < contentTypes.length && set == null) {
set= (Set) fAnnotationModelFactoryDescriptors.get(new ContentTypeAdapter(contentTypes[i++]));
}
if (set != null) {
IConfigurationElement entry= selectConfigurationElement(set);
return (IAnnotationModelFactory) getExtension(entry, fAnnotationModelFactories, IAnnotationModelFactory.class);
}
return null;
}
/**
* Returns a sharable annotation model factory for the given content types.
* This method considers the base content types of the given set of content
* types.
*
* @param contentTypes the content types used to find the factory
* @return the sharable annotation model factory or <code>null</code>
*/
private IAnnotationModelFactory getAnnotationModelFactory(IContentType[] contentTypes) {
IAnnotationModelFactory factory= doGetAnnotationModelFactory(contentTypes);
while (factory == null) {
contentTypes= computeBaseContentTypes(contentTypes);
if (contentTypes == null)
break;
factory= doGetAnnotationModelFactory(contentTypes);
}
return factory;
}
/**
* Returns a sharable annotation model factory for the given file name or file extension.
*
* @param extension the name or extension to be used for lookup
* @return the sharable document factory or <code>null</code>
*/
private IAnnotationModelFactory getAnnotationModelFactory(String extension) {
Set set= (Set) fAnnotationModelFactoryDescriptors.get(extension);
if (set != null) {
IConfigurationElement entry= selectConfigurationElement(set);
return (IAnnotationModelFactory) getExtension(entry, fAnnotationModelFactories, IAnnotationModelFactory.class);
}
return null;
}
/**
* Returns the set of content types for the given location.
*
* @param location the location for which to look up the content types
* @return the set of content types for the location
*/
private IContentType[] findContentTypes(IPath location) {
IFile file= FileBuffers.getWorkspaceFileAtLocation(location);
if (file != null) {
try {
IContentDescription contentDescription= file.getContentDescription();
if (contentDescription != null) {
IContentType contentType= contentDescription.getContentType();
if (contentType != null)
return new IContentType[] {contentType};
}
} catch (CoreException x) {
// go for the default
}
}
return fContentTypeManager.findContentTypesFor(location.lastSegment());
}
/**
* Returns the set of direct base content types for the given set of content
* types. Returns <code>null</code> if non of the given content types has
* a direct base content type.
*
* @param contentTypes the content types
* @return the set of direct base content types
*/
private IContentType[] computeBaseContentTypes(IContentType[] contentTypes) {
List baseTypes= new ArrayList();
for (int i= 0; i < contentTypes.length; i++) {
IContentType baseType= contentTypes[i].getBaseType();
if (baseType != null)
baseTypes.add(baseType);
}
IContentType[] result= null;
int size= baseTypes.size();
if (size > 0) {
result= new IContentType[size];
baseTypes.toArray(result);
}
return result;
}
/**
* Returns the sharable document factory for the given location.
*
* @param location the location for which to looked up the factory
* @return the sharable document factory
*/
public IDocumentFactory getDocumentFactory(IPath location) {
IDocumentFactory factory= getDocumentFactory(findContentTypes(location));
if (factory == null)
factory= getDocumentFactory(location.lastSegment());
if (factory == null)
factory= getDocumentFactory(location.getFileExtension());
if (factory == null)
factory= getDocumentFactory(WILDCARD);
return factory;
}
/**
* Returns the sharable set of document setup participants for the given location.
*
* @param location the location for which to look up the setup participants
* @return the sharable set of document setup participants
*/
public IDocumentSetupParticipant[] getDocumentSetupParticipants(IPath location) {
- List participants= new ArrayList();
+ Set participants= new HashSet();
List p= getDocumentSetupParticipants(findContentTypes(location));
if (p != null)
participants.addAll(p);
p= getDocumentSetupParticipants(location.lastSegment());
if (p != null)
participants.addAll(p);
p= getDocumentSetupParticipants(location.getFileExtension());
if (p != null)
participants.addAll(p);
p= getDocumentSetupParticipants(WILDCARD);
if (p != null)
participants.addAll(p);
IDocumentSetupParticipant[] result= new IDocumentSetupParticipant[participants.size()];
participants.toArray(result);
return result;
}
/**
* Returns the sharable annotation model factory for the given location.
*
* @param location the location for which to look up the factory
* @return the sharable annotation model factory
*/
public IAnnotationModelFactory getAnnotationModelFactory(IPath location) {
IAnnotationModelFactory factory= getAnnotationModelFactory(findContentTypes(location));
if (factory == null)
factory= getAnnotationModelFactory(location.lastSegment());
if (factory == null)
factory= getAnnotationModelFactory(location.getFileExtension());
if (factory == null)
factory= getAnnotationModelFactory(WILDCARD);
return factory;
}
}
| true | true | public IDocumentSetupParticipant[] getDocumentSetupParticipants(IPath location) {
List participants= new ArrayList();
List p= getDocumentSetupParticipants(findContentTypes(location));
if (p != null)
participants.addAll(p);
p= getDocumentSetupParticipants(location.lastSegment());
if (p != null)
participants.addAll(p);
p= getDocumentSetupParticipants(location.getFileExtension());
if (p != null)
participants.addAll(p);
p= getDocumentSetupParticipants(WILDCARD);
if (p != null)
participants.addAll(p);
IDocumentSetupParticipant[] result= new IDocumentSetupParticipant[participants.size()];
participants.toArray(result);
return result;
}
| public IDocumentSetupParticipant[] getDocumentSetupParticipants(IPath location) {
Set participants= new HashSet();
List p= getDocumentSetupParticipants(findContentTypes(location));
if (p != null)
participants.addAll(p);
p= getDocumentSetupParticipants(location.lastSegment());
if (p != null)
participants.addAll(p);
p= getDocumentSetupParticipants(location.getFileExtension());
if (p != null)
participants.addAll(p);
p= getDocumentSetupParticipants(WILDCARD);
if (p != null)
participants.addAll(p);
IDocumentSetupParticipant[] result= new IDocumentSetupParticipant[participants.size()];
participants.toArray(result);
return result;
}
|
diff --git a/src/com/vaadin/terminal/gwt/client/ui/VWindow.java b/src/com/vaadin/terminal/gwt/client/ui/VWindow.java
index ecb499fdf..4cf3f5fc8 100644
--- a/src/com/vaadin/terminal/gwt/client/ui/VWindow.java
+++ b/src/com/vaadin/terminal/gwt/client/ui/VWindow.java
@@ -1,1161 +1,1161 @@
/*
@ITMillApache2LicenseForJavaFiles@
*/
package com.vaadin.terminal.gwt.client.ui;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.ScrollListener;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.terminal.gwt.client.ApplicationConnection;
import com.vaadin.terminal.gwt.client.BrowserInfo;
import com.vaadin.terminal.gwt.client.Console;
import com.vaadin.terminal.gwt.client.Container;
import com.vaadin.terminal.gwt.client.Paintable;
import com.vaadin.terminal.gwt.client.RenderSpace;
import com.vaadin.terminal.gwt.client.UIDL;
import com.vaadin.terminal.gwt.client.Util;
import com.vaadin.terminal.gwt.client.VDebugConsole;
/**
* "Sub window" component.
*
* TODO update position / scroll position / size to client
*
* @author IT Mill Ltd
*/
public class VWindow extends VOverlay implements Container, ScrollListener {
/**
* Minimum allowed height of a window. This refers to the content area, not
* the outer borders.
*/
private static final int MIN_CONTENT_AREA_HEIGHT = 100;
/**
* Minimum allowed width of a window. This refers to the content area, not
* the outer borders.
*/
private static final int MIN_CONTENT_AREA_WIDTH = 150;
private static ArrayList<VWindow> windowOrder = new ArrayList<VWindow>();
public static final String CLASSNAME = "v-window";
/**
* Difference between offsetWidth and inner width for the content area.
*/
private int contentAreaBorderPadding = -1;
/**
* Pixels used by inner borders and paddings horizontally (calculated only
* once). This is the difference between the width of the root element and
* the content area, such that if root element width is set to "XYZpx" the
* inner width (width-border-padding) of the content area is
* X-contentAreaRootDifference.
*/
private int contentAreaToRootDifference = -1;
private static final int STACKING_OFFSET_PIXELS = 15;
public static final int Z_INDEX = 10000;
private Paintable layout;
private Element contents;
private Element header;
private Element footer;
private Element resizeBox;
private final ScrollPanel contentPanel = new ScrollPanel();
private boolean dragging;
private int startX;
private int startY;
private int origX;
private int origY;
private boolean resizing;
private int origW;
private int origH;
private Element closeBox;
protected ApplicationConnection client;
private String id;
ShortcutActionHandler shortcutHandler;
/** Last known positionx read from UIDL or updated to application connection */
private int uidlPositionX = -1;
/** Last known positiony read from UIDL or updated to application connection */
private int uidlPositionY = -1;
private boolean vaadinModality = false;
private boolean resizable = true;
private boolean draggable = true;
private Element modalityCurtain;
private Element draggingCurtain;
private Element headerText;
private boolean closable = true;
boolean dynamicWidth = false;
boolean dynamicHeight = false;
boolean layoutRelativeWidth = false;
boolean layoutRelativeHeight = false;
// If centered (via UIDL), the window should stay in the centered -mode
// until a position is received from the server, or the user moves or
// resizes the window.
boolean centered = false;
private RenderSpace renderSpace = new RenderSpace(MIN_CONTENT_AREA_WIDTH,
MIN_CONTENT_AREA_HEIGHT, true);
private String width;
private String height;
private boolean immediate;
private Element wrapper, wrapper2;
public VWindow() {
super(false, false, true); // no autohide, not modal, shadow
// Different style of shadow for windows
setShadowStyle("window");
final int order = windowOrder.size();
setWindowOrder(order);
windowOrder.add(this);
constructDOM();
setPopupPosition(order * STACKING_OFFSET_PIXELS, order
* STACKING_OFFSET_PIXELS);
contentPanel.addScrollListener(this);
// make it focusable, but last in focus chain
DOM.setElementProperty(contentPanel.getElement(), "tabIndex", "0");
}
private void bringToFront() {
int curIndex = windowOrder.indexOf(this);
if (curIndex + 1 < windowOrder.size()) {
windowOrder.remove(this);
windowOrder.add(this);
for (; curIndex < windowOrder.size(); curIndex++) {
windowOrder.get(curIndex).setWindowOrder(curIndex);
}
}
}
/**
* Returns true if window is the topmost window
*
* @return
*/
private boolean isActive() {
return windowOrder.get(windowOrder.size() - 1).equals(this);
}
public void setWindowOrder(int order) {
setZIndex(order + Z_INDEX);
}
@Override
protected void setZIndex(int zIndex) {
super.setZIndex(zIndex);
if (vaadinModality) {
DOM.setStyleAttribute(modalityCurtain, "zIndex", "" + zIndex);
}
}
protected void constructDOM() {
setStyleName(CLASSNAME);
header = DOM.createDiv();
DOM.setElementProperty(header, "className", CLASSNAME + "-outerheader");
headerText = DOM.createDiv();
DOM.setElementProperty(headerText, "className", CLASSNAME + "-header");
contents = DOM.createDiv();
DOM.setElementProperty(contents, "className", CLASSNAME + "-contents");
footer = DOM.createDiv();
DOM.setElementProperty(footer, "className", CLASSNAME + "-footer");
resizeBox = DOM.createDiv();
DOM
.setElementProperty(resizeBox, "className", CLASSNAME
+ "-resizebox");
closeBox = DOM.createDiv();
DOM.setElementProperty(closeBox, "className", CLASSNAME + "-closebox");
DOM.appendChild(footer, resizeBox);
DOM.sinkEvents(getElement(), Event.ONLOSECAPTURE);
DOM.sinkEvents(closeBox, Event.ONCLICK);
DOM.sinkEvents(contents, Event.ONCLICK);
wrapper = DOM.createDiv();
DOM.setElementProperty(wrapper, "className", CLASSNAME + "-wrap");
wrapper2 = DOM.createDiv();
DOM.setElementProperty(wrapper2, "className", CLASSNAME + "-wrap2");
DOM.sinkEvents(wrapper, Event.ONKEYDOWN);
DOM.appendChild(wrapper2, closeBox);
DOM.appendChild(wrapper2, header);
DOM.appendChild(header, headerText);
DOM.appendChild(wrapper2, contents);
DOM.appendChild(wrapper2, footer);
DOM.appendChild(wrapper, wrapper2);
DOM.appendChild(super.getContainerElement(), wrapper);
sinkEvents(Event.MOUSEEVENTS);
setWidget(contentPanel);
}
public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
id = uidl.getId();
this.client = client;
// Workaround needed for Testing Tools (GWT generates window DOM
// slightly different in different browsers).
DOM.setElementProperty(closeBox, "id", id + "_window_close");
if (uidl.hasAttribute("invisible")) {
hide();
return;
}
if (!uidl.hasAttribute("cached")) {
if (uidl.getBooleanAttribute("modal") != vaadinModality) {
setVaadinModality(!vaadinModality);
}
if (!isAttached()) {
show();
}
if (uidl.getBooleanAttribute("resizable") != resizable) {
setResizable(!resizable);
}
setDraggable(!uidl.hasAttribute("fixedposition"));
}
if (client.updateComponent(this, uidl, false)) {
return;
}
immediate = uidl.hasAttribute("immediate");
setClosable(!uidl.getBooleanAttribute("readonly"));
// Initialize the position form UIDL
int positionx = uidl.getIntVariable("positionx");
int positiony = uidl.getIntVariable("positiony");
if (positionx >= 0 || positiony >= 0) {
if (positionx < 0) {
positionx = 0;
}
if (positiony < 0) {
positiony = 0;
}
setPopupPosition(positionx, positiony);
}
if (uidl.hasAttribute("caption")) {
setCaption(uidl.getStringAttribute("caption"), uidl
.getStringAttribute("icon"));
}
boolean showingUrl = false;
int childIndex = 0;
UIDL childUidl = uidl.getChildUIDL(childIndex++);
while ("open".equals(childUidl.getTag())) {
// TODO multiple opens with the same target will in practice just
// open the last one - should we fix that somehow?
final String parsedUri = client.translateVaadinUri(childUidl
.getStringAttribute("src"));
if (!childUidl.hasAttribute("name")) {
final Frame frame = new Frame();
DOM.setStyleAttribute(frame.getElement(), "width", "100%");
DOM.setStyleAttribute(frame.getElement(), "height", "100%");
DOM.setStyleAttribute(frame.getElement(), "border", "0px");
frame.setUrl(parsedUri);
contentPanel.setWidget(frame);
showingUrl = true;
} else {
final String target = childUidl.getStringAttribute("name");
Window.open(parsedUri, target, "");
}
childUidl = uidl.getChildUIDL(childIndex++);
}
final Paintable lo = client.getPaintable(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
contentPanel.remove((Widget) layout);
// add new
if (!showingUrl) {
contentPanel.setWidget((Widget) lo);
}
layout = lo;
}
} else if (!showingUrl) {
contentPanel.setWidget((Widget) lo);
layout = lo;
}
dynamicWidth = !uidl.hasAttribute("width");
dynamicHeight = !uidl.hasAttribute("height");
layoutRelativeWidth = uidl.hasAttribute("layoutRelativeWidth");
layoutRelativeHeight = uidl.hasAttribute("layoutRelativeHeight");
if (dynamicWidth && layoutRelativeWidth) {
/*
* Relative layout width, fix window width before rendering (width
* according to caption)
*/
setNaturalWidth();
}
layout.updateFromUIDL(childUidl, client);
if (!dynamicHeight && layoutRelativeWidth) {
/*
* Relative layout width, and fixed height. Must update the size to
* be able to take scrollbars into account (layout gets narrower
* space if it is higher than the window) -> only vertical scrollbar
*/
client.runDescendentsLayout(this);
}
/*
* No explicit width is set and the layout does not have relative width
* so fix the size according to the layout.
*/
if (dynamicWidth && !layoutRelativeWidth) {
setNaturalWidth();
}
if (dynamicHeight && layoutRelativeHeight) {
// Prevent resizing until height has been fixed
resizable = false;
}
// we may have actions and notifications
if (uidl.getChildCount() > 1) {
final int cnt = uidl.getChildCount();
for (int i = 1; i < cnt; i++) {
childUidl = uidl.getChildUIDL(i);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null) {
shortcutHandler = new ShortcutActionHandler(id, client);
}
shortcutHandler.updateActionMap(childUidl);
} else if (childUidl.getTag().equals("notifications")) {
// TODO needed? move ->
for (final Iterator it = childUidl.getChildIterator(); it
.hasNext();) {
final UIDL notification = (UIDL) it.next();
String html = "";
if (notification.hasAttribute("icon")) {
final String parsedUri = client
.translateVaadinUri(notification
.getStringAttribute("icon"));
html += "<img src=\"" + parsedUri + "\" />";
}
if (notification.hasAttribute("caption")) {
html += "<h1>"
+ notification
.getStringAttribute("caption")
+ "</h1>";
}
if (notification.hasAttribute("message")) {
html += "<p>"
+ notification
.getStringAttribute("message")
+ "</p>";
}
final String style = notification.hasAttribute("style") ? notification
.getStringAttribute("style")
: null;
final int position = notification
.getIntAttribute("position");
final int delay = notification.getIntAttribute("delay");
new VNotification(delay).show(html, position, style);
}
}
}
}
// setting scrollposition must happen after children is rendered
contentPanel.setScrollPosition(uidl.getIntVariable("scrollTop"));
contentPanel.setHorizontalScrollPosition(uidl
.getIntVariable("scrollLeft"));
// Center this window on screen if requested
// This has to be here because we might not know the content size before
// everything is painted into the window
if (uidl.getBooleanAttribute("center")) {
// mark as centered - this is unset on move/resize
centered = true;
center();
} else {
// don't try to center the window anymore
centered = false;
}
updateShadowSizeAndPosition();
boolean sizeReduced = false;
// ensure window is not larger than browser window
if (getOffsetWidth() > Window.getClientWidth()) {
setWidth(Window.getClientWidth() + "px");
sizeReduced = true;
}
if (getOffsetHeight() > Window.getClientHeight()) {
setHeight(Window.getClientHeight() + "px");
sizeReduced = true;
}
if (dynamicHeight && layoutRelativeHeight) {
/*
* Window height is undefined, layout is 100% high so the layout
* should define the initial window height but on resize the layout
* should be as high as the window. We fix the height to deal with
* this.
*/
int h = contents.getOffsetHeight() + getExtraHeight();
- int w = contents.getOffsetWidth();
+ int w = getElement().getOffsetWidth();
client.updateVariable(id, "height", h, false);
client.updateVariable(id, "width", w, true);
}
if (sizeReduced) {
// If we changed the size we need to update the size of the child
// component if it is relative (#3407)
client.runDescendentsLayout(this);
}
Util.runWebkitOverflowAutoFix(contentPanel.getElement());
client.getView().scrollIntoView(uidl);
}
private void setDraggable(boolean draggable) {
if (this.draggable == draggable) {
return;
}
this.draggable = draggable;
if (!this.draggable) {
header.getStyle().setProperty("cursor", "default");
} else {
header.getStyle().setProperty("cursor", "");
}
}
private void setNaturalWidth() {
/*
* Use max(layout width, window width) i.e layout content width or
* caption width. We remove the previous set width so the width is
* allowed to shrink. All widths are measured as outer sizes, i.e. the
* borderWidth is added to the content.
*/
DOM.setStyleAttribute(getElement(), "width", "");
String oldHeaderWidth = ""; // Only for IE6
if (BrowserInfo.get().isIE6()) {
/*
* For some reason IE6 has title DIV set to width 100% which
* interferes with the header measuring. Also IE6 has width set to
* the contentPanel.
*/
oldHeaderWidth = headerText.getStyle().getProperty("width");
DOM.setStyleAttribute(contentPanel.getElement(), "width", "auto");
DOM.setStyleAttribute(contentPanel.getElement(), "zoom", "1");
headerText.getStyle().setProperty("width", "auto");
}
// Content
int contentWidth = contentPanel.getElement().getScrollWidth();
contentWidth += getContentAreaToRootDifference();
// Window width (caption)
int windowCaptionWidth = getOffsetWidth();
int naturalWidth = (contentWidth > windowCaptionWidth ? contentWidth
: windowCaptionWidth);
if (BrowserInfo.get().isIE6()) {
headerText.getStyle().setProperty("width", oldHeaderWidth);
}
setWidth(naturalWidth + "px");
}
private int getContentAreaToRootDifference() {
if (contentAreaToRootDifference < 0) {
measure();
}
return contentAreaToRootDifference;
}
private int getContentAreaBorderPadding() {
if (contentAreaBorderPadding < 0) {
measure();
}
return contentAreaBorderPadding;
}
private void measure() {
if (!isAttached()) {
return;
}
contentAreaBorderPadding = Util.measureHorizontalPaddingAndBorder(
contents, 4);
int wrapperPaddingBorder = Util.measureHorizontalPaddingAndBorder(
wrapper, 0)
+ Util.measureHorizontalPaddingAndBorder(wrapper2, 0);
contentAreaToRootDifference = wrapperPaddingBorder
+ contentAreaBorderPadding;
}
/**
* Sets the closable state of the window. Additionally hides/shows the close
* button according to the new state.
*
* @param closable
* true if the window can be closed by the user
*/
protected void setClosable(boolean closable) {
if (this.closable == closable) {
return;
}
this.closable = closable;
if (closable) {
DOM.setStyleAttribute(closeBox, "display", "");
} else {
DOM.setStyleAttribute(closeBox, "display", "none");
}
}
/**
* Returns the closable state of the sub window. If the sub window is
* closable a decoration (typically an X) is shown to the user. By clicking
* on the X the user can close the window.
*
* @return true if the sub window is closable
*/
protected boolean isClosable() {
return closable;
}
@Override
public void show() {
if (vaadinModality) {
showModalityCurtain();
}
super.show();
setFF2CaretFixEnabled(true);
fixFF3OverflowBug();
}
/** Disable overflow auto with FF3 to fix #1837. */
private void fixFF3OverflowBug() {
if (BrowserInfo.get().isFF3()) {
DeferredCommand.addCommand(new Command() {
public void execute() {
DOM.setStyleAttribute(getElement(), "overflow", "");
}
});
}
}
/**
* Fix "missing cursor" browser bug workaround for FF2 in Windows and Linux.
*
* Calling this method has no effect on other browsers than the ones based
* on Gecko 1.8
*
* @param enable
*/
private void setFF2CaretFixEnabled(boolean enable) {
if (BrowserInfo.get().isFF2()) {
if (enable) {
DeferredCommand.addCommand(new Command() {
public void execute() {
DOM.setStyleAttribute(getElement(), "overflow", "auto");
}
});
} else {
DOM.setStyleAttribute(getElement(), "overflow", "");
}
}
}
@Override
public void hide() {
if (vaadinModality) {
hideModalityCurtain();
}
super.hide();
}
private void setVaadinModality(boolean modality) {
vaadinModality = modality;
if (vaadinModality) {
modalityCurtain = DOM.createDiv();
DOM.setElementProperty(modalityCurtain, "className", CLASSNAME
+ "-modalitycurtain");
if (isAttached()) {
showModalityCurtain();
bringToFront();
} else {
DeferredCommand.addCommand(new Command() {
public void execute() {
// vaadinModality window must on top of others
bringToFront();
}
});
}
} else {
if (modalityCurtain != null) {
if (isAttached()) {
hideModalityCurtain();
}
modalityCurtain = null;
}
}
}
private void showModalityCurtain() {
if (BrowserInfo.get().isFF2()) {
DOM.setStyleAttribute(modalityCurtain, "height", DOM
.getElementPropertyInt(RootPanel.getBodyElement(),
"offsetHeight")
+ "px");
DOM.setStyleAttribute(modalityCurtain, "position", "absolute");
}
DOM.setStyleAttribute(modalityCurtain, "zIndex", ""
+ (windowOrder.indexOf(this) + Z_INDEX));
DOM.appendChild(RootPanel.getBodyElement(), modalityCurtain);
}
private void hideModalityCurtain() {
DOM.removeChild(RootPanel.getBodyElement(), modalityCurtain);
}
/*
* Shows (or hides) an empty div on top of all other content; used when
* resizing or moving, so that iframes (etc) do not steal event.
*/
private void showDraggingCurtain(boolean show) {
if (show && draggingCurtain == null) {
setFF2CaretFixEnabled(false); // makes FF2 slow
draggingCurtain = DOM.createDiv();
DOM.setStyleAttribute(draggingCurtain, "position", "absolute");
DOM.setStyleAttribute(draggingCurtain, "top", "0px");
DOM.setStyleAttribute(draggingCurtain, "left", "0px");
DOM.setStyleAttribute(draggingCurtain, "width", "100%");
DOM.setStyleAttribute(draggingCurtain, "height", "100%");
DOM.setStyleAttribute(draggingCurtain, "zIndex", ""
+ VOverlay.Z_INDEX);
DOM.appendChild(RootPanel.getBodyElement(), draggingCurtain);
} else if (!show && draggingCurtain != null) {
setFF2CaretFixEnabled(true); // makes FF2 slow
DOM.removeChild(RootPanel.getBodyElement(), draggingCurtain);
draggingCurtain = null;
}
}
private void setResizable(boolean resizability) {
resizable = resizability;
if (resizability) {
DOM.setElementProperty(footer, "className", CLASSNAME + "-footer");
DOM.setElementProperty(resizeBox, "className", CLASSNAME
+ "-resizebox");
} else {
DOM.setElementProperty(footer, "className", CLASSNAME + "-footer "
+ CLASSNAME + "-footer-noresize");
DOM.setElementProperty(resizeBox, "className", CLASSNAME
+ "-resizebox " + CLASSNAME + "-resizebox-disabled");
}
}
@Override
public void setPopupPosition(int left, int top) {
if (top < 0) {
// ensure window is not moved out of browser window from top of the
// screen
top = 0;
}
super.setPopupPosition(left, top);
if (left != uidlPositionX && client != null) {
client.updateVariable(id, "positionx", left, false);
uidlPositionX = left;
}
if (top != uidlPositionY && client != null) {
client.updateVariable(id, "positiony", top, false);
uidlPositionY = top;
}
}
public void setCaption(String c) {
setCaption(c, null);
}
public void setCaption(String c, String icon) {
String html = Util.escapeHTML(c);
if (icon != null) {
icon = client.translateVaadinUri(icon);
html = "<img src=\"" + icon + "\" class=\"v-icon\" />" + html;
}
DOM.setInnerHTML(headerText, html);
}
@Override
protected Element getContainerElement() {
// in GWT 1.5 this method is used in PopupPanel constructor
if (contents == null) {
return super.getContainerElement();
}
return contents;
}
@Override
public void onBrowserEvent(final Event event) {
if (event != null) {
final int type = event.getTypeInt();
if (type == Event.ONKEYDOWN && shortcutHandler != null) {
shortcutHandler.handleKeyboardEvent(event);
return;
}
final Element target = DOM.eventGetTarget(event);
// Handle window caption tooltips
if (client != null && DOM.isOrHasChild(header, target)) {
client.handleTooltipEvent(event, this);
}
if (resizing || resizeBox == target) {
onResizeEvent(event);
event.cancelBubble(true);
} else if (target == closeBox) {
if (type == Event.ONCLICK && isClosable()) {
onCloseClick();
event.cancelBubble(true);
}
} else if (dragging || !DOM.isOrHasChild(contents, target)) {
onDragEvent(event);
event.cancelBubble(true);
} else if (type == Event.ONCLICK) {
// clicked inside window, ensure to be on top
if (!isActive()) {
bringToFront();
}
}
if (type == Event.ONMOUSEDOWN
&& !DOM.isOrHasChild(contentPanel.getElement(), target)) {
Util.focus(contentPanel.getElement());
}
}
}
private void onCloseClick() {
client.updateVariable(id, "close", true, true);
}
private void onResizeEvent(Event event) {
if (resizable) {
switch (event.getTypeInt()) {
case Event.ONMOUSEDOWN:
if (!isActive()) {
bringToFront();
}
showDraggingCurtain(true);
if (BrowserInfo.get().isIE()) {
DOM.setStyleAttribute(resizeBox, "visibility", "hidden");
}
resizing = true;
startX = event.getScreenX();
startY = event.getScreenY();
origW = getElement().getOffsetWidth();
origH = getElement().getOffsetHeight();
DOM.setCapture(getElement());
event.preventDefault();
break;
case Event.ONMOUSEUP:
showDraggingCurtain(false);
if (BrowserInfo.get().isIE()) {
DOM.setStyleAttribute(resizeBox, "visibility", "");
}
resizing = false;
DOM.releaseCapture(getElement());
setSize(event, true);
break;
case Event.ONLOSECAPTURE:
showDraggingCurtain(false);
if (BrowserInfo.get().isIE()) {
DOM.setStyleAttribute(resizeBox, "visibility", "");
}
resizing = false;
case Event.ONMOUSEMOVE:
if (resizing) {
centered = false;
setSize(event, false);
event.preventDefault();
}
break;
default:
event.preventDefault();
break;
}
}
}
/**
* Checks if the cursor was inside the browser content area when the event
* happened.
*
* @param event
* The event to be checked
* @return true, if the cursor is inside the browser content area
*
* false, otherwise
*/
private boolean cursorInsideBrowserContentArea(Event event) {
if (event.getClientX() < 0 || event.getClientY() < 0) {
// Outside to the left or above
return false;
}
if (event.getClientX() > Window.getClientWidth()
|| event.getClientY() > Window.getClientHeight()) {
// Outside to the right or below
return false;
}
return true;
}
private void setSize(Event event, boolean updateVariables) {
if (!cursorInsideBrowserContentArea(event)) {
// Only drag while cursor is inside the browser client area
return;
}
int w = event.getScreenX() - startX + origW;
if (w < MIN_CONTENT_AREA_WIDTH + getContentAreaToRootDifference()) {
w = MIN_CONTENT_AREA_WIDTH + getContentAreaToRootDifference();
}
int h = event.getScreenY() - startY + origH;
if (h < MIN_CONTENT_AREA_HEIGHT + getExtraHeight()) {
h = MIN_CONTENT_AREA_HEIGHT + getExtraHeight();
}
setWidth(w + "px");
setHeight(h + "px");
if (updateVariables) {
// sending width back always as pixels, no need for unit
client.updateVariable(id, "width", w, false);
client.updateVariable(id, "height", h, immediate);
}
// Update child widget dimensions
if (client != null) {
client.handleComponentRelativeSize((Widget) layout);
client.runDescendentsLayout((HasWidgets) layout);
}
Util.runWebkitOverflowAutoFix(contentPanel.getElement());
}
@Override
/*
* Width is set to the out-most element (v-window).
*
* This function should never be called with percentage values (it will
* throw an exception)
*/
public void setWidth(String width) {
this.width = width;
if (!isAttached()) {
return;
}
if (width != null && !"".equals(width)) {
int rootPixelWidth = -1;
if (width.indexOf("px") < 0) {
/*
* Convert non-pixel values to pixels by setting the width and
* then measuring it. Updates the "width" variable with the
* pixel width.
*/
DOM.setStyleAttribute(getElement(), "width", width);
rootPixelWidth = getElement().getOffsetWidth();
width = rootPixelWidth + "px";
} else {
rootPixelWidth = Integer.parseInt(width.substring(0, width
.indexOf("px")));
}
// "width" now contains the new width in pixels
if (BrowserInfo.get().isIE6()) {
getElement().getStyle().setProperty("overflow", "hidden");
}
// Apply the new pixel width
getElement().getStyle().setProperty("width", width);
// Caculate the inner width of the content area
int contentAreaInnerWidth = rootPixelWidth
- getContentAreaToRootDifference();
if (contentAreaInnerWidth < MIN_CONTENT_AREA_WIDTH) {
contentAreaInnerWidth = MIN_CONTENT_AREA_WIDTH;
int rootWidth = contentAreaInnerWidth
+ getContentAreaToRootDifference();
DOM.setStyleAttribute(getElement(), "width", rootWidth + "px");
}
// IE6 needs the actual inner content width on the content element,
// otherwise it won't wrap the content properly (no scrollbars
// appear, content flows out of window)
if (BrowserInfo.get().isIE6()) {
DOM.setStyleAttribute(contentPanel.getElement(), "width",
contentAreaInnerWidth + "px");
}
renderSpace.setWidth(contentAreaInnerWidth);
updateShadowSizeAndPosition();
}
}
@Override
/*
* Height is set to the out-most element (v-window).
*
* This function should never be called with percentage values (it will
* throw an exception)
*/
public void setHeight(String height) {
this.height = height;
if (!isAttached()) {
return;
}
if (height != null && !"".equals(height)) {
DOM.setStyleAttribute(getElement(), "height", height);
int pixels = getElement().getOffsetHeight() - getExtraHeight();
if (pixels < MIN_CONTENT_AREA_HEIGHT) {
pixels = MIN_CONTENT_AREA_HEIGHT;
int rootHeight = pixels + getExtraHeight();
DOM.setStyleAttribute(getElement(), "height", (rootHeight)
+ "px");
}
renderSpace.setHeight(pixels);
height = pixels + "px";
contentPanel.getElement().getStyle().setProperty("height", height);
updateShadowSizeAndPosition();
}
}
private int extraH = 0;
private int getExtraHeight() {
extraH = header.getOffsetHeight() + footer.getOffsetHeight();
return extraH;
}
private void onDragEvent(Event event) {
switch (DOM.eventGetType(event)) {
case Event.ONMOUSEDOWN:
if (!isActive()) {
bringToFront();
}
if (draggable) {
showDraggingCurtain(true);
dragging = true;
startX = DOM.eventGetScreenX(event);
startY = DOM.eventGetScreenY(event);
origX = DOM.getAbsoluteLeft(getElement());
origY = DOM.getAbsoluteTop(getElement());
DOM.setCapture(getElement());
DOM.eventPreventDefault(event);
}
break;
case Event.ONMOUSEUP:
dragging = false;
showDraggingCurtain(false);
DOM.releaseCapture(getElement());
break;
case Event.ONLOSECAPTURE:
showDraggingCurtain(false);
dragging = false;
break;
case Event.ONMOUSEMOVE:
if (dragging) {
centered = false;
if (cursorInsideBrowserContentArea(event)) {
// Only drag while cursor is inside the browser client area
final int x = DOM.eventGetScreenX(event) - startX + origX;
final int y = DOM.eventGetScreenY(event) - startY + origY;
setPopupPosition(x, y);
}
DOM.eventPreventDefault(event);
}
break;
default:
break;
}
}
@Override
public boolean onEventPreview(Event event) {
if (dragging) {
onDragEvent(event);
return false;
} else if (resizing) {
onResizeEvent(event);
return false;
} else if (vaadinModality) {
// return false when modal and outside window
final Element target = event.getTarget().cast();
if (DOM.getCaptureElement() != null) {
// Allow events when capture is set
return true;
}
if (!DOM.isOrHasChild(getElement(), target)) {
// not within the modal window, but let's see if it's in the
// debug window
Console console = ApplicationConnection.getConsole();
if (console instanceof VDebugConsole
&& DOM.isOrHasChild(((VDebugConsole) console)
.getElement(), target)) {
return true; // allow debug-window clicks
}
return false;
}
}
return true;
}
public void onScroll(Widget widget, int scrollLeft, int scrollTop) {
client.updateVariable(id, "scrollTop", scrollTop, false);
client.updateVariable(id, "scrollLeft", scrollLeft, false);
}
@Override
public void addStyleDependentName(String styleSuffix) {
// VWindow's getStyleElement() does not return the same element as
// getElement(), so we need to override this.
setStyleName(getElement(), getStylePrimaryName() + "-" + styleSuffix,
true);
}
@Override
protected void onAttach() {
super.onAttach();
setWidth(width);
setHeight(height);
}
public RenderSpace getAllocatedSpace(Widget child) {
if (child == layout) {
return renderSpace;
} else {
// Exception ??
return null;
}
}
public boolean hasChildComponent(Widget component) {
if (component == layout) {
return true;
} else {
return false;
}
}
public void replaceChildComponent(Widget oldComponent, Widget newComponent) {
contentPanel.setWidget(newComponent);
}
public boolean requestLayout(Set<Paintable> child) {
if (dynamicWidth && !layoutRelativeWidth) {
setNaturalWidth();
}
if (centered) {
center();
}
updateShadowSizeAndPosition();
// layout size change may affect its available space (scrollbars)
client.handleComponentRelativeSize((Widget) layout);
return true;
}
public void updateCaption(Paintable component, UIDL uidl) {
// NOP, window has own caption, layout captio not rendered
}
}
| true | true | public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
id = uidl.getId();
this.client = client;
// Workaround needed for Testing Tools (GWT generates window DOM
// slightly different in different browsers).
DOM.setElementProperty(closeBox, "id", id + "_window_close");
if (uidl.hasAttribute("invisible")) {
hide();
return;
}
if (!uidl.hasAttribute("cached")) {
if (uidl.getBooleanAttribute("modal") != vaadinModality) {
setVaadinModality(!vaadinModality);
}
if (!isAttached()) {
show();
}
if (uidl.getBooleanAttribute("resizable") != resizable) {
setResizable(!resizable);
}
setDraggable(!uidl.hasAttribute("fixedposition"));
}
if (client.updateComponent(this, uidl, false)) {
return;
}
immediate = uidl.hasAttribute("immediate");
setClosable(!uidl.getBooleanAttribute("readonly"));
// Initialize the position form UIDL
int positionx = uidl.getIntVariable("positionx");
int positiony = uidl.getIntVariable("positiony");
if (positionx >= 0 || positiony >= 0) {
if (positionx < 0) {
positionx = 0;
}
if (positiony < 0) {
positiony = 0;
}
setPopupPosition(positionx, positiony);
}
if (uidl.hasAttribute("caption")) {
setCaption(uidl.getStringAttribute("caption"), uidl
.getStringAttribute("icon"));
}
boolean showingUrl = false;
int childIndex = 0;
UIDL childUidl = uidl.getChildUIDL(childIndex++);
while ("open".equals(childUidl.getTag())) {
// TODO multiple opens with the same target will in practice just
// open the last one - should we fix that somehow?
final String parsedUri = client.translateVaadinUri(childUidl
.getStringAttribute("src"));
if (!childUidl.hasAttribute("name")) {
final Frame frame = new Frame();
DOM.setStyleAttribute(frame.getElement(), "width", "100%");
DOM.setStyleAttribute(frame.getElement(), "height", "100%");
DOM.setStyleAttribute(frame.getElement(), "border", "0px");
frame.setUrl(parsedUri);
contentPanel.setWidget(frame);
showingUrl = true;
} else {
final String target = childUidl.getStringAttribute("name");
Window.open(parsedUri, target, "");
}
childUidl = uidl.getChildUIDL(childIndex++);
}
final Paintable lo = client.getPaintable(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
contentPanel.remove((Widget) layout);
// add new
if (!showingUrl) {
contentPanel.setWidget((Widget) lo);
}
layout = lo;
}
} else if (!showingUrl) {
contentPanel.setWidget((Widget) lo);
layout = lo;
}
dynamicWidth = !uidl.hasAttribute("width");
dynamicHeight = !uidl.hasAttribute("height");
layoutRelativeWidth = uidl.hasAttribute("layoutRelativeWidth");
layoutRelativeHeight = uidl.hasAttribute("layoutRelativeHeight");
if (dynamicWidth && layoutRelativeWidth) {
/*
* Relative layout width, fix window width before rendering (width
* according to caption)
*/
setNaturalWidth();
}
layout.updateFromUIDL(childUidl, client);
if (!dynamicHeight && layoutRelativeWidth) {
/*
* Relative layout width, and fixed height. Must update the size to
* be able to take scrollbars into account (layout gets narrower
* space if it is higher than the window) -> only vertical scrollbar
*/
client.runDescendentsLayout(this);
}
/*
* No explicit width is set and the layout does not have relative width
* so fix the size according to the layout.
*/
if (dynamicWidth && !layoutRelativeWidth) {
setNaturalWidth();
}
if (dynamicHeight && layoutRelativeHeight) {
// Prevent resizing until height has been fixed
resizable = false;
}
// we may have actions and notifications
if (uidl.getChildCount() > 1) {
final int cnt = uidl.getChildCount();
for (int i = 1; i < cnt; i++) {
childUidl = uidl.getChildUIDL(i);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null) {
shortcutHandler = new ShortcutActionHandler(id, client);
}
shortcutHandler.updateActionMap(childUidl);
} else if (childUidl.getTag().equals("notifications")) {
// TODO needed? move ->
for (final Iterator it = childUidl.getChildIterator(); it
.hasNext();) {
final UIDL notification = (UIDL) it.next();
String html = "";
if (notification.hasAttribute("icon")) {
final String parsedUri = client
.translateVaadinUri(notification
.getStringAttribute("icon"));
html += "<img src=\"" + parsedUri + "\" />";
}
if (notification.hasAttribute("caption")) {
html += "<h1>"
+ notification
.getStringAttribute("caption")
+ "</h1>";
}
if (notification.hasAttribute("message")) {
html += "<p>"
+ notification
.getStringAttribute("message")
+ "</p>";
}
final String style = notification.hasAttribute("style") ? notification
.getStringAttribute("style")
: null;
final int position = notification
.getIntAttribute("position");
final int delay = notification.getIntAttribute("delay");
new VNotification(delay).show(html, position, style);
}
}
}
}
// setting scrollposition must happen after children is rendered
contentPanel.setScrollPosition(uidl.getIntVariable("scrollTop"));
contentPanel.setHorizontalScrollPosition(uidl
.getIntVariable("scrollLeft"));
// Center this window on screen if requested
// This has to be here because we might not know the content size before
// everything is painted into the window
if (uidl.getBooleanAttribute("center")) {
// mark as centered - this is unset on move/resize
centered = true;
center();
} else {
// don't try to center the window anymore
centered = false;
}
updateShadowSizeAndPosition();
boolean sizeReduced = false;
// ensure window is not larger than browser window
if (getOffsetWidth() > Window.getClientWidth()) {
setWidth(Window.getClientWidth() + "px");
sizeReduced = true;
}
if (getOffsetHeight() > Window.getClientHeight()) {
setHeight(Window.getClientHeight() + "px");
sizeReduced = true;
}
if (dynamicHeight && layoutRelativeHeight) {
/*
* Window height is undefined, layout is 100% high so the layout
* should define the initial window height but on resize the layout
* should be as high as the window. We fix the height to deal with
* this.
*/
int h = contents.getOffsetHeight() + getExtraHeight();
int w = contents.getOffsetWidth();
client.updateVariable(id, "height", h, false);
client.updateVariable(id, "width", w, true);
}
if (sizeReduced) {
// If we changed the size we need to update the size of the child
// component if it is relative (#3407)
client.runDescendentsLayout(this);
}
Util.runWebkitOverflowAutoFix(contentPanel.getElement());
client.getView().scrollIntoView(uidl);
}
| public void updateFromUIDL(UIDL uidl, ApplicationConnection client) {
id = uidl.getId();
this.client = client;
// Workaround needed for Testing Tools (GWT generates window DOM
// slightly different in different browsers).
DOM.setElementProperty(closeBox, "id", id + "_window_close");
if (uidl.hasAttribute("invisible")) {
hide();
return;
}
if (!uidl.hasAttribute("cached")) {
if (uidl.getBooleanAttribute("modal") != vaadinModality) {
setVaadinModality(!vaadinModality);
}
if (!isAttached()) {
show();
}
if (uidl.getBooleanAttribute("resizable") != resizable) {
setResizable(!resizable);
}
setDraggable(!uidl.hasAttribute("fixedposition"));
}
if (client.updateComponent(this, uidl, false)) {
return;
}
immediate = uidl.hasAttribute("immediate");
setClosable(!uidl.getBooleanAttribute("readonly"));
// Initialize the position form UIDL
int positionx = uidl.getIntVariable("positionx");
int positiony = uidl.getIntVariable("positiony");
if (positionx >= 0 || positiony >= 0) {
if (positionx < 0) {
positionx = 0;
}
if (positiony < 0) {
positiony = 0;
}
setPopupPosition(positionx, positiony);
}
if (uidl.hasAttribute("caption")) {
setCaption(uidl.getStringAttribute("caption"), uidl
.getStringAttribute("icon"));
}
boolean showingUrl = false;
int childIndex = 0;
UIDL childUidl = uidl.getChildUIDL(childIndex++);
while ("open".equals(childUidl.getTag())) {
// TODO multiple opens with the same target will in practice just
// open the last one - should we fix that somehow?
final String parsedUri = client.translateVaadinUri(childUidl
.getStringAttribute("src"));
if (!childUidl.hasAttribute("name")) {
final Frame frame = new Frame();
DOM.setStyleAttribute(frame.getElement(), "width", "100%");
DOM.setStyleAttribute(frame.getElement(), "height", "100%");
DOM.setStyleAttribute(frame.getElement(), "border", "0px");
frame.setUrl(parsedUri);
contentPanel.setWidget(frame);
showingUrl = true;
} else {
final String target = childUidl.getStringAttribute("name");
Window.open(parsedUri, target, "");
}
childUidl = uidl.getChildUIDL(childIndex++);
}
final Paintable lo = client.getPaintable(childUidl);
if (layout != null) {
if (layout != lo) {
// remove old
client.unregisterPaintable(layout);
contentPanel.remove((Widget) layout);
// add new
if (!showingUrl) {
contentPanel.setWidget((Widget) lo);
}
layout = lo;
}
} else if (!showingUrl) {
contentPanel.setWidget((Widget) lo);
layout = lo;
}
dynamicWidth = !uidl.hasAttribute("width");
dynamicHeight = !uidl.hasAttribute("height");
layoutRelativeWidth = uidl.hasAttribute("layoutRelativeWidth");
layoutRelativeHeight = uidl.hasAttribute("layoutRelativeHeight");
if (dynamicWidth && layoutRelativeWidth) {
/*
* Relative layout width, fix window width before rendering (width
* according to caption)
*/
setNaturalWidth();
}
layout.updateFromUIDL(childUidl, client);
if (!dynamicHeight && layoutRelativeWidth) {
/*
* Relative layout width, and fixed height. Must update the size to
* be able to take scrollbars into account (layout gets narrower
* space if it is higher than the window) -> only vertical scrollbar
*/
client.runDescendentsLayout(this);
}
/*
* No explicit width is set and the layout does not have relative width
* so fix the size according to the layout.
*/
if (dynamicWidth && !layoutRelativeWidth) {
setNaturalWidth();
}
if (dynamicHeight && layoutRelativeHeight) {
// Prevent resizing until height has been fixed
resizable = false;
}
// we may have actions and notifications
if (uidl.getChildCount() > 1) {
final int cnt = uidl.getChildCount();
for (int i = 1; i < cnt; i++) {
childUidl = uidl.getChildUIDL(i);
if (childUidl.getTag().equals("actions")) {
if (shortcutHandler == null) {
shortcutHandler = new ShortcutActionHandler(id, client);
}
shortcutHandler.updateActionMap(childUidl);
} else if (childUidl.getTag().equals("notifications")) {
// TODO needed? move ->
for (final Iterator it = childUidl.getChildIterator(); it
.hasNext();) {
final UIDL notification = (UIDL) it.next();
String html = "";
if (notification.hasAttribute("icon")) {
final String parsedUri = client
.translateVaadinUri(notification
.getStringAttribute("icon"));
html += "<img src=\"" + parsedUri + "\" />";
}
if (notification.hasAttribute("caption")) {
html += "<h1>"
+ notification
.getStringAttribute("caption")
+ "</h1>";
}
if (notification.hasAttribute("message")) {
html += "<p>"
+ notification
.getStringAttribute("message")
+ "</p>";
}
final String style = notification.hasAttribute("style") ? notification
.getStringAttribute("style")
: null;
final int position = notification
.getIntAttribute("position");
final int delay = notification.getIntAttribute("delay");
new VNotification(delay).show(html, position, style);
}
}
}
}
// setting scrollposition must happen after children is rendered
contentPanel.setScrollPosition(uidl.getIntVariable("scrollTop"));
contentPanel.setHorizontalScrollPosition(uidl
.getIntVariable("scrollLeft"));
// Center this window on screen if requested
// This has to be here because we might not know the content size before
// everything is painted into the window
if (uidl.getBooleanAttribute("center")) {
// mark as centered - this is unset on move/resize
centered = true;
center();
} else {
// don't try to center the window anymore
centered = false;
}
updateShadowSizeAndPosition();
boolean sizeReduced = false;
// ensure window is not larger than browser window
if (getOffsetWidth() > Window.getClientWidth()) {
setWidth(Window.getClientWidth() + "px");
sizeReduced = true;
}
if (getOffsetHeight() > Window.getClientHeight()) {
setHeight(Window.getClientHeight() + "px");
sizeReduced = true;
}
if (dynamicHeight && layoutRelativeHeight) {
/*
* Window height is undefined, layout is 100% high so the layout
* should define the initial window height but on resize the layout
* should be as high as the window. We fix the height to deal with
* this.
*/
int h = contents.getOffsetHeight() + getExtraHeight();
int w = getElement().getOffsetWidth();
client.updateVariable(id, "height", h, false);
client.updateVariable(id, "width", w, true);
}
if (sizeReduced) {
// If we changed the size we need to update the size of the child
// component if it is relative (#3407)
client.runDescendentsLayout(this);
}
Util.runWebkitOverflowAutoFix(contentPanel.getElement());
client.getView().scrollIntoView(uidl);
}
|
diff --git a/src/AggregateReducer.java b/src/AggregateReducer.java
index 3cc298d..2b9282b 100644
--- a/src/AggregateReducer.java
+++ b/src/AggregateReducer.java
@@ -1,102 +1,102 @@
import java.io.IOException;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Iterator;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
public class AggregateReducer extends MapReduceBase
implements Reducer<Text, DoubleWritable, Text, Text>
{
private int id;
private int reducersNum;
private int reqApproxNum;
private int sampleSize;
private float epsilon;
private boolean set;
@Override
public void configure(JobConf conf)
{
reducersNum = conf.getInt("PARMM.reducersNum", 64);
reqApproxNum = conf.getInt("PARMM.reqApproxNum", reducersNum / 2 +1);
epsilon = conf.getFloat("PARMM.epsilon", (float) 0.02);
sampleSize = conf.getInt("PARMM.sampleSize", 1000);
id = conf.getInt("mapred.task.partition", -1);
set = false;
}
@Override
public void reduce(Text itemset, Iterator<DoubleWritable> values,
OutputCollector<Text,Text> output,
Reporter reporter) throws IOException
{
long startTime = System.currentTimeMillis();
if (! set)
{
reporter.incrCounter("AggregateReducerStart", String.valueOf(id), startTime);
reporter.incrCounter("AggregateReducerEnd", String.valueOf(id), startTime);
set = true;
}
ArrayList<Double> valuesArrList = new ArrayList<Double>(reqApproxNum);
while (values.hasNext())
{
valuesArrList.add(new Double(values.next().get()));
}
//System.out.println("Itemset: " + itemset.toString() + " in: " + valuesArrList.size());
/**
* Only consider the itemset as "global frequent" if it
* appears among the "local frequent" itemsets a sufficient
* number of times.
*/
if (valuesArrList.size() >= reqApproxNum)
{
Double[] valuesArr = new Double[valuesArrList.size()];
valuesArr = valuesArrList.toArray(valuesArr);
Arrays.sort(valuesArr);
/**
* Compute the smallest frequency interval containing
* reducersNum-requiredApproxNum+1 estimates of the
* frequency of the itemset. Use the center of this
* interval as global estimate for the frequency. The
* confidence interval is obtained by enlarging the
* above interval by epsilon/2 on both sides.
*/
double minIntervalLength = valuesArr[reducersNum-reqApproxNum] - valuesArr[0];
int startIndex = 0;
for (int i = 1; i < valuesArr.length - reducersNum + reqApproxNum; i++)
{
double intervalLength = valuesArr[reducersNum-reqApproxNum + i] - valuesArr[i];
if (intervalLength < minIntervalLength)
{
minIntervalLength = intervalLength;
startIndex = i;
}
}
double estimatedFreq = (valuesArr[startIndex] + ((double) (valuesArr[startIndex + reducersNum -
reqApproxNum] - valuesArr[startIndex])/2)) / sampleSize;
- double confIntervalLowBound = Math.max(0, valuesArr[startIndex] / sampleSize - epsilon / 2);
- double confIntervalUppBound = Math.min(1, valuesArr[startIndex + reducersNum - reqApproxNum] / sampleSize + epsilon / 2);
+ double confIntervalLowBound = Math.max(0, (((double)valuesArr[startIndex]) / sampleSize) - (epsilon / 2));
+ double confIntervalUppBound = Math.min(1, (((double)valuesArr[startIndex + reducersNum - reqApproxNum]) / sampleSize) + (epsilon / 2));
String estFreqAndBoundsStr = "(" + estimatedFreq + "," + confIntervalLowBound + "," + confIntervalUppBound + ")";
output.collect(itemset, new Text(estFreqAndBoundsStr));
} // end if (valuesArrList.size() >= requiredNum)
long endTime = System.currentTimeMillis();
reporter.incrCounter("AggregateReducerEnd", String.valueOf(id), endTime-startTime);
}
}
| true | true | public void reduce(Text itemset, Iterator<DoubleWritable> values,
OutputCollector<Text,Text> output,
Reporter reporter) throws IOException
{
long startTime = System.currentTimeMillis();
if (! set)
{
reporter.incrCounter("AggregateReducerStart", String.valueOf(id), startTime);
reporter.incrCounter("AggregateReducerEnd", String.valueOf(id), startTime);
set = true;
}
ArrayList<Double> valuesArrList = new ArrayList<Double>(reqApproxNum);
while (values.hasNext())
{
valuesArrList.add(new Double(values.next().get()));
}
//System.out.println("Itemset: " + itemset.toString() + " in: " + valuesArrList.size());
/**
* Only consider the itemset as "global frequent" if it
* appears among the "local frequent" itemsets a sufficient
* number of times.
*/
if (valuesArrList.size() >= reqApproxNum)
{
Double[] valuesArr = new Double[valuesArrList.size()];
valuesArr = valuesArrList.toArray(valuesArr);
Arrays.sort(valuesArr);
/**
* Compute the smallest frequency interval containing
* reducersNum-requiredApproxNum+1 estimates of the
* frequency of the itemset. Use the center of this
* interval as global estimate for the frequency. The
* confidence interval is obtained by enlarging the
* above interval by epsilon/2 on both sides.
*/
double minIntervalLength = valuesArr[reducersNum-reqApproxNum] - valuesArr[0];
int startIndex = 0;
for (int i = 1; i < valuesArr.length - reducersNum + reqApproxNum; i++)
{
double intervalLength = valuesArr[reducersNum-reqApproxNum + i] - valuesArr[i];
if (intervalLength < minIntervalLength)
{
minIntervalLength = intervalLength;
startIndex = i;
}
}
double estimatedFreq = (valuesArr[startIndex] + ((double) (valuesArr[startIndex + reducersNum -
reqApproxNum] - valuesArr[startIndex])/2)) / sampleSize;
double confIntervalLowBound = Math.max(0, valuesArr[startIndex] / sampleSize - epsilon / 2);
double confIntervalUppBound = Math.min(1, valuesArr[startIndex + reducersNum - reqApproxNum] / sampleSize + epsilon / 2);
String estFreqAndBoundsStr = "(" + estimatedFreq + "," + confIntervalLowBound + "," + confIntervalUppBound + ")";
output.collect(itemset, new Text(estFreqAndBoundsStr));
} // end if (valuesArrList.size() >= requiredNum)
long endTime = System.currentTimeMillis();
reporter.incrCounter("AggregateReducerEnd", String.valueOf(id), endTime-startTime);
}
| public void reduce(Text itemset, Iterator<DoubleWritable> values,
OutputCollector<Text,Text> output,
Reporter reporter) throws IOException
{
long startTime = System.currentTimeMillis();
if (! set)
{
reporter.incrCounter("AggregateReducerStart", String.valueOf(id), startTime);
reporter.incrCounter("AggregateReducerEnd", String.valueOf(id), startTime);
set = true;
}
ArrayList<Double> valuesArrList = new ArrayList<Double>(reqApproxNum);
while (values.hasNext())
{
valuesArrList.add(new Double(values.next().get()));
}
//System.out.println("Itemset: " + itemset.toString() + " in: " + valuesArrList.size());
/**
* Only consider the itemset as "global frequent" if it
* appears among the "local frequent" itemsets a sufficient
* number of times.
*/
if (valuesArrList.size() >= reqApproxNum)
{
Double[] valuesArr = new Double[valuesArrList.size()];
valuesArr = valuesArrList.toArray(valuesArr);
Arrays.sort(valuesArr);
/**
* Compute the smallest frequency interval containing
* reducersNum-requiredApproxNum+1 estimates of the
* frequency of the itemset. Use the center of this
* interval as global estimate for the frequency. The
* confidence interval is obtained by enlarging the
* above interval by epsilon/2 on both sides.
*/
double minIntervalLength = valuesArr[reducersNum-reqApproxNum] - valuesArr[0];
int startIndex = 0;
for (int i = 1; i < valuesArr.length - reducersNum + reqApproxNum; i++)
{
double intervalLength = valuesArr[reducersNum-reqApproxNum + i] - valuesArr[i];
if (intervalLength < minIntervalLength)
{
minIntervalLength = intervalLength;
startIndex = i;
}
}
double estimatedFreq = (valuesArr[startIndex] + ((double) (valuesArr[startIndex + reducersNum -
reqApproxNum] - valuesArr[startIndex])/2)) / sampleSize;
double confIntervalLowBound = Math.max(0, (((double)valuesArr[startIndex]) / sampleSize) - (epsilon / 2));
double confIntervalUppBound = Math.min(1, (((double)valuesArr[startIndex + reducersNum - reqApproxNum]) / sampleSize) + (epsilon / 2));
String estFreqAndBoundsStr = "(" + estimatedFreq + "," + confIntervalLowBound + "," + confIntervalUppBound + ")";
output.collect(itemset, new Text(estFreqAndBoundsStr));
} // end if (valuesArrList.size() >= requiredNum)
long endTime = System.currentTimeMillis();
reporter.incrCounter("AggregateReducerEnd", String.valueOf(id), endTime-startTime);
}
|
diff --git a/src/com/activeandroid/Configuration.java b/src/com/activeandroid/Configuration.java
index 086f6b0..09f38bb 100644
--- a/src/com/activeandroid/Configuration.java
+++ b/src/com/activeandroid/Configuration.java
@@ -1,298 +1,302 @@
package com.activeandroid;
/*
* Copyright (C) 2010 Michael Pardo
*
* 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.
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import com.activeandroid.serializer.TypeSerializer;
import com.activeandroid.util.Log;
import com.activeandroid.util.ReflectionUtils;
public class Configuration {
//////////////////////////////////////////////////////////////////////////////////////
// PRIVATE MEMBERS
//////////////////////////////////////////////////////////////////////////////////////
private Context mContext;
private String mDatabaseName;
private int mDatabaseVersion;
private List<Class<? extends Model>> mModelClasses;
private List<Class<? extends TypeSerializer>> mTypeSerializers;
private int mCacheSize;
//////////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////
private Configuration(Context context) {
mContext = context;
}
//////////////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
//////////////////////////////////////////////////////////////////////////////////////
public Context getContext() {
return mContext;
}
public String getDatabaseName() {
return mDatabaseName;
}
public int getDatabaseVersion() {
return mDatabaseVersion;
}
public List<Class<? extends Model>> getModelClasses() {
return mModelClasses;
}
public List<Class<? extends TypeSerializer>> getTypeSerializers() {
return mTypeSerializers;
}
public int getCacheSize() {
return mCacheSize;
}
public boolean isValid() {
return mModelClasses.size() > 0;
}
//////////////////////////////////////////////////////////////////////////////////////
// INNER CLASSES
//////////////////////////////////////////////////////////////////////////////////////
public static class Builder {
//////////////////////////////////////////////////////////////////////////////////////
// PRIVATE CONSTANTS
//////////////////////////////////////////////////////////////////////////////////////
private static final String AA_DB_NAME = "AA_DB_NAME";
private static final String AA_DB_VERSION = "AA_DB_VERSION";
private final static String AA_MODELS = "AA_MODELS";
private final static String AA_SERIALIZERS = "AA_SERIALIZERS";
private static final int DEFAULT_CACHE_SIZE = 1024;
private static final String DEFAULT_DB_NAME = "Application.db";
//////////////////////////////////////////////////////////////////////////////////////
// PRIVATE MEMBERS
//////////////////////////////////////////////////////////////////////////////////////
private Context mContext;
private Integer mCacheSize;
private String mDatabaseName;
private Integer mDatabaseVersion;
private List<Class<? extends Model>> mModelClasses;
private List<Class<? extends TypeSerializer>> mTypeSerializers;
//////////////////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
//////////////////////////////////////////////////////////////////////////////////////
public Builder(Context context) {
mContext = context.getApplicationContext();
mCacheSize = DEFAULT_CACHE_SIZE;
}
//////////////////////////////////////////////////////////////////////////////////////
// PUBLIC METHODS
//////////////////////////////////////////////////////////////////////////////////////
public Builder setCacheSize(int cacheSize) {
mCacheSize = cacheSize;
return this;
}
public Builder setDatabaseName(String databaseName) {
mDatabaseName = databaseName;
return this;
}
public Builder setDatabaseVersion(int databaseVersion) {
mDatabaseVersion = databaseVersion;
return this;
}
public Builder addModelClass(Class<? extends Model> modelClass) {
if (mModelClasses == null) {
mModelClasses = new ArrayList<Class<? extends Model>>();
}
mModelClasses.add(modelClass);
return this;
}
public Builder addModelClasses(Class<? extends Model>... modelClasses) {
if (mModelClasses == null) {
mModelClasses = new ArrayList<Class<? extends Model>>();
}
mModelClasses.addAll(Arrays.asList(modelClasses));
return this;
}
public Builder setModelClasses(Class<? extends Model>... modelClasses) {
mModelClasses = Arrays.asList(modelClasses);
return this;
}
public Builder addTypeSerializer(Class<? extends TypeSerializer> typeSerializer) {
if (mTypeSerializers == null) {
mTypeSerializers = new ArrayList<Class<? extends TypeSerializer>>();
}
mTypeSerializers.add(typeSerializer);
return this;
}
public Builder addTypeSerializers(Class<? extends TypeSerializer>... typeSerializers) {
if (mTypeSerializers == null) {
mTypeSerializers = new ArrayList<Class<? extends TypeSerializer>>();
}
mTypeSerializers.addAll(Arrays.asList(typeSerializers));
return this;
}
public Builder setTypeSerializers(Class<? extends TypeSerializer>... typeSerializers) {
mTypeSerializers = Arrays.asList(typeSerializers);
return this;
}
public Configuration create() {
Configuration configuration = new Configuration(mContext);
configuration.mCacheSize = mCacheSize;
// Get database name from meta-data
if (mDatabaseName != null) {
configuration.mDatabaseName = mDatabaseName;
}
else {
configuration.mDatabaseName = getMetaDataDatabaseNameOrDefault();
}
// Get database version from meta-data
if (mDatabaseVersion != null) {
configuration.mDatabaseVersion = mDatabaseVersion;
}
else {
configuration.mDatabaseVersion = getMetaDataDatabaseVersionOrDefault();
}
// Get model classes from meta-data
if (mModelClasses != null) {
configuration.mModelClasses = mModelClasses;
}
else {
final String modelList = ReflectionUtils.getMetaData(mContext, AA_MODELS);
- configuration.mModelClasses = loadModelList(modelList.split(","));
+ if (modelList != null) {
+ configuration.mModelClasses = loadModelList(modelList.split(","));
+ }
}
// Get type serializer classes from meta-data
if (mTypeSerializers != null) {
configuration.mTypeSerializers = mTypeSerializers;
}
else {
final String serializerList = ReflectionUtils.getMetaData(mContext, AA_SERIALIZERS);
- configuration.mTypeSerializers = loadSerializerList(serializerList.split(","));
+ if (serializerList != null) {
+ configuration.mTypeSerializers = loadSerializerList(serializerList.split(","));
+ }
}
return configuration;
}
//////////////////////////////////////////////////////////////////////////////////////
// PRIVATE METHODS
//////////////////////////////////////////////////////////////////////////////////////
// Meta-data methods
private String getMetaDataDatabaseNameOrDefault() {
String aaName = ReflectionUtils.getMetaData(mContext, AA_DB_NAME);
if (aaName == null) {
aaName = DEFAULT_DB_NAME;
}
return aaName;
}
private int getMetaDataDatabaseVersionOrDefault() {
Integer aaVersion = ReflectionUtils.getMetaData(mContext, AA_DB_VERSION);
if (aaVersion == null || aaVersion == 0) {
aaVersion = 1;
}
return aaVersion;
}
private List<Class<? extends Model>> loadModelList(String[] models) {
final List<Class<? extends Model>> modelClasses = new ArrayList<Class<? extends Model>>();
final ClassLoader classLoader = mContext.getClass().getClassLoader();
for (String model : models) {
model = ensurePackageInName(model);
try {
Class modelClass = Class.forName(model, false, classLoader);
if (ReflectionUtils.isModel(modelClass)) {
modelClasses.add(modelClass);
}
}
catch (ClassNotFoundException e) {
Log.e("Couldn't create class.", e);
}
}
return modelClasses;
}
private List<Class<? extends TypeSerializer>> loadSerializerList(String[] serializers) {
final List<Class<? extends TypeSerializer>> typeSerializers = new ArrayList<Class<? extends TypeSerializer>>();
final ClassLoader classLoader = mContext.getClass().getClassLoader();
for (String serializer : serializers) {
serializer = ensurePackageInName(serializer);
try {
Class serializerClass = Class.forName(serializer, false, classLoader);
if (ReflectionUtils.isTypeSerializer(serializerClass)) {
typeSerializers.add(serializerClass);
}
}
catch (ClassNotFoundException e) {
Log.e("Couldn't create class.", e);
}
}
return typeSerializers;
}
private String ensurePackageInName(String name) {
String packageName = mContext.getPackageName();
if (name.startsWith(packageName)) {
return name.trim();
}
return packageName + name.trim();
}
}
}
| false | true | public Configuration create() {
Configuration configuration = new Configuration(mContext);
configuration.mCacheSize = mCacheSize;
// Get database name from meta-data
if (mDatabaseName != null) {
configuration.mDatabaseName = mDatabaseName;
}
else {
configuration.mDatabaseName = getMetaDataDatabaseNameOrDefault();
}
// Get database version from meta-data
if (mDatabaseVersion != null) {
configuration.mDatabaseVersion = mDatabaseVersion;
}
else {
configuration.mDatabaseVersion = getMetaDataDatabaseVersionOrDefault();
}
// Get model classes from meta-data
if (mModelClasses != null) {
configuration.mModelClasses = mModelClasses;
}
else {
final String modelList = ReflectionUtils.getMetaData(mContext, AA_MODELS);
configuration.mModelClasses = loadModelList(modelList.split(","));
}
// Get type serializer classes from meta-data
if (mTypeSerializers != null) {
configuration.mTypeSerializers = mTypeSerializers;
}
else {
final String serializerList = ReflectionUtils.getMetaData(mContext, AA_SERIALIZERS);
configuration.mTypeSerializers = loadSerializerList(serializerList.split(","));
}
return configuration;
}
| public Configuration create() {
Configuration configuration = new Configuration(mContext);
configuration.mCacheSize = mCacheSize;
// Get database name from meta-data
if (mDatabaseName != null) {
configuration.mDatabaseName = mDatabaseName;
}
else {
configuration.mDatabaseName = getMetaDataDatabaseNameOrDefault();
}
// Get database version from meta-data
if (mDatabaseVersion != null) {
configuration.mDatabaseVersion = mDatabaseVersion;
}
else {
configuration.mDatabaseVersion = getMetaDataDatabaseVersionOrDefault();
}
// Get model classes from meta-data
if (mModelClasses != null) {
configuration.mModelClasses = mModelClasses;
}
else {
final String modelList = ReflectionUtils.getMetaData(mContext, AA_MODELS);
if (modelList != null) {
configuration.mModelClasses = loadModelList(modelList.split(","));
}
}
// Get type serializer classes from meta-data
if (mTypeSerializers != null) {
configuration.mTypeSerializers = mTypeSerializers;
}
else {
final String serializerList = ReflectionUtils.getMetaData(mContext, AA_SERIALIZERS);
if (serializerList != null) {
configuration.mTypeSerializers = loadSerializerList(serializerList.split(","));
}
}
return configuration;
}
|
diff --git a/main/src/com/google/refine/browsing/facets/RangeFacet.java b/main/src/com/google/refine/browsing/facets/RangeFacet.java
index 6b63cf11..d2c696a4 100644
--- a/main/src/com/google/refine/browsing/facets/RangeFacet.java
+++ b/main/src/com/google/refine/browsing/facets/RangeFacet.java
@@ -1,259 +1,261 @@
package com.google.refine.browsing.facets;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import com.google.refine.browsing.FilteredRecords;
import com.google.refine.browsing.FilteredRows;
import com.google.refine.browsing.RecordFilter;
import com.google.refine.browsing.RowFilter;
import com.google.refine.browsing.filters.AnyRowRecordFilter;
import com.google.refine.browsing.filters.ExpressionNumberComparisonRowFilter;
import com.google.refine.browsing.util.ExpressionBasedRowEvaluable;
import com.google.refine.browsing.util.ExpressionNumericValueBinner;
import com.google.refine.browsing.util.NumericBinIndex;
import com.google.refine.browsing.util.NumericBinRecordIndex;
import com.google.refine.browsing.util.NumericBinRowIndex;
import com.google.refine.browsing.util.RowEvaluable;
import com.google.refine.expr.Evaluable;
import com.google.refine.expr.MetaParser;
import com.google.refine.expr.ParsingException;
import com.google.refine.model.Column;
import com.google.refine.model.Project;
import com.google.refine.util.JSONUtilities;
public class RangeFacet implements Facet {
/*
* Configuration, from the client side
*/
protected String _name; // name of facet
protected String _expression; // expression to compute numeric value(s) per row
protected String _columnName; // column to base expression on, if any
protected double _from; // the numeric selection
protected double _to;
protected boolean _selectNumeric; // whether the numeric selection applies, default true
protected boolean _selectNonNumeric;
protected boolean _selectBlank;
protected boolean _selectError;
/*
* Derived configuration data
*/
protected int _cellIndex;
protected Evaluable _eval;
protected String _errorMessage;
protected boolean _selected; // false if we're certain that all rows will match
// and there isn't any filtering to do
/*
* Computed data, to return to the client side
*/
protected double _min;
protected double _max;
protected double _step;
protected int[] _baseBins;
protected int[] _bins;
protected int _baseNumericCount;
protected int _baseNonNumericCount;
protected int _baseBlankCount;
protected int _baseErrorCount;
protected int _numericCount;
protected int _nonNumericCount;
protected int _blankCount;
protected int _errorCount;
public RangeFacet() {
}
protected static final String MIN = "min";
protected static final String MAX = "max";
protected static final String TO = "to";
protected static final String FROM = "from";
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("name"); writer.value(_name);
writer.key("expression"); writer.value(_expression);
writer.key("columnName"); writer.value(_columnName);
if (_errorMessage != null) {
writer.key("error"); writer.value(_errorMessage);
} else {
if (!Double.isInfinite(_min) && !Double.isInfinite(_max)) {
writer.key(MIN); writer.value(_min);
writer.key(MAX); writer.value(_max);
writer.key("step"); writer.value(_step);
writer.key("bins"); writer.array();
for (int b : _bins) {
writer.value(b);
}
writer.endArray();
writer.key("baseBins"); writer.array();
for (int b : _baseBins) {
writer.value(b);
}
writer.endArray();
writer.key(FROM); writer.value(_from);
writer.key(TO); writer.value(_to);
+ } else {
+ writer.key("error"); writer.value("No numeric value present.");
}
writer.key("baseNumericCount"); writer.value(_baseNumericCount);
writer.key("baseNonNumericCount"); writer.value(_baseNonNumericCount);
writer.key("baseBlankCount"); writer.value(_baseBlankCount);
writer.key("baseErrorCount"); writer.value(_baseErrorCount);
writer.key("numericCount"); writer.value(_numericCount);
writer.key("nonNumericCount"); writer.value(_nonNumericCount);
writer.key("blankCount"); writer.value(_blankCount);
writer.key("errorCount"); writer.value(_errorCount);
}
writer.endObject();
}
public void initializeFromJSON(Project project, JSONObject o) throws Exception {
_name = o.getString("name");
_expression = o.getString("expression");
_columnName = o.getString("columnName");
if (_columnName.length() > 0) {
Column column = project.columnModel.getColumnByName(_columnName);
if (column != null) {
_cellIndex = column.getCellIndex();
} else {
_errorMessage = "No column named " + _columnName;
}
} else {
_cellIndex = -1;
}
try {
_eval = MetaParser.parse(_expression);
} catch (ParsingException e) {
_errorMessage = e.getMessage();
}
if (o.has(FROM) || o.has(TO)) {
_from = o.has(FROM) ? o.getDouble(FROM) : _min;
_to = o.has(TO) ? o.getDouble(TO) : _max;
_selected = true;
}
_selectNumeric = JSONUtilities.getBoolean(o, "selectNumeric", true);
_selectNonNumeric = JSONUtilities.getBoolean(o, "selectNonNumeric", true);
_selectBlank = JSONUtilities.getBoolean(o, "selectBlank", true);
_selectError = JSONUtilities.getBoolean(o, "selectError", true);
if (!_selectNumeric || !_selectNonNumeric || !_selectBlank || !_selectError) {
_selected = true;
}
}
public RowFilter getRowFilter(Project project) {
if (_eval != null && _errorMessage == null && _selected) {
return new ExpressionNumberComparisonRowFilter(
getRowEvaluable(project), _selectNumeric, _selectNonNumeric, _selectBlank, _selectError) {
protected boolean checkValue(double d) {
return d >= _from && d < _to;
};
};
} else {
return null;
}
}
@Override
public RecordFilter getRecordFilter(Project project) {
RowFilter rowFilter = getRowFilter(project);
return rowFilter == null ? null : new AnyRowRecordFilter(rowFilter);
}
public void computeChoices(Project project, FilteredRows filteredRows) {
if (_eval != null && _errorMessage == null) {
RowEvaluable rowEvaluable = getRowEvaluable(project);
Column column = project.columnModel.getColumnByCellIndex(_cellIndex);
String key = "numeric-bin:row-based:" + _expression;
NumericBinIndex index = (NumericBinIndex) column.getPrecompute(key);
if (index == null) {
index = new NumericBinRowIndex(project, rowEvaluable);
column.setPrecompute(key, index);
}
retrieveDataFromBaseBinIndex(index);
ExpressionNumericValueBinner binner =
new ExpressionNumericValueBinner(rowEvaluable, index);
filteredRows.accept(project, binner);
retrieveDataFromBinner(binner);
}
}
public void computeChoices(Project project, FilteredRecords filteredRecords) {
if (_eval != null && _errorMessage == null) {
RowEvaluable rowEvaluable = getRowEvaluable(project);
Column column = project.columnModel.getColumnByCellIndex(_cellIndex);
String key = "numeric-bin:record-based:" + _expression;
NumericBinIndex index = (NumericBinIndex) column.getPrecompute(key);
if (index == null) {
index = new NumericBinRecordIndex(project, rowEvaluable);
column.setPrecompute(key, index);
}
retrieveDataFromBaseBinIndex(index);
ExpressionNumericValueBinner binner =
new ExpressionNumericValueBinner(rowEvaluable, index);
filteredRecords.accept(project, binner);
retrieveDataFromBinner(binner);
}
}
protected RowEvaluable getRowEvaluable(Project project) {
return new ExpressionBasedRowEvaluable(_columnName, _cellIndex, _eval);
}
protected void retrieveDataFromBaseBinIndex(NumericBinIndex index) {
_min = index.getMin();
_max = index.getMax();
_step = index.getStep();
_baseBins = index.getBins();
_baseNumericCount = index.getNumericRowCount();
_baseNonNumericCount = index.getNonNumericRowCount();
_baseBlankCount = index.getBlankRowCount();
_baseErrorCount = index.getErrorRowCount();
if (_selected) {
_from = Math.max(_from, _min);
_to = Math.min(_to, _max);
} else {
_from = _min;
_to = _max;
}
}
protected void retrieveDataFromBinner(ExpressionNumericValueBinner binner) {
_bins = binner.bins;
_numericCount = binner.numericCount;
_nonNumericCount = binner.nonNumericCount;
_blankCount = binner.blankCount;
_errorCount = binner.errorCount;
}
}
| true | true | public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("name"); writer.value(_name);
writer.key("expression"); writer.value(_expression);
writer.key("columnName"); writer.value(_columnName);
if (_errorMessage != null) {
writer.key("error"); writer.value(_errorMessage);
} else {
if (!Double.isInfinite(_min) && !Double.isInfinite(_max)) {
writer.key(MIN); writer.value(_min);
writer.key(MAX); writer.value(_max);
writer.key("step"); writer.value(_step);
writer.key("bins"); writer.array();
for (int b : _bins) {
writer.value(b);
}
writer.endArray();
writer.key("baseBins"); writer.array();
for (int b : _baseBins) {
writer.value(b);
}
writer.endArray();
writer.key(FROM); writer.value(_from);
writer.key(TO); writer.value(_to);
}
writer.key("baseNumericCount"); writer.value(_baseNumericCount);
writer.key("baseNonNumericCount"); writer.value(_baseNonNumericCount);
writer.key("baseBlankCount"); writer.value(_baseBlankCount);
writer.key("baseErrorCount"); writer.value(_baseErrorCount);
writer.key("numericCount"); writer.value(_numericCount);
writer.key("nonNumericCount"); writer.value(_nonNumericCount);
writer.key("blankCount"); writer.value(_blankCount);
writer.key("errorCount"); writer.value(_errorCount);
}
writer.endObject();
}
| public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("name"); writer.value(_name);
writer.key("expression"); writer.value(_expression);
writer.key("columnName"); writer.value(_columnName);
if (_errorMessage != null) {
writer.key("error"); writer.value(_errorMessage);
} else {
if (!Double.isInfinite(_min) && !Double.isInfinite(_max)) {
writer.key(MIN); writer.value(_min);
writer.key(MAX); writer.value(_max);
writer.key("step"); writer.value(_step);
writer.key("bins"); writer.array();
for (int b : _bins) {
writer.value(b);
}
writer.endArray();
writer.key("baseBins"); writer.array();
for (int b : _baseBins) {
writer.value(b);
}
writer.endArray();
writer.key(FROM); writer.value(_from);
writer.key(TO); writer.value(_to);
} else {
writer.key("error"); writer.value("No numeric value present.");
}
writer.key("baseNumericCount"); writer.value(_baseNumericCount);
writer.key("baseNonNumericCount"); writer.value(_baseNonNumericCount);
writer.key("baseBlankCount"); writer.value(_baseBlankCount);
writer.key("baseErrorCount"); writer.value(_baseErrorCount);
writer.key("numericCount"); writer.value(_numericCount);
writer.key("nonNumericCount"); writer.value(_nonNumericCount);
writer.key("blankCount"); writer.value(_blankCount);
writer.key("errorCount"); writer.value(_errorCount);
}
writer.endObject();
}
|
diff --git a/hazelcast/src/test/java/com/hazelcast/queue/QueueListenerTest.java b/hazelcast/src/test/java/com/hazelcast/queue/QueueListenerTest.java
index c2e3879930..a9e191eb22 100644
--- a/hazelcast/src/test/java/com/hazelcast/queue/QueueListenerTest.java
+++ b/hazelcast/src/test/java/com/hazelcast/queue/QueueListenerTest.java
@@ -1,91 +1,91 @@
/*
* Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
*
* 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.hazelcast.queue;
import com.hazelcast.config.Config;
import com.hazelcast.config.ItemListenerConfig;
import com.hazelcast.config.QueueConfig;
import com.hazelcast.core.*;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static junit.framework.Assert.assertTrue;
@RunWith(HazelcastParallelClassRunner.class)
@Category(QuickTest.class)
public class QueueListenerTest extends HazelcastTestSupport {
@Test
- public void testItemListener_addedToQueueConfig() throws InterruptedException {
+ public void testItemListener_addedToQueueConfig_Issue366() throws InterruptedException {
int count=2000;
ItemListenerConfig itemListenerConfig = new ItemListenerConfig();
itemListenerConfig.setImplementation(new SimpleItemListener(count));
itemListenerConfig.setIncludeValue(true);
QueueConfig qConfig = new QueueConfig();
qConfig.setName("Q");
qConfig.addItemListenerConfig(itemListenerConfig);
Config cfg = new Config();
cfg.addQueueConfig(qConfig);
HazelcastInstance node1 = Hazelcast.newHazelcastInstance(cfg);
for(int i=0; i<count/2; i++) {
node1.getQueue("Q").put(i);
}
HazelcastInstance node2 = Hazelcast.newHazelcastInstance(cfg);
for(int i=0; i<count/4; i++) {
node1.getQueue("Q").put(i);
}
List<ItemListenerConfig> configs = qConfig.getItemListenerConfigs();
SimpleItemListener simpleItemListener = (SimpleItemListener) configs.get(0).getImplementation();
assertTrue(simpleItemListener.added.await(10, TimeUnit.SECONDS));
}
private static class SimpleItemListener implements ItemListener {
public CountDownLatch added;
public SimpleItemListener(int CountDown){
added = new CountDownLatch(CountDown);
}
public void itemAdded(ItemEvent itemEvent) {
added.countDown();
}
public void itemRemoved(ItemEvent itemEvent) {
}
}
}
| true | true | public void testItemListener_addedToQueueConfig() throws InterruptedException {
int count=2000;
ItemListenerConfig itemListenerConfig = new ItemListenerConfig();
itemListenerConfig.setImplementation(new SimpleItemListener(count));
itemListenerConfig.setIncludeValue(true);
QueueConfig qConfig = new QueueConfig();
qConfig.setName("Q");
qConfig.addItemListenerConfig(itemListenerConfig);
Config cfg = new Config();
cfg.addQueueConfig(qConfig);
HazelcastInstance node1 = Hazelcast.newHazelcastInstance(cfg);
for(int i=0; i<count/2; i++) {
node1.getQueue("Q").put(i);
}
HazelcastInstance node2 = Hazelcast.newHazelcastInstance(cfg);
for(int i=0; i<count/4; i++) {
node1.getQueue("Q").put(i);
}
List<ItemListenerConfig> configs = qConfig.getItemListenerConfigs();
SimpleItemListener simpleItemListener = (SimpleItemListener) configs.get(0).getImplementation();
assertTrue(simpleItemListener.added.await(10, TimeUnit.SECONDS));
}
| public void testItemListener_addedToQueueConfig_Issue366() throws InterruptedException {
int count=2000;
ItemListenerConfig itemListenerConfig = new ItemListenerConfig();
itemListenerConfig.setImplementation(new SimpleItemListener(count));
itemListenerConfig.setIncludeValue(true);
QueueConfig qConfig = new QueueConfig();
qConfig.setName("Q");
qConfig.addItemListenerConfig(itemListenerConfig);
Config cfg = new Config();
cfg.addQueueConfig(qConfig);
HazelcastInstance node1 = Hazelcast.newHazelcastInstance(cfg);
for(int i=0; i<count/2; i++) {
node1.getQueue("Q").put(i);
}
HazelcastInstance node2 = Hazelcast.newHazelcastInstance(cfg);
for(int i=0; i<count/4; i++) {
node1.getQueue("Q").put(i);
}
List<ItemListenerConfig> configs = qConfig.getItemListenerConfigs();
SimpleItemListener simpleItemListener = (SimpleItemListener) configs.get(0).getImplementation();
assertTrue(simpleItemListener.added.await(10, TimeUnit.SECONDS));
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/editors/AbstractTaskEditorPage.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/editors/AbstractTaskEditorPage.java
index ed8af6515..468c78f15 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/editors/AbstractTaskEditorPage.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/tasks/ui/editors/AbstractTaskEditorPage.java
@@ -1,1588 +1,1589 @@
/*******************************************************************************
* Copyright (c) 2004, 2009 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
* David Green - fixes for bug 237503
* Frank Becker - fixes for bug 252300
*******************************************************************************/
package org.eclipse.mylyn.tasks.ui.editors;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonFormUtil;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonTextSupport;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonUiUtil;
import org.eclipse.mylyn.internal.provisional.commons.ui.GradientCanvas;
import org.eclipse.mylyn.internal.tasks.core.AbstractTaskContainer;
import org.eclipse.mylyn.internal.tasks.core.ITaskListRunnable;
import org.eclipse.mylyn.internal.tasks.core.data.ITaskDataManagerListener;
import org.eclipse.mylyn.internal.tasks.core.data.TaskDataManagerEvent;
import org.eclipse.mylyn.internal.tasks.ui.TasksUiPlugin;
import org.eclipse.mylyn.internal.tasks.ui.actions.ClearOutgoingAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.DeleteTaskEditorAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.NewSubTaskAction;
import org.eclipse.mylyn.internal.tasks.ui.actions.SynchronizeEditorAction;
import org.eclipse.mylyn.internal.tasks.ui.editors.EditorUtil;
import org.eclipse.mylyn.internal.tasks.ui.editors.FocusTracker;
import org.eclipse.mylyn.internal.tasks.ui.editors.Messages;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskAttachmentDropListener;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorActionContributor;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorActionPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorAttachmentPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorAttributePart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorCommentPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorContributionExtensionReader;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorDescriptionPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorNewCommentPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorOutlineNode;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorOutlinePage;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorPeoplePart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorPlanningPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorRichTextPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskEditorSummaryPart;
import org.eclipse.mylyn.internal.tasks.ui.editors.TaskMigrator;
import org.eclipse.mylyn.internal.tasks.ui.editors.ToolBarButtonContribution;
import org.eclipse.mylyn.internal.tasks.ui.util.AttachmentUtil;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiInternal;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.IRepositoryElement;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.RepositoryStatus;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.ITask.SynchronizationState;
import org.eclipse.mylyn.tasks.core.data.ITaskDataWorkingCopy;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskData;
import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
import org.eclipse.mylyn.tasks.core.data.TaskDataModelEvent;
import org.eclipse.mylyn.tasks.core.data.TaskDataModelListener;
import org.eclipse.mylyn.tasks.core.sync.SubmitJob;
import org.eclipse.mylyn.tasks.core.sync.SubmitJobEvent;
import org.eclipse.mylyn.tasks.core.sync.SubmitJobListener;
import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.TasksUiImages;
import org.eclipse.mylyn.tasks.ui.TasksUiUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.FormColors;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.IFormPart;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.editor.FormPage;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
/**
* Extend to provide a task editor page.
*
* @author Mik Kersten
* @author Rob Elves
* @author Steffen Pingel
* @since 3.0
*/
public abstract class AbstractTaskEditorPage extends TaskFormPage implements ISelectionProvider,
ISelectionChangedListener {
/**
* Causes the form page to reflow on resize.
*/
private final class ParentResizeHandler implements Listener {
private int generation;
public void handleEvent(Event event) {
++generation;
Display.getCurrent().timerExec(300, new Runnable() {
int scheduledGeneration = generation;
public void run() {
if (getManagedForm().getForm().isDisposed()) {
return;
}
// only reflow if this is the latest generation to prevent
// unnecessary reflows while the form is being resized
if (scheduledGeneration == generation) {
getManagedForm().reflow(true);
}
}
});
}
}
private class SubmitTaskJobListener extends SubmitJobListener {
private final boolean attachContext;
public SubmitTaskJobListener(boolean attachContext) {
this.attachContext = attachContext;
}
@Override
public void done(SubmitJobEvent event) {
final SubmitJob job = event.getJob();
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
private void addTask(ITask newTask) {
AbstractTaskContainer parent = null;
AbstractTaskEditorPart actionPart = getPart(ID_PART_ACTIONS);
if (actionPart instanceof TaskEditorActionPart) {
parent = ((TaskEditorActionPart) actionPart).getCategory();
}
TasksUiInternal.getTaskList().addTask(newTask, parent);
}
public void run() {
try {
if (job.getStatus() == null) {
TasksUiInternal.synchronizeRepository(getTaskRepository(), false);
if (job.getTask().equals(getTask())) {
refreshFormContent();
} else {
ITask oldTask = getTask();
ITask newTask = job.getTask();
addTask(newTask);
TaskMigrator migrator = new TaskMigrator(oldTask);
migrator.setDelete(true);
migrator.setEditor(getTaskEditor());
migrator.execute(newTask);
}
}
handleTaskSubmitted(new SubmitJobEvent(job));
} finally {
showEditorBusy(false);
}
}
});
}
@Override
public void taskSubmitted(SubmitJobEvent event, IProgressMonitor monitor) throws CoreException {
if (!getModel().getTaskData().isNew() && attachContext) {
AttachmentUtil.postContext(connector, getModel().getTaskRepository(), task, "", null, monitor); //$NON-NLS-1$
}
}
@Override
public void taskSynchronized(SubmitJobEvent event, IProgressMonitor monitor) {
}
}
// private class TaskListChangeListener extends TaskListChangeAdapter {
// @Override
// public void containersChanged(Set<TaskContainerDelta> containers) {
// if (refreshDisabled) {
// return;
// }
// ITask taskToRefresh = null;
// for (TaskContainerDelta taskContainerDelta : containers) {
// if (task.equals(taskContainerDelta.getElement())) {
// if (taskContainerDelta.getKind().equals(TaskContainerDelta.Kind.CONTENT)
// && !taskContainerDelta.isTransient()) {
// taskToRefresh = (ITask) taskContainerDelta.getElement();
// break;
// }
// }
// }
// if (taskToRefresh != null) {
// PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
// public void run() {
// if (!isDirty() && task.getSynchronizationState() == SynchronizationState.SYNCHRONIZED) {
// // automatically refresh if the user has not made any changes and there is no chance of missing incomings
// refreshFormContent();
// } else {
// getTaskEditor().setMessage("Task has incoming changes", IMessageProvider.WARNING,
// new HyperlinkAdapter() {
// @Override
// public void linkActivated(HyperlinkEvent e) {
// refreshFormContent();
// }
// });
// setSubmitEnabled(false);
// }
// }
// });
// }
// }
// }
private final ITaskDataManagerListener TASK_DATA_LISTENER = new ITaskDataManagerListener() {
public void taskDataUpdated(final TaskDataManagerEvent event) {
ITask task = event.getTask();
if (task.equals(AbstractTaskEditorPage.this.getTask()) && event.getTaskDataUpdated()) {
refresh(task);
}
}
private void refresh(final ITask task) {
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
public void run() {
if (refreshDisabled) {
return;
}
if (!isDirty() && task.getSynchronizationState() == SynchronizationState.SYNCHRONIZED) {
// automatically refresh if the user has not made any changes and there is no chance of missing incomings
refreshFormContent();
} else {
getTaskEditor().setMessage(Messages.AbstractTaskEditorPage_Task_has_incoming_changes,
IMessageProvider.WARNING, new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
refreshFormContent();
}
});
setSubmitEnabled(false);
}
}
});
}
public void editsDiscarded(TaskDataManagerEvent event) {
if (event.getTask().equals(AbstractTaskEditorPage.this.getTask())) {
refresh(event.getTask());
}
}
};
private static final String ERROR_NOCONNECTIVITY = Messages.AbstractTaskEditorPage_Unable_to_submit_at_this_time;
public static final String ID_PART_ACTIONS = "org.eclipse.mylyn.tasks.ui.editors.parts.actions"; //$NON-NLS-1$
public static final String ID_PART_ATTACHMENTS = "org.eclipse.mylyn.tasks.ui.editors.parts.attachments"; //$NON-NLS-1$
public static final String ID_PART_ATTRIBUTES = "org.eclipse.mylyn.tasks.ui.editors.parts.attributes"; //$NON-NLS-1$
public static final String ID_PART_COMMENTS = "org.eclipse.mylyn.tasks.ui.editors.parts.comments"; //$NON-NLS-1$
public static final String ID_PART_DESCRIPTION = "org.eclipse.mylyn.tasks.ui.editors.parts.descriptions"; //$NON-NLS-1$
public static final String ID_PART_NEW_COMMENT = "org.eclipse.mylyn.tasks.ui.editors.parts.newComment"; //$NON-NLS-1$
public static final String ID_PART_PEOPLE = "org.eclipse.mylyn.tasks.ui.editors.parts.people"; //$NON-NLS-1$
public static final String ID_PART_PLANNING = "org.eclipse.mylyn.tasks.ui.editors.parts.planning"; //$NON-NLS-1$
public static final String ID_PART_SUMMARY = "org.eclipse.mylyn.tasks.ui.editors.parts.summary"; //$NON-NLS-1$
public static final String PATH_ACTIONS = "actions"; //$NON-NLS-1$
public static final String PATH_ATTACHMENTS = "attachments"; //$NON-NLS-1$
public static final String PATH_ATTRIBUTES = "attributes"; //$NON-NLS-1$
public static final String PATH_COMMENTS = "comments"; //$NON-NLS-1$
public static final String PATH_HEADER = "header"; //$NON-NLS-1$
public static final String PATH_PEOPLE = "people"; //$NON-NLS-1$
public static final String PATH_PLANNING = "planning"; //$NON-NLS-1$
// private static final String ID_POPUP_MENU = "org.eclipse.mylyn.tasks.ui.editor.menu.page";
private AttributeEditorFactory attributeEditorFactory;
private AttributeEditorToolkit attributeEditorToolkit;
private AbstractRepositoryConnector connector;
private final String connectorKind;
private StructuredSelection defaultSelection;
private Composite editorComposite;
private ScrolledForm form;
private boolean busy;
private ISelection lastSelection;
private TaskDataModel model;
private boolean needsAddToCategory;
private boolean reflow;
private volatile boolean refreshDisabled;
private final ListenerList selectionChangedListeners;
private SynchronizeEditorAction synchronizeEditorAction;
private ITask task;
private TaskData taskData;
// private ITaskListChangeListener taskListChangeListener;
private FormToolkit toolkit;
private TaskEditorOutlinePage outlinePage;
private TaskAttachmentDropListener defaultDropListener;
private CommonTextSupport textSupport;
private Composite partControl;
private GradientCanvas footerComposite;
private boolean needsFooter;
private Button submitButton;
private boolean submitEnabled;
private boolean needsSubmit;
private boolean needsSubmitButton;
private boolean needsPrivateSection;
private FocusTracker focusTracker;
/**
* @since 3.1
*/
public AbstractTaskEditorPage(TaskEditor editor, String id, String label, String connectorKind) {
super(editor, id, label);
Assert.isNotNull(connectorKind);
this.connectorKind = connectorKind;
this.reflow = true;
this.selectionChangedListeners = new ListenerList();
this.submitEnabled = true;
this.needsSubmit = true;
}
public AbstractTaskEditorPage(TaskEditor editor, String connectorKind) {
this(editor, "id", "label", connectorKind); //$NON-NLS-1$ //$NON-NLS-2$
}
/**
* @since 3.1
* @see FormPage#getEditor()
*/
@Override
public TaskEditor getEditor() {
return (TaskEditor) super.getEditor();
}
public void addSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.add(listener);
}
public void appendTextToNewComment(String text) {
AbstractTaskEditorPart newCommentPart = getPart(ID_PART_NEW_COMMENT);
if (newCommentPart instanceof TaskEditorRichTextPart) {
((TaskEditorRichTextPart) newCommentPart).appendText(text);
newCommentPart.setFocus();
}
}
public boolean canPerformAction(String actionId) {
return CommonTextSupport.canPerformAction(actionId, EditorUtil.getFocusControl(this));
}
public void close() {
if (Display.getCurrent() != null) {
getSite().getPage().closeEditor(getTaskEditor(), false);
} else {
// TODO consider removing asyncExec()
Display activeDisplay = getSite().getShell().getDisplay();
activeDisplay.asyncExec(new Runnable() {
public void run() {
if (getSite() != null && getSite().getPage() != null && !getManagedForm().getForm().isDisposed()) {
if (getTaskEditor() != null) {
getSite().getPage().closeEditor(getTaskEditor(), false);
} else {
getSite().getPage().closeEditor(AbstractTaskEditorPage.this, false);
}
}
}
});
}
}
protected AttributeEditorFactory createAttributeEditorFactory() {
return new AttributeEditorFactory(getModel(), getTaskRepository(), getEditorSite());
}
AttributeEditorToolkit createAttributeEditorToolkit() {
return new AttributeEditorToolkit(textSupport);
}
@Override
public void createPartControl(Composite parent) {
parent.addListener(SWT.Resize, new ParentResizeHandler());
if (needsFooter()) {
partControl = getEditor().getToolkit().createComposite(parent);
GridLayout partControlLayout = new GridLayout(1, false);
partControlLayout.marginWidth = 0;
partControlLayout.marginHeight = 0;
partControlLayout.verticalSpacing = 0;
partControl.setLayout(partControlLayout);
super.createPartControl(partControl);
getManagedForm().getForm().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
footerComposite = new GradientCanvas(partControl, SWT.NONE);
footerComposite.setSeparatorVisible(true);
footerComposite.setSeparatorAlignment(SWT.TOP);
GridLayout headLayout = new GridLayout();
headLayout.marginHeight = 0;
headLayout.marginWidth = 0;
headLayout.horizontalSpacing = 0;
headLayout.verticalSpacing = 0;
headLayout.numColumns = 1;
footerComposite.setLayout(headLayout);
footerComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
FormColors colors = getEditor().getToolkit().getColors();
Color top = colors.getColor(IFormColors.H_GRADIENT_END);
Color bottom = colors.getColor(IFormColors.H_GRADIENT_START);
footerComposite.setBackgroundGradient(new Color[] { bottom, top }, new int[] { 100 }, true);
footerComposite.putColor(IFormColors.H_BOTTOM_KEYLINE1, colors.getColor(IFormColors.H_BOTTOM_KEYLINE1));
footerComposite.putColor(IFormColors.H_BOTTOM_KEYLINE2, colors.getColor(IFormColors.H_BOTTOM_KEYLINE2));
footerComposite.putColor(IFormColors.H_HOVER_LIGHT, colors.getColor(IFormColors.H_HOVER_LIGHT));
footerComposite.putColor(IFormColors.H_HOVER_FULL, colors.getColor(IFormColors.H_HOVER_FULL));
footerComposite.putColor(IFormColors.TB_TOGGLE, colors.getColor(IFormColors.TB_TOGGLE));
footerComposite.putColor(IFormColors.TB_TOGGLE_HOVER, colors.getColor(IFormColors.TB_TOGGLE_HOVER));
footerComposite.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
createFooterContent(footerComposite);
} else {
super.createPartControl(parent);
}
}
@Override
protected void createFormContent(final IManagedForm managedForm) {
super.createFormContent(managedForm);
form = managedForm.getForm();
toolkit = managedForm.getToolkit();
registerDefaultDropListener(form);
CommonFormUtil.disableScrollingOnFocus(form);
try {
setReflow(false);
editorComposite = form.getBody();
// TODO consider using TableWrapLayout, it makes resizing much faster
GridLayout editorLayout = new GridLayout();
editorLayout.verticalSpacing = 0;
editorComposite.setLayout(editorLayout);
//form.setData("focusScrolling", Boolean.FALSE);
// menuManager = new MenuManager();
// menuManager.setRemoveAllWhenShown(true);
// getEditorSite().registerContextMenu(ID_POPUP_MENU, menuManager, this, true);
// editorComposite.setMenu(menuManager.createContextMenu(editorComposite));
editorComposite.setMenu(getTaskEditor().getMenu());
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(getConnectorKind());
if (connectorUi == null) {
getTaskEditor().setMessage(Messages.AbstractTaskEditorPage_Synchronize_to_update_editor_contents,
IMessageProvider.INFORMATION, new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
refreshFormContent();
}
});
}
if (taskData != null) {
createFormContentInternal();
}
updateHeaderMessage();
} finally {
setReflow(true);
// if the editor is restored as part of workbench startup then we must reflow() asynchronously
// otherwise the editor layout is incorrect
boolean reflowRequired = calculateReflowRequired(form);
if (reflowRequired) {
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
// this fixes a problem with layout that occurs when an editor
// is restored before the workbench is fully initialized
reflow();
}
});
}
}
}
private boolean calculateReflowRequired(ScrolledForm form) {
Composite stopComposite = getEditor().getEditorParent().getParent().getParent();
Composite composite = form.getParent();
while (composite != null) {
Rectangle clientArea = composite.getClientArea();
if (clientArea.width > 1) {
return false;
}
if (composite == stopComposite) {
return true;
}
composite = composite.getParent();
}
return true;
}
private void createFormContentInternal() {
// end life-cycle of previous editor controls
if (attributeEditorToolkit != null) {
attributeEditorToolkit.dispose();
}
// start life-cycle of previous editor controls
if (attributeEditorFactory == null) {
attributeEditorFactory = createAttributeEditorFactory();
Assert.isNotNull(attributeEditorFactory);
}
attributeEditorToolkit = createAttributeEditorToolkit();
Assert.isNotNull(attributeEditorToolkit);
attributeEditorToolkit.setMenu(editorComposite.getMenu());
attributeEditorFactory.setEditorToolkit(attributeEditorToolkit);
createParts();
focusTracker = new FocusTracker();
focusTracker.track(editorComposite);
// AbstractTaskEditorPart summaryPart = getPart(ID_PART_SUMMARY);
// if (summaryPart != null) {
// lastFocusControl = summaryPart.getControl();
// }
}
protected TaskDataModel createModel(TaskEditorInput input) throws CoreException {
ITaskDataWorkingCopy taskDataState;
try {
taskDataState = TasksUi.getTaskDataManager().getWorkingCopy(task);
} catch (OperationCanceledException e) {
// XXX retry once to work around bug 235479
taskDataState = TasksUi.getTaskDataManager().getWorkingCopy(task);
}
TaskRepository taskRepository = TasksUi.getRepositoryManager().getRepository(taskDataState.getConnectorKind(),
taskDataState.getRepositoryUrl());
return new TaskDataModel(taskRepository, input.getTask(), taskDataState);
}
/**
* To suppress a section, just remove its descriptor from the list. To add your own section in a specific order on
* the page, use the path value for where you want it to appear (your descriptor will appear after previously added
* descriptors with the same path), and add it to the descriptors list in your override of this method.
*/
protected Set<TaskEditorPartDescriptor> createPartDescriptors() {
Set<TaskEditorPartDescriptor> descriptors = new LinkedHashSet<TaskEditorPartDescriptor>();
descriptors.add(new TaskEditorPartDescriptor(ID_PART_SUMMARY) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorSummaryPart();
}
}.setPath(PATH_HEADER));
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ATTRIBUTES) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorAttributePart();
}
}.setPath(PATH_ATTRIBUTES));
- if (!taskData.isNew() && connector.getTaskAttachmentHandler() != null) {
+ if (!taskData.isNew() && connector.getTaskAttachmentHandler() != null
+ && (AttachmentUtil.canDownloadAttachment(task) || AttachmentUtil.canUploadAttachment(task))) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ATTACHMENTS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorAttachmentPart();
}
}.setPath(PATH_ATTACHMENTS));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_DESCRIPTION) {
@Override
public AbstractTaskEditorPart createPart() {
TaskEditorDescriptionPart part = new TaskEditorDescriptionPart();
if (getModel().getTaskData().isNew()) {
part.setExpandVertically(true);
part.setSectionStyle(ExpandableComposite.TITLE_BAR | ExpandableComposite.EXPANDED);
}
return part;
}
}.setPath(PATH_COMMENTS));
if (!taskData.isNew()) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_COMMENTS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorCommentPart();
}
}.setPath(PATH_COMMENTS));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_NEW_COMMENT) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorNewCommentPart();
}
}.setPath(PATH_COMMENTS));
if (needsPrivateSection() || taskData.isNew()) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_PLANNING) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorPlanningPart();
}
}.setPath(PATH_PLANNING));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ACTIONS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorActionPart();
}
}.setPath(PATH_ACTIONS));
descriptors.add(new TaskEditorPartDescriptor(ID_PART_PEOPLE) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorPeoplePart();
}
}.setPath(PATH_PEOPLE));
descriptors.addAll(getContributionPartDescriptors());
return descriptors;
}
private Collection<TaskEditorPartDescriptor> getContributionPartDescriptors() {
return TaskEditorContributionExtensionReader.getRepositoryEditorContributions();
}
protected void createParts() {
List<TaskEditorPartDescriptor> descriptors = new LinkedList<TaskEditorPartDescriptor>(createPartDescriptors());
// single column
createParts(PATH_HEADER, editorComposite, descriptors);
createParts(PATH_ATTRIBUTES, editorComposite, descriptors);
createParts(PATH_PLANNING, editorComposite, descriptors);
createParts(PATH_ATTACHMENTS, editorComposite, descriptors);
createParts(PATH_COMMENTS, editorComposite, descriptors);
// two column
Composite bottomComposite = toolkit.createComposite(editorComposite);
bottomComposite.setLayout(GridLayoutFactory.fillDefaults().numColumns(2).create());
GridDataFactory.fillDefaults().grab(true, false).applyTo(bottomComposite);
createParts(PATH_ACTIONS, bottomComposite, descriptors);
createParts(PATH_PEOPLE, bottomComposite, descriptors);
bottomComposite.pack(true);
}
private void createParts(String path, final Composite parent, Collection<TaskEditorPartDescriptor> descriptors) {
for (Iterator<TaskEditorPartDescriptor> it = descriptors.iterator(); it.hasNext();) {
final TaskEditorPartDescriptor descriptor = it.next();
if (path == null || path.equals(descriptor.getPath())) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Error creating task editor part: \"" + descriptor.getId() + "\"", e)); //$NON-NLS-1$ //$NON-NLS-2$
}
public void run() throws Exception {
AbstractTaskEditorPart part = descriptor.createPart();
part.setPartId(descriptor.getId());
initializePart(parent, part);
}
});
it.remove();
}
}
}
@Override
public void dispose() {
if (textSupport != null) {
textSupport.dispose();
}
if (attributeEditorToolkit != null) {
attributeEditorToolkit.dispose();
}
TasksUiPlugin.getTaskDataManager().removeListener(TASK_DATA_LISTENER);
super.dispose();
}
public void doAction(String actionId) {
CommonTextSupport.doAction(actionId, EditorUtil.getFocusControl(this));
}
@Override
public void doSave(IProgressMonitor monitor) {
if (!isDirty()) {
return;
}
getManagedForm().commit(true);
if (model.isDirty()) {
try {
model.save(monitor);
} catch (final CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Error saving task", e)); //$NON-NLS-1$
getTaskEditor().setMessage(Messages.AbstractTaskEditorPage_Could_not_save_task, IMessageProvider.ERROR,
new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent event) {
TasksUiInternal.displayStatus(Messages.AbstractTaskEditorPage_Save_failed,
e.getStatus());
}
});
}
}
// update the summary of unsubmitted repository tasks
if (getTask().getSynchronizationState() == SynchronizationState.OUTGOING_NEW) {
final String summary = connector.getTaskMapping(model.getTaskData()).getSummary();
try {
TasksUiPlugin.getTaskList().run(new ITaskListRunnable() {
public void execute(IProgressMonitor monitor) throws CoreException {
task.setSummary(summary);
}
});
TasksUiPlugin.getTaskList().notifyElementChanged(task);
} catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Failed to set summary for task \"" + task + "\"", e)); //$NON-NLS-1$ //$NON-NLS-2$
}
}
updateHeaderMessage();
getManagedForm().dirtyStateChanged();
getTaskEditor().updateHeaderToolBar();
}
@Override
public void doSaveAs() {
throw new UnsupportedOperationException();
}
public void doSubmit() {
if (!submitEnabled || !needsSubmit()) {
return;
}
try {
showEditorBusy(true);
doSave(new NullProgressMonitor());
SubmitJob submitJob = TasksUiInternal.getJobFactory().createSubmitTaskJob(connector,
getModel().getTaskRepository(), task, getModel().getTaskData(),
getModel().getChangedOldAttributes());
submitJob.addSubmitJobListener(new SubmitTaskJobListener(getAttachContext()));
submitJob.schedule();
} catch (RuntimeException e) {
showEditorBusy(false);
throw e;
}
}
/**
* Override for customizing the tool bar.
*/
@Override
public void fillToolBar(IToolBarManager toolBarManager) {
final TaskRepository taskRepository = (model != null) ? getModel().getTaskRepository() : null;
if (taskData == null) {
synchronizeEditorAction = new SynchronizeEditorAction();
synchronizeEditorAction.selectionChanged(new StructuredSelection(getTaskEditor()));
toolBarManager.appendToGroup("repository", synchronizeEditorAction); //$NON-NLS-1$
} else {
if (taskData.isNew()) {
DeleteTaskEditorAction deleteAction = new DeleteTaskEditorAction(getTask());
toolBarManager.appendToGroup("new", deleteAction); //$NON-NLS-1$
} else if (taskRepository != null) {
ClearOutgoingAction clearOutgoingAction = new ClearOutgoingAction(
Collections.singletonList((IRepositoryElement) task));
(clearOutgoingAction).setTaskEditorPage(this);
if (clearOutgoingAction.isEnabled()) {
toolBarManager.appendToGroup("new", clearOutgoingAction); //$NON-NLS-1$
}
if (task.getSynchronizationState() != SynchronizationState.OUTGOING_NEW) {
synchronizeEditorAction = new SynchronizeEditorAction();
synchronizeEditorAction.selectionChanged(new StructuredSelection(getTaskEditor()));
toolBarManager.appendToGroup("repository", synchronizeEditorAction); //$NON-NLS-1$
}
NewSubTaskAction newSubTaskAction = new NewSubTaskAction();
newSubTaskAction.selectionChanged(newSubTaskAction, new StructuredSelection(task));
if (newSubTaskAction.isEnabled()) {
toolBarManager.appendToGroup("new", newSubTaskAction); //$NON-NLS-1$
}
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(taskData.getConnectorKind());
if (connectorUi != null) {
final String historyUrl = connectorUi.getTaskHistoryUrl(taskRepository, task);
if (historyUrl != null) {
Action historyAction = new Action() {
@Override
public void run() {
TasksUiUtil.openUrl(historyUrl);
}
};
historyAction.setImageDescriptor(TasksUiImages.TASK_REPOSITORY_HISTORY);
historyAction.setToolTipText(Messages.AbstractTaskEditorPage_History);
toolBarManager.prependToGroup("open", historyAction); //$NON-NLS-1$
}
}
}
if (needsSubmitButton()) {
ToolBarButtonContribution submitButtonContribution = new ToolBarButtonContribution(
"org.eclipse.mylyn.tasks.toolbars.submit") { //$NON-NLS-1$
@Override
protected Control createButton(Composite composite) {
submitButton = new Button(composite, SWT.FLAT);
submitButton.setText(Messages.TaskEditorActionPart_Submit + " "); //$NON-NLS-1$
submitButton.setImage(CommonImages.getImage(TasksUiImages.REPOSITORY_SUBMIT));
submitButton.setBackground(null);
submitButton.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event e) {
doSubmit();
}
});
return submitButton;
}
};
submitButtonContribution.marginLeft = 10;
toolBarManager.add(submitButtonContribution);
}
}
}
protected void fireSelectionChanged(ISelection selection) {
// create an event
final SelectionChangedEvent event = new SelectionChangedEvent(this, selection);
// fire the event
Object[] listeners = selectionChangedListeners.getListeners();
for (int i = 0; i < listeners.length; ++i) {
final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i];
SafeRunner.run(new SafeRunnable() {
public void run() {
l.selectionChanged(event);
}
});
}
}
@SuppressWarnings("unchecked")
@Override
public Object getAdapter(Class adapter) {
if (adapter == IContentOutlinePage.class) {
updateOutlinePage();
return outlinePage;
}
// TODO 3.3 replace by getTextSupport() method
if (adapter == CommonTextSupport.class) {
return textSupport;
}
return super.getAdapter(adapter);
}
private void updateOutlinePage() {
if (outlinePage == null) {
outlinePage = new TaskEditorOutlinePage();
outlinePage.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection instanceof StructuredSelection) {
Object select = ((StructuredSelection) selection).getFirstElement();
if (select instanceof TaskEditorOutlineNode) {
TaskEditorOutlineNode node = (TaskEditorOutlineNode) select;
TaskAttribute attribute = node.getData();
if (attribute != null) {
if (TaskAttribute.TYPE_COMMENT.equals(attribute.getMetaData().getType())) {
AbstractTaskEditorPart actionPart = getPart(ID_PART_COMMENTS);
if (actionPart != null && actionPart.getControl() instanceof ExpandableComposite) {
CommonFormUtil.setExpanded((ExpandableComposite) actionPart.getControl(), true);
if (actionPart.getControl() instanceof Section) {
Control client = ((Section) actionPart.getControl()).getClient();
if (client instanceof Composite) {
for (Control control : ((Composite) client).getChildren()) {
// toggle subsections
if (control instanceof Section) {
CommonFormUtil.setExpanded((Section) control, true);
}
}
}
}
}
}
EditorUtil.reveal(form, attribute.getId());
} else {
EditorUtil.reveal(form, node.getLabel());
}
getEditor().setActivePage(getId());
}
}
}
});
}
if (getModel() != null) {
TaskEditorOutlineNode node = TaskEditorOutlineNode.parse(getModel().getTaskData());
outlinePage.setInput(getTaskRepository(), node);
} else {
outlinePage.setInput(null, null);
}
}
private boolean getAttachContext() {
AbstractTaskEditorPart actionPart = getPart(ID_PART_ACTIONS);
if (actionPart instanceof TaskEditorActionPart) {
return ((TaskEditorActionPart) actionPart).getAttachContext();
}
return false;
}
public AttributeEditorFactory getAttributeEditorFactory() {
return attributeEditorFactory;
}
public AttributeEditorToolkit getAttributeEditorToolkit() {
return attributeEditorToolkit;
}
public AbstractRepositoryConnector getConnector() {
return connector;
}
public String getConnectorKind() {
return connectorKind;
}
/**
* @return The composite for the whole editor.
*/
public Composite getEditorComposite() {
return editorComposite;
}
public TaskDataModel getModel() {
return model;
}
public AbstractTaskEditorPart getPart(String partId) {
Assert.isNotNull(partId);
if (getManagedForm() != null) {
for (IFormPart part : getManagedForm().getParts()) {
if (part instanceof AbstractTaskEditorPart) {
AbstractTaskEditorPart taskEditorPart = (AbstractTaskEditorPart) part;
if (partId.equals(taskEditorPart.getPartId())) {
return taskEditorPart;
}
}
}
}
return null;
}
public ISelection getSelection() {
return lastSelection;
}
public ITask getTask() {
return task;
}
public TaskEditor getTaskEditor() {
return getEditor();
}
public TaskRepository getTaskRepository() {
// FIXME model can be null
return getModel().getTaskRepository();
}
/**
* Invoked after task submission has completed. This method is invoked on the UI thread in all cases whether
* submission was successful, canceled or failed. The value returned by <code>event.getJob().getStatus()</code>
* indicates the result of the submit job. Sub-classes may override but are encouraged to invoke the super method.
*
* @since 3.2
* @see SubmitJob
*/
protected void handleTaskSubmitted(SubmitJobEvent event) {
IStatus status = event.getJob().getStatus();
if (status != null && status.getSeverity() != IStatus.CANCEL) {
handleSubmitError(event.getJob());
}
}
private void handleSubmitError(SubmitJob job) {
if (form != null && !form.isDisposed()) {
final IStatus status = job.getStatus();
if (status.getCode() == RepositoryStatus.REPOSITORY_COMMENT_REQUIRED) {
TasksUiInternal.displayStatus(Messages.AbstractTaskEditorPage_Comment_required, status);
AbstractTaskEditorPart newCommentPart = getPart(ID_PART_NEW_COMMENT);
if (newCommentPart != null) {
newCommentPart.setFocus();
}
} else if (status.getCode() == RepositoryStatus.ERROR_REPOSITORY_LOGIN) {
if (TasksUiUtil.openEditRepositoryWizard(getTaskRepository()) == Window.OK) {
doSubmit();
}
} else {
String message;
if (status.getCode() == RepositoryStatus.ERROR_IO) {
message = ERROR_NOCONNECTIVITY;
} else if (status.getMessage().length() > 0) {
message = Messages.AbstractTaskEditorPage_Submit_failed_ + status.getMessage();
} else {
message = Messages.AbstractTaskEditorPage_Submit_failed;
}
getTaskEditor().setMessage(message, IMessageProvider.ERROR, new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
TasksUiInternal.displayStatus(Messages.AbstractTaskEditorPage_Submit_failed, status);
}
});
}
}
}
@Override
public void init(IEditorSite site, IEditorInput input) {
super.init(site, input);
// XXX consider propagating selection events to site selection provider instead to avoid conflicts with other pages
site.setSelectionProvider(this);
TaskEditorInput taskEditorInput = (TaskEditorInput) input;
this.task = taskEditorInput.getTask();
this.defaultSelection = new StructuredSelection(task);
this.lastSelection = defaultSelection;
IHandlerService handlerService = (IHandlerService) getSite().getService(IHandlerService.class);
this.textSupport = new CommonTextSupport(handlerService);
this.textSupport.setSelectionChangedListener(this);
initModel(taskEditorInput);
TasksUiPlugin.getTaskDataManager().addListener(TASK_DATA_LISTENER);
}
private void initModel(TaskEditorInput input) {
Assert.isTrue(model == null);
try {
this.model = createModel(input);
this.connector = TasksUi.getRepositoryManager().getRepositoryConnector(getConnectorKind());
setTaskData(model.getTaskData());
model.addModelListener(new TaskDataModelListener() {
@Override
public void attributeChanged(TaskDataModelEvent event) {
getManagedForm().dirtyStateChanged();
}
});
setNeedsAddToCategory(model.getTaskData().isNew());
} catch (final CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Error opening task", e)); //$NON-NLS-1$
getTaskEditor().setStatus(Messages.AbstractTaskEditorPage_Error_opening_task,
Messages.AbstractTaskEditorPage_Open_failed, e.getStatus());
}
}
private void initializePart(Composite parent, AbstractTaskEditorPart part) {
getManagedForm().addPart(part);
part.initialize(this);
part.createControl(parent, toolkit);
if (part.getControl() != null) {
if (ID_PART_ACTIONS.equals(part.getPartId())) {
// do not expand horizontally
GridDataFactory.fillDefaults().align(SWT.FILL, SWT.FILL).grab(false, false).applyTo(part.getControl());
} else {
if (part.getExpandVertically()) {
GridDataFactory.fillDefaults()
.align(SWT.FILL, SWT.FILL)
.grab(true, true)
.applyTo(part.getControl());
} else {
GridDataFactory.fillDefaults()
.align(SWT.FILL, SWT.TOP)
.grab(true, false)
.applyTo(part.getControl());
}
}
// for outline
if (ID_PART_COMMENTS.equals(part.getPartId())) {
EditorUtil.setMarker(part.getControl(), TaskEditorOutlineNode.LABEL_COMMENTS);
}
}
}
@Override
public boolean isDirty() {
return (getModel() != null && getModel().isDirty()) || (getManagedForm() != null && getManagedForm().isDirty());
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
public boolean needsAddToCategory() {
return needsAddToCategory;
}
/**
* Force a re-layout of entire form.
*/
public void reflow() {
if (reflow) {
try {
form.setRedraw(false);
// help the layout managers: ensure that the form width always matches
// the parent client area width.
Rectangle parentClientArea = form.getParent().getClientArea();
Point formSize = form.getSize();
if (formSize.x != parentClientArea.width) {
ScrollBar verticalBar = form.getVerticalBar();
int verticalBarWidth = verticalBar != null ? verticalBar.getSize().x : 15;
form.setSize(parentClientArea.width - verticalBarWidth, formSize.y);
}
form.layout(true, false);
form.reflow(true);
} finally {
form.setRedraw(true);
}
}
}
/**
* Updates the editor contents in place.
*/
public void refreshFormContent() {
if (getManagedForm() == null || getManagedForm().getForm().isDisposed()) {
// editor possibly closed as part of submit or page has not been intialized, yet
return;
}
try {
showEditorBusy(true);
if (model != null) {
doSave(new NullProgressMonitor());
refreshInput();
} else {
initModel(getTaskEditor().getTaskEditorInput());
}
if (taskData != null) {
try {
setReflow(false);
// prevent menu from being disposed when disposing control on the form during refresh
Menu menu = editorComposite.getMenu();
CommonUiUtil.setMenu(editorComposite, null);
// clear old controls and parts
for (Control control : editorComposite.getChildren()) {
control.dispose();
}
if (focusTracker != null) {
focusTracker.reset();
}
lastSelection = null;
for (IFormPart part : getManagedForm().getParts()) {
part.dispose();
getManagedForm().removePart(part);
}
// restore menu
editorComposite.setMenu(menu);
createFormContentInternal();
getTaskEditor().setMessage(null, 0);
getTaskEditor().setActivePage(getId());
setSubmitEnabled(true);
} finally {
setReflow(true);
}
}
updateOutlinePage();
updateHeaderMessage();
getManagedForm().dirtyStateChanged();
getTaskEditor().updateHeaderToolBar();
} finally {
showEditorBusy(false);
}
reflow();
}
private void refreshInput() {
try {
refreshDisabled = true;
model.refresh(null);
} catch (CoreException e) {
getTaskEditor().setMessage(Messages.AbstractTaskEditorPage_Failed_to_read_task_data_ + e.getMessage(),
IMessageProvider.ERROR);
taskData = null;
return;
} finally {
refreshDisabled = false;
}
setTaskData(model.getTaskData());
}
/**
* Registers a drop listener for <code>control</code>. The default implementation registers a listener for attaching
* files. Does nothing if the editor is showing a new task.
* <p>
* Clients may override.
* </p>
*
* @param control
* the control to register the listener for
*/
public void registerDefaultDropListener(final Control control) {
if (getModel() == null || getModel().getTaskData().isNew()) {
return;
}
DropTarget target = new DropTarget(control, DND.DROP_COPY | DND.DROP_DEFAULT);
final TextTransfer textTransfer = TextTransfer.getInstance();
final FileTransfer fileTransfer = FileTransfer.getInstance();
Transfer[] types = new Transfer[] { textTransfer, fileTransfer };
target.setTransfer(types);
if (defaultDropListener == null) {
defaultDropListener = new TaskAttachmentDropListener(this);
}
target.addDropListener(defaultDropListener);
}
public void removeSelectionChangedListener(ISelectionChangedListener listener) {
selectionChangedListeners.remove(listener);
}
public void selectionChanged(Object element) {
selectionChanged(new SelectionChangedEvent(this, new StructuredSelection(element)));
}
public void selectionChanged(SelectionChangedEvent event) {
ISelection selection = event.getSelection();
if (selection instanceof TextSelection) {
// only update global actions
((TaskEditorActionContributor) getEditorSite().getActionBarContributor()).updateSelectableActions(event.getSelection());
return;
}
if (selection.isEmpty()) {
// something was unselected, reset to default selection
selection = defaultSelection;
// XXX a styled text widget has lost focus, re-enable all edit actions
((TaskEditorActionContributor) getEditorSite().getActionBarContributor()).forceActionsEnabled();
}
if (!selection.equals(lastSelection)) {
this.lastSelection = selection;
fireSelectionChanged(lastSelection);
}
}
@Override
public void setFocus() {
if (focusTracker != null && focusTracker.setFocus()) {
return;
} else {
IFormPart[] parts = getManagedForm().getParts();
if (parts.length > 0) {
parts[0].setFocus();
return;
}
}
super.setFocus();
}
public void setNeedsAddToCategory(boolean needsAddToCategory) {
this.needsAddToCategory = needsAddToCategory;
}
public void setReflow(boolean reflow) {
this.reflow = reflow;
form.setRedraw(reflow);
}
public void setSelection(ISelection selection) {
IFormPart[] parts = getManagedForm().getParts();
for (IFormPart formPart : parts) {
if (formPart instanceof AbstractTaskEditorPart) {
if (((AbstractTaskEditorPart) formPart).setSelection(selection)) {
lastSelection = selection;
return;
}
}
}
}
// TODO EDITOR this needs to be tracked somewhere else
private void setSubmitEnabled(boolean enabled) {
AbstractTaskEditorPart actionPart = getPart(ID_PART_ACTIONS);
if (actionPart instanceof TaskEditorActionPart) {
((TaskEditorActionPart) actionPart).setSubmitEnabled(enabled);
}
if (submitButton != null) {
submitButton.setEnabled(enabled);
}
submitEnabled = enabled;
}
private void setTaskData(TaskData taskData) {
this.taskData = taskData;
}
@Override
public void showBusy(boolean busy) {
if (getManagedForm() != null && !getManagedForm().getForm().isDisposed() && this.busy != busy) {
setSubmitEnabled(!busy);
CommonUiUtil.setEnabled(editorComposite, !busy);
this.busy = busy;
}
}
public void showEditorBusy(boolean busy) {
getTaskEditor().showBusy(busy);
refreshDisabled = busy;
}
private void updateHeaderMessage() {
if (taskData == null) {
getTaskEditor().setMessage(Messages.AbstractTaskEditorPage_Synchronize_to_retrieve_task_data,
IMessageProvider.WARNING, new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
if (synchronizeEditorAction != null) {
synchronizeEditorAction.run();
}
}
});
}
if (getTaskEditor().getMessage() == null
&& TasksUiPlugin.getTaskList().getTask(task.getRepositoryUrl(), task.getTaskId()) == null) {
getTaskEditor().setMessage(Messages.AbstractTaskEditorPage_Add_task_to_tasklist,
IMessageProvider.INFORMATION, new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
if (TasksUiPlugin.getTaskList().getTask(task.getRepositoryUrl(), task.getTaskId()) == null) {
TasksUiPlugin.getTaskList().addTask(task,
TasksUiPlugin.getTaskList().getDefaultCategory());
getTaskEditor().setMessage(null, IMessageProvider.NONE, null);
// updateHeaderMessage();
}
}
});
}
}
@Override
public Control getPartControl() {
return partControl != null ? partControl : super.getPartControl();
}
/**
* Returns true, if the page has an always visible footer.
*
* @see #setNeedsFooter(boolean)
*/
private boolean needsFooter() {
return needsFooter;
}
/**
* Specifies that the page should provide an always visible footer. This flag is not set by default.
*
* @see #createFooterContent(Composite)
* @see #needsFooter()
*/
@SuppressWarnings("unused")
private void setNeedsFooter(boolean needsFooter) {
this.needsFooter = needsFooter;
}
private void createFooterContent(Composite parent) {
parent.setLayout(new GridLayout());
// submitButton = toolkit.createButton(parent, Messages.TaskEditorActionPart_Submit, SWT.NONE);
// GridData submitButtonData = new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING);
// submitButtonData.widthHint = 100;
// submitButton.setBackground(null);
// submitButton.setImage(CommonImages.getImage(TasksUiImages.REPOSITORY_SUBMIT));
// submitButton.setLayoutData(submitButtonData);
// submitButton.addListener(SWT.Selection, new Listener() {
// public void handleEvent(Event e) {
// doSubmit();
// }
// });
}
/**
* Returns true, if the page supports a submit operation.
*
* @since 3.2
* @see #setNeedsSubmit(boolean)
*/
public boolean needsSubmit() {
return needsSubmit;
}
/**
* Specifies that the page supports the submit operation. This flag is set to true by default.
*
* @since 3.2
* @see #needsSubmit()
* @see #doSubmit()
*/
public void setNeedsSubmit(boolean needsSubmit) {
this.needsSubmit = needsSubmit;
}
/**
* Returns true, if the page provides a submit button.
*
* @since 3.2
* @see #setNeedsSubmitButton(boolean)
*/
public boolean needsSubmitButton() {
return needsSubmitButton;
}
/**
* Specifies that the page supports submitting. This flag is set to false by default.
*
* @since 3.2
* @see #needsSubmitButton()
*/
public void setNeedsSubmitButton(boolean needsSubmitButton) {
this.needsSubmitButton = needsSubmitButton;
}
/**
* Returns true, if the page provides a submit button.
*
* @since 3.2
* @see #setNeedsPrivateSection(boolean)
*/
public boolean needsPrivateSection() {
return needsPrivateSection;
}
/**
* Specifies that the page should provide the private section. This flag is not set by default.
*
* @since 3.2
* @see #needsPrivateSection()
*/
public void setNeedsPrivateSection(boolean needsPrivateSection) {
this.needsPrivateSection = needsPrivateSection;
}
// private void fillLeftHeaderToolBar(IToolBarManager toolBarManager) {
// if (needsSubmit()) {
// ControlContribution submitButtonContribution = new ControlContribution(
// "org.eclipse.mylyn.tasks.toolbars.submit") { //$NON-NLS-1$
// @Override
// protected int computeWidth(Control control) {
// return super.computeWidth(control) + 5;
// }
//
// @Override
// protected Control createControl(Composite parent) {
// Composite composite = new Composite(parent, SWT.NONE);
// composite.setBackground(null);
// GridLayout layout = new GridLayout();
// layout.marginWidth = 0;
// layout.marginHeight = 0;
// layout.marginLeft = 10;
// composite.setLayout(layout);
//
// submitButton = toolkit.createButton(composite, Messages.TaskEditorActionPart_Submit + " ", SWT.NONE); //$NON-NLS-1$
// submitButton.setImage(CommonImages.getImage(TasksUiImages.REPOSITORY_SUBMIT));
// submitButton.setBackground(null);
// submitButton.addListener(SWT.Selection, new Listener() {
// public void handleEvent(Event e) {
// doSubmit();
// }
// });
// GridDataFactory.fillDefaults().align(SWT.BEGINNING, SWT.BOTTOM).applyTo(submitButton);
// return composite;
// }
// };
// toolBarManager.add(submitButtonContribution);
// }
// }
}
| true | true | protected Set<TaskEditorPartDescriptor> createPartDescriptors() {
Set<TaskEditorPartDescriptor> descriptors = new LinkedHashSet<TaskEditorPartDescriptor>();
descriptors.add(new TaskEditorPartDescriptor(ID_PART_SUMMARY) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorSummaryPart();
}
}.setPath(PATH_HEADER));
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ATTRIBUTES) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorAttributePart();
}
}.setPath(PATH_ATTRIBUTES));
if (!taskData.isNew() && connector.getTaskAttachmentHandler() != null) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ATTACHMENTS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorAttachmentPart();
}
}.setPath(PATH_ATTACHMENTS));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_DESCRIPTION) {
@Override
public AbstractTaskEditorPart createPart() {
TaskEditorDescriptionPart part = new TaskEditorDescriptionPart();
if (getModel().getTaskData().isNew()) {
part.setExpandVertically(true);
part.setSectionStyle(ExpandableComposite.TITLE_BAR | ExpandableComposite.EXPANDED);
}
return part;
}
}.setPath(PATH_COMMENTS));
if (!taskData.isNew()) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_COMMENTS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorCommentPart();
}
}.setPath(PATH_COMMENTS));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_NEW_COMMENT) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorNewCommentPart();
}
}.setPath(PATH_COMMENTS));
if (needsPrivateSection() || taskData.isNew()) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_PLANNING) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorPlanningPart();
}
}.setPath(PATH_PLANNING));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ACTIONS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorActionPart();
}
}.setPath(PATH_ACTIONS));
descriptors.add(new TaskEditorPartDescriptor(ID_PART_PEOPLE) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorPeoplePart();
}
}.setPath(PATH_PEOPLE));
descriptors.addAll(getContributionPartDescriptors());
return descriptors;
}
| protected Set<TaskEditorPartDescriptor> createPartDescriptors() {
Set<TaskEditorPartDescriptor> descriptors = new LinkedHashSet<TaskEditorPartDescriptor>();
descriptors.add(new TaskEditorPartDescriptor(ID_PART_SUMMARY) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorSummaryPart();
}
}.setPath(PATH_HEADER));
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ATTRIBUTES) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorAttributePart();
}
}.setPath(PATH_ATTRIBUTES));
if (!taskData.isNew() && connector.getTaskAttachmentHandler() != null
&& (AttachmentUtil.canDownloadAttachment(task) || AttachmentUtil.canUploadAttachment(task))) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ATTACHMENTS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorAttachmentPart();
}
}.setPath(PATH_ATTACHMENTS));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_DESCRIPTION) {
@Override
public AbstractTaskEditorPart createPart() {
TaskEditorDescriptionPart part = new TaskEditorDescriptionPart();
if (getModel().getTaskData().isNew()) {
part.setExpandVertically(true);
part.setSectionStyle(ExpandableComposite.TITLE_BAR | ExpandableComposite.EXPANDED);
}
return part;
}
}.setPath(PATH_COMMENTS));
if (!taskData.isNew()) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_COMMENTS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorCommentPart();
}
}.setPath(PATH_COMMENTS));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_NEW_COMMENT) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorNewCommentPart();
}
}.setPath(PATH_COMMENTS));
if (needsPrivateSection() || taskData.isNew()) {
descriptors.add(new TaskEditorPartDescriptor(ID_PART_PLANNING) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorPlanningPart();
}
}.setPath(PATH_PLANNING));
}
descriptors.add(new TaskEditorPartDescriptor(ID_PART_ACTIONS) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorActionPart();
}
}.setPath(PATH_ACTIONS));
descriptors.add(new TaskEditorPartDescriptor(ID_PART_PEOPLE) {
@Override
public AbstractTaskEditorPart createPart() {
return new TaskEditorPeoplePart();
}
}.setPath(PATH_PEOPLE));
descriptors.addAll(getContributionPartDescriptors());
return descriptors;
}
|
diff --git a/src/org/coocood/vcontentprovider/VContentProvider.java b/src/org/coocood/vcontentprovider/VContentProvider.java
index 9ed404c..b87bb84 100644
--- a/src/org/coocood/vcontentprovider/VContentProvider.java
+++ b/src/org/coocood/vcontentprovider/VContentProvider.java
@@ -1,378 +1,381 @@
/*
* Copyright 2013 - Ewan Chou ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.coocood.vcontentprovider;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.RemoteException;
public abstract class VContentProvider extends ContentProvider {
private VSQLiteOpenHelper mOpenHelper;
private SQLiteDatabase db;
private static HashMap<String, ArrayList<String>> tableMap = new HashMap<String, ArrayList<String>>();
private static HashMap<String, ArrayList<String>> viewTablesMap = new HashMap<String, ArrayList<String>>();
private HashSet<Uri> batchingUris;
/**
* @param dbVersions
* All create table and alter table add column definition goes to
* an upgrade object put every upgrade object into the list, then
* the database version is determined by the greatest upgrade
* version.
* @param viewCreatorMap
* ViewCreations will be dropped and recreated when the database
* upgrades.
* @return database name
*/
protected abstract String addDatabaseVersionsViewsAndGetName(
ArrayList<VDatabaseVersion> dbVersions,
HashMap<String, VViewCreation> viewCreationMap);
/**
* see also {@link #updateWithJSONObject}
*/
public static ContentProviderResult[] updateWithJSONArray(Context context,
Uri uri, JSONArray array,
LinkedHashMap<String, String> subJSONObjectMap)
throws RemoteException, OperationApplicationException,
JSONException {
Uri baseUri = new Uri.Builder().scheme(uri.getScheme())
.authority(uri.getAuthority()).build();
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
for (int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
addOperations(operations, uri, baseUri, json, subJSONObjectMap);
}
return context.getContentResolver().applyBatch(uri.getAuthority(),
operations);
}
/**
* If the JSONObject has any sub JSONObject, create a LinkedHashMap and
* put the key to the sub JSONObject and the corresponding table name as value in it.
* first in, first out(get updated).
*/
public static ContentProviderResult[] updateWithJSONObject(Context context,
Uri uri, JSONObject json,
LinkedHashMap<String, String> subJSONObjectMap)
throws JSONException, RemoteException,
OperationApplicationException {
Uri baseUri = new Uri.Builder().scheme(uri.getScheme())
.authority(uri.getAuthority()).build();
ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
addOperations(operations, uri, baseUri, json, subJSONObjectMap);
return context.getContentResolver().applyBatch(uri.getAuthority(),
operations);
}
private static void addOperations(
ArrayList<ContentProviderOperation> operations, Uri uri,
Uri baseUri, JSONObject json,
LinkedHashMap<String, String> subJSONObjectMap)
throws JSONException {
if (subJSONObjectMap != null) {
for (String key : subJSONObjectMap.keySet()) {
JSONObject subJson = json.getJSONObject(key);
String subTable = subJSONObjectMap.get(key);
operations.add(getOperation(baseUri, subJson, subTable));
}
}
String table = getTableName(uri);
operations.add(getOperation(baseUri, json, table));
}
private static ContentProviderOperation getOperation(Uri baseUri,
JSONObject json, String table) throws JSONException {
Uri uri = Uri.withAppendedPath(baseUri, table);
ArrayList<String> columns = tableMap.get(table);
ContentValues values = new ContentValues();
for (int i = 0; i < columns.size(); i++) {
String column = columns.get(i);
if (json.has(column)) {
String value = json.getString(column);
// The id column index in the columns ArrayList is 0.
// Put "_id" as the local id column name.
values.put(i == 0 ? "_id" : column, value);
}
}
return ContentProviderOperation.newUpdate(uri).withValues(values)
.build();
}
@Override
public boolean onCreate() {
ArrayList<VDatabaseVersion> versions = new ArrayList<VDatabaseVersion>();
HashMap<String, VViewCreation> viewMap = new HashMap<String, VViewCreation>();
String databaseName = addDatabaseVersionsViewsAndGetName(versions,
viewMap);
Collections.sort(versions);
mOpenHelper = new VSQLiteOpenHelper(getContext(), databaseName,
versions, viewMap);
for (VDatabaseVersion upgrade : versions) {
for (VTableCreation tableCreation : upgrade.tableCreations) {
ArrayList<String> columns = new ArrayList<String>();
/*
* Add id column at first so we can retrieve it back later.
* later.
*/
columns.add(tableCreation.sourceIdName);
for (VTableColumn column : tableCreation.columns) {
columns.add(column.name);
}
tableMap.put(tableCreation.table, columns);
}
for (VTableColumn column : upgrade.newColumns) {
tableMap.get(column.table).add(column.name);
}
}
for (VViewCreation viewCreation : viewMap.values()) {
ArrayList<String> viewTables = new ArrayList<String>();
viewTables.add(viewCreation.childTable.table);
- viewTables.addAll(viewCreation.parentTables.keySet());
- viewTablesMap.put(viewCreation.viewName, viewTables);
+ for (String key : viewCreation.parentTables.keySet()) {
+ VTableCreation vTableCreation = viewCreation.parentTables.get(key);
+ viewTables.add(vTableCreation.table);
+ }
+ viewTablesMap.put(viewCreation.viewName, viewTables);
}
batchingUris = new HashSet<Uri>();
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
String table = getTableName(uri);
String idPath = getIdPath(uri);
db = mOpenHelper.getReadableDatabase();
Cursor c = db.query(table, projection,
finalSelection(idPath, selection), selectionArgs, null, null,
sortOrder);
c.setNotificationUri(getContext().getContentResolver(), uri);
return c;
}
@Override
public String getType(Uri uri) {
String table = getTableName(uri);
String idPath = getIdPath(uri);
return "vnd.android.cursor." + idPath == null ? "dir" : "item"
+ "/vnd." + uri.getAuthority() + "." + table;
}
/**
* This implementation do not accept primary key value. If you want to
* insert a record with a primary key, call update instead, it will be
* inserted automatically if not exists.
*
* @see android.content.ContentProvider#insert(android.net.Uri,
* android.content.ContentValues)
*/
@Override
public Uri insert(Uri uri, ContentValues values) {
String tableName = getTableName(uri);
String idPath = getIdPath(uri);
if (idPath != null)
throw new IllegalArgumentException("Unknown URI " + uri);
if (values.containsKey("_id"))
throw new IllegalArgumentException(
"insert method do not accept primary key, call update instead.");
db = mOpenHelper.getWritableDatabase();
long id = db.insert(tableName, null, values);
if (id != -1) {
notifyChange(uri, 1);
return ContentUris.withAppendedId(uri, id);
}
return null;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
String table = getTableName(uri);
String idPath = getIdPath(uri);
db = mOpenHelper.getWritableDatabase();
int deleteCount = db.delete(table, finalSelection(idPath, selection),
selectionArgs);
notifyChange(uri, deleteCount);
return deleteCount;
}
/**
* If the primary key value is given, either in ContentValues or uri, this
* implementation will automatically intert the row if not exists.
*
* @see android.content.ContentProvider#update(android.net.Uri,
* android.content.ContentValues, java.lang.String, java.lang.String[])
*/
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int affectedRows = 0;
String tableName = getTableName(uri);
String idPath = getIdPath(uri);
if (idPath == null)
idPath = values.getAsString("_id");
db = mOpenHelper.getWritableDatabase();
if (idPath != null) {
db.beginTransaction();
try {
affectedRows = db.update(tableName, values,
finalSelection(idPath, selection), null);
if (affectedRows == 0) {
values.put("_id", Long.parseLong(idPath));
if (db.insert(tableName, null, values) != -1)
affectedRows = 1;
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
} else {
affectedRows = db.update(tableName, values,
finalSelection(idPath, selection), selectionArgs);
}
notifyChange(uri, affectedRows);
return affectedRows;
}
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
db = mOpenHelper.getWritableDatabase();
int succeedCount = 0;
db.beginTransaction();
batchingUris.add(uri);
try {
for (ContentValues value : values) {
if (insert(uri, value) != null)
succeedCount++;
}
db.setTransactionSuccessful();
} finally {
batchingUris.remove(uri);
db.endTransaction();
}
notifyChange(uri, succeedCount);
return succeedCount;
}
@Override
public ContentProviderResult[] applyBatch(
ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
db = mOpenHelper.getWritableDatabase();
ContentProviderResult[] results;
HashSet<Uri> tempUris = new HashSet<Uri>();
for (ContentProviderOperation operation : operations) {
tempUris.add(operation.getUri());
}
db.beginTransaction();
batchingUris.addAll(tempUris);
try {
results = super.applyBatch(operations);
db.setTransactionSuccessful();
} finally {
batchingUris.removeAll(tempUris);
db.endTransaction();
}
for (Uri uri : tempUris) {
notifyChange(uri, 1);
}
return results;
}
private static String getTableName(Uri uri) {
List<String> paths = uri.getPathSegments();
if (paths == null || paths.size() == 0)
throw new IllegalArgumentException("Unknown URI " + uri);
String tableName = paths.get(0);
if (tableMap.keySet().contains(tableName)
|| viewTablesMap.keySet().contains(tableName)) {
return tableName;
} else {
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
private String getIdPath(Uri uri) {
List<String> paths = uri.getPathSegments();
if (paths.size() == 1) {
return null;
} else if (paths.size() == 2) {
String idPath = paths.get(1);
try {
Long.parseLong(idPath);
return idPath;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Unknown URI " + uri);
}
} else {
throw new IllegalArgumentException("Unknown URI " + uri);
}
}
private String finalSelection(String idPath, String selection) {
if (idPath == null)
return selection;
String pathWhere = "_id = " + idPath;
if (selection != null) {
return pathWhere + " AND " + selection;
} else {
return pathWhere;
}
}
private void notifyChange(Uri uri, int count) {
if (!batchingUris.contains(uri) && count != 0) {
getContext().getContentResolver().notifyChange(uri, null);
// Notify not only the table Uri, but also the view Uris which
// contain the table.
String table = uri.getPathSegments().get(0);
for (String view : viewTablesMap.keySet()) {
if (viewTablesMap.get(view).contains(table)) {
Uri viewUri = new Uri.Builder().scheme(uri.getScheme())
.authority(uri.getAuthority()).appendPath(view)
.build();
getContext().getContentResolver().notifyChange(viewUri,
null);
}
}
}
}
}
| true | true | public boolean onCreate() {
ArrayList<VDatabaseVersion> versions = new ArrayList<VDatabaseVersion>();
HashMap<String, VViewCreation> viewMap = new HashMap<String, VViewCreation>();
String databaseName = addDatabaseVersionsViewsAndGetName(versions,
viewMap);
Collections.sort(versions);
mOpenHelper = new VSQLiteOpenHelper(getContext(), databaseName,
versions, viewMap);
for (VDatabaseVersion upgrade : versions) {
for (VTableCreation tableCreation : upgrade.tableCreations) {
ArrayList<String> columns = new ArrayList<String>();
/*
* Add id column at first so we can retrieve it back later.
* later.
*/
columns.add(tableCreation.sourceIdName);
for (VTableColumn column : tableCreation.columns) {
columns.add(column.name);
}
tableMap.put(tableCreation.table, columns);
}
for (VTableColumn column : upgrade.newColumns) {
tableMap.get(column.table).add(column.name);
}
}
for (VViewCreation viewCreation : viewMap.values()) {
ArrayList<String> viewTables = new ArrayList<String>();
viewTables.add(viewCreation.childTable.table);
viewTables.addAll(viewCreation.parentTables.keySet());
viewTablesMap.put(viewCreation.viewName, viewTables);
}
batchingUris = new HashSet<Uri>();
return true;
}
| public boolean onCreate() {
ArrayList<VDatabaseVersion> versions = new ArrayList<VDatabaseVersion>();
HashMap<String, VViewCreation> viewMap = new HashMap<String, VViewCreation>();
String databaseName = addDatabaseVersionsViewsAndGetName(versions,
viewMap);
Collections.sort(versions);
mOpenHelper = new VSQLiteOpenHelper(getContext(), databaseName,
versions, viewMap);
for (VDatabaseVersion upgrade : versions) {
for (VTableCreation tableCreation : upgrade.tableCreations) {
ArrayList<String> columns = new ArrayList<String>();
/*
* Add id column at first so we can retrieve it back later.
* later.
*/
columns.add(tableCreation.sourceIdName);
for (VTableColumn column : tableCreation.columns) {
columns.add(column.name);
}
tableMap.put(tableCreation.table, columns);
}
for (VTableColumn column : upgrade.newColumns) {
tableMap.get(column.table).add(column.name);
}
}
for (VViewCreation viewCreation : viewMap.values()) {
ArrayList<String> viewTables = new ArrayList<String>();
viewTables.add(viewCreation.childTable.table);
for (String key : viewCreation.parentTables.keySet()) {
VTableCreation vTableCreation = viewCreation.parentTables.get(key);
viewTables.add(vTableCreation.table);
}
viewTablesMap.put(viewCreation.viewName, viewTables);
}
batchingUris = new HashSet<Uri>();
return true;
}
|
diff --git a/main/src/cgeo/geocaching/cgCache.java b/main/src/cgeo/geocaching/cgCache.java
index 230e84e97..dfc18ab0e 100644
--- a/main/src/cgeo/geocaching/cgCache.java
+++ b/main/src/cgeo/geocaching/cgCache.java
@@ -1,1636 +1,1636 @@
package cgeo.geocaching;
import cgeo.geocaching.cgData.StorageLocation;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.activity.IAbstractActivity;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.capability.ISearchByCenter;
import cgeo.geocaching.connector.capability.ISearchByGeocode;
import cgeo.geocaching.connector.gc.GCConnector;
import cgeo.geocaching.connector.gc.GCConstants;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.enumerations.CacheAttribute;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.LoadFlag;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.files.GPXParser;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.LazyInitializedList;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.LogTemplateProvider;
import cgeo.geocaching.utils.LogTemplateProvider.LogContext;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Spannable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Internal c:geo representation of a "cache"
*/
public class cgCache implements ICache, IWaypoint {
private long updated = 0;
private long detailedUpdate = 0;
private long visitedDate = 0;
private int listId = StoredList.TEMPORARY_LIST_ID;
private boolean detailed = false;
private String geocode = "";
private String cacheId = "";
private String guid = "";
private CacheType cacheType = CacheType.UNKNOWN;
private String name = "";
private Spannable nameSp = null;
private String ownerDisplayName = "";
private String ownerUserId = "";
private Date hidden = null;
private String hint = "";
private CacheSize size = CacheSize.UNKNOWN;
private float difficulty = 0;
private float terrain = 0;
private Float direction = null;
private Float distance = null;
private String latlon = "";
private String location = "";
private Geopoint coords = null;
private boolean reliableLatLon = false;
private Double elevation = null;
private String personalNote = null;
private String shortdesc = "";
private String description = null;
private boolean disabled = false;
private boolean archived = false;
private boolean premiumMembersOnly = false;
private boolean found = false;
private boolean favorite = false;
private boolean own = false;
private int favoritePoints = 0;
private float rating = 0; // valid ratings are larger than zero
private int votes = 0;
private float myVote = 0; // valid ratings are larger than zero
private int inventoryItems = 0;
private boolean onWatchlist = false;
private LazyInitializedList<String> attributes = new LazyInitializedList<String>() {
@Override
protected List<String> loadFromDatabase() {
return cgeoapplication.getInstance().loadAttributes(geocode);
}
};
private LazyInitializedList<cgWaypoint> waypoints = new LazyInitializedList<cgWaypoint>() {
@Override
protected List<cgWaypoint> loadFromDatabase() {
return cgeoapplication.getInstance().loadWaypoints(geocode);
}
};
private List<cgImage> spoilers = null;
private LazyInitializedList<LogEntry> logs = new LazyInitializedList<LogEntry>() {
@Override
protected List<LogEntry> loadFromDatabase() {
return cgeoapplication.getInstance().loadLogs(geocode);
}
};
private List<cgTrackable> inventory = null;
private Map<LogType, Integer> logCounts = new HashMap<LogType, Integer>();
private boolean logOffline = false;
private boolean userModifiedCoords = false;
// temporary values
private boolean statusChecked = false;
private String directionImg = "";
private String nameForSorting;
private final EnumSet<StorageLocation> storageLocation = EnumSet.of(StorageLocation.HEAP);
private boolean finalDefined = false;
private int zoomlevel = Tile.ZOOMLEVEL_MAX + 1;
private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+");
private Handler changeNotificationHandler = null;
/**
* Create a new cache. To be used everywhere except for the GPX parser
*/
public cgCache() {
// empty
}
/**
* Cache constructor to be used by the GPX parser only. This constructor explicitly sets several members to empty
* lists.
*
* @param gpxParser
*/
public cgCache(GPXParser gpxParser) {
setReliableLatLon(true);
setAttributes(Collections.<String> emptyList());
setWaypoints(Collections.<cgWaypoint> emptyList(), false);
setLogs(Collections.<LogEntry> emptyList());
}
public void setChangeNotificationHandler(Handler newNotificationHandler) {
changeNotificationHandler = newNotificationHandler;
}
/**
* Sends a change notification to interested parties
*/
private void notifyChange() {
if (changeNotificationHandler != null) {
changeNotificationHandler.sendEmptyMessage(0);
}
}
/**
* Gather missing information from another cache object.
*
* @param other
* the other version, or null if non-existent
* @return true if this cache is "equal" to the other version
*/
public boolean gatherMissingFrom(final cgCache other) {
if (other == null) {
return false;
}
updated = System.currentTimeMillis();
if (!detailed && (other.detailed || zoomlevel < other.zoomlevel)) {
detailed = other.detailed;
detailedUpdate = other.detailedUpdate;
coords = other.coords;
cacheType = other.cacheType;
zoomlevel = other.zoomlevel;
// boolean values must be enumerated here. Other types are assigned outside this if-statement
premiumMembersOnly = other.premiumMembersOnly;
reliableLatLon = other.reliableLatLon;
archived = other.archived;
found = other.found;
own = other.own;
disabled = other.disabled;
favorite = other.favorite;
onWatchlist = other.onWatchlist;
logOffline = other.logOffline;
finalDefined = other.finalDefined;
}
/*
* No gathering for boolean members if other cache is not-detailed
* and does not have information with higher reliability (denoted by zoomlevel)
* - found
* - own
* - disabled
* - favorite
* - onWatchlist
* - logOffline
*/
if (visitedDate == 0) {
visitedDate = other.visitedDate;
}
if (listId == StoredList.TEMPORARY_LIST_ID) {
listId = other.listId;
}
if (StringUtils.isBlank(geocode)) {
geocode = other.geocode;
}
if (StringUtils.isBlank(cacheId)) {
cacheId = other.cacheId;
}
if (StringUtils.isBlank(guid)) {
guid = other.guid;
}
if (null == cacheType || CacheType.UNKNOWN == cacheType) {
cacheType = other.cacheType;
}
if (StringUtils.isBlank(name)) {
name = other.name;
}
if (StringUtils.isBlank(nameSp)) {
nameSp = other.nameSp;
}
if (StringUtils.isBlank(ownerDisplayName)) {
ownerDisplayName = other.ownerDisplayName;
}
if (StringUtils.isBlank(ownerUserId)) {
ownerUserId = other.ownerUserId;
}
if (hidden == null) {
hidden = other.hidden;
}
if (StringUtils.isBlank(hint)) {
hint = other.hint;
}
if (size == null || CacheSize.UNKNOWN == size) {
size = other.size;
}
if (difficulty == 0) {
difficulty = other.difficulty;
}
if (terrain == 0) {
terrain = other.terrain;
}
if (direction == null) {
direction = other.direction;
}
if (distance == null) {
distance = other.distance;
}
if (StringUtils.isBlank(latlon)) {
latlon = other.latlon;
}
if (StringUtils.isBlank(location)) {
location = other.location;
}
if (coords == null) {
coords = other.coords;
}
if (elevation == null) {
elevation = other.elevation;
}
if (personalNote == null) { // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC
personalNote = other.personalNote;
}
if (StringUtils.isBlank(shortdesc)) {
shortdesc = other.shortdesc;
}
if (StringUtils.isBlank(description)) {
description = other.description;
}
if (favoritePoints == 0) {
favoritePoints = other.favoritePoints;
}
if (rating == 0) {
rating = other.rating;
}
if (votes == 0) {
votes = other.votes;
}
if (myVote == 0) {
myVote = other.myVote;
}
if (attributes.isEmpty()) {
attributes.set(other.attributes);
}
if (waypoints.isEmpty()) {
- waypoints.set(other.waypoints);
+ this.setWaypoints(other.waypoints.asList(), false);
}
else {
ArrayList<cgWaypoint> newPoints = new ArrayList<cgWaypoint>(waypoints.asList());
- cgWaypoint.mergeWayPoints(newPoints, other.getWaypoints(), false);
- waypoints.set(newPoints);
+ cgWaypoint.mergeWayPoints(newPoints, other.waypoints.asList(), false);
+ this.setWaypoints(newPoints, false);
}
if (spoilers == null) {
spoilers = other.spoilers;
}
if (inventory == null) {
// If inventoryItems is 0, it can mean both
// "don't know" or "0 items". Since we cannot distinguish
// them here, only populate inventoryItems from
// old data when we have to do it for inventory.
inventory = other.inventory;
inventoryItems = other.inventoryItems;
}
if (logs.isEmpty()) { // keep last known logs if none
logs.set(other.logs);
}
if (logCounts.size() == 0) {
logCounts = other.logCounts;
}
if (!userModifiedCoords) {
userModifiedCoords = other.userModifiedCoords;
}
if (!reliableLatLon) {
reliableLatLon = other.reliableLatLon;
}
if (zoomlevel == -1) {
zoomlevel = other.zoomlevel;
}
boolean isEqual = isEqualTo(other);
if (!isEqual) {
notifyChange();
}
return isEqual;
}
/**
* Compare two caches quickly. For map and list fields only the references are compared !
*
* @param other the other cache to compare this one to
* @return true if both caches have the same content
*/
private boolean isEqualTo(final cgCache other) {
return detailed == other.detailed &&
StringUtils.equalsIgnoreCase(geocode, other.geocode) &&
StringUtils.equalsIgnoreCase(name, other.name) &&
cacheType == other.cacheType &&
size == other.size &&
found == other.found &&
own == other.own &&
premiumMembersOnly == other.premiumMembersOnly &&
difficulty == other.difficulty &&
terrain == other.terrain &&
(coords != null ? coords.equals(other.coords) : null == other.coords) &&
reliableLatLon == other.reliableLatLon &&
disabled == other.disabled &&
archived == other.archived &&
listId == other.listId &&
StringUtils.equalsIgnoreCase(ownerDisplayName, other.ownerDisplayName) &&
StringUtils.equalsIgnoreCase(ownerUserId, other.ownerUserId) &&
StringUtils.equalsIgnoreCase(description, other.description) &&
StringUtils.equalsIgnoreCase(personalNote, other.personalNote) &&
StringUtils.equalsIgnoreCase(shortdesc, other.shortdesc) &&
StringUtils.equalsIgnoreCase(latlon, other.latlon) &&
StringUtils.equalsIgnoreCase(location, other.location) &&
favorite == other.favorite &&
favoritePoints == other.favoritePoints &&
onWatchlist == other.onWatchlist &&
(hidden != null ? hidden.equals(other.hidden) : null == other.hidden) &&
StringUtils.equalsIgnoreCase(guid, other.guid) &&
StringUtils.equalsIgnoreCase(hint, other.hint) &&
StringUtils.equalsIgnoreCase(cacheId, other.cacheId) &&
(direction != null ? direction.equals(other.direction) : null == other.direction) &&
(distance != null ? distance.equals(other.distance) : null == other.distance) &&
(elevation != null ? elevation.equals(other.elevation) : null == other.elevation) &&
nameSp == other.nameSp &&
rating == other.rating &&
votes == other.votes &&
myVote == other.myVote &&
inventoryItems == other.inventoryItems &&
attributes == other.attributes &&
waypoints == other.waypoints &&
spoilers == other.spoilers &&
logs == other.logs &&
inventory == other.inventory &&
logCounts == other.logCounts &&
logOffline == other.logOffline &&
finalDefined == other.finalDefined;
}
public boolean hasTrackables() {
return inventoryItems > 0;
}
public boolean canBeAddedToCalendar() {
// is event type?
if (!isEventCache()) {
return false;
}
// has event date set?
if (hidden == null) {
return false;
}
// is not in the past?
final Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return hidden.compareTo(cal.getTime()) >= 0;
}
/**
* Checks if a page contains the guid of a cache
*
* @param page
* the page to search in, may be null
* @return true if the page contains the guid of the cache, false otherwise
*/
public boolean isGuidContainedInPage(final String page) {
if (StringUtils.isBlank(page) || StringUtils.isBlank(guid)) {
return false;
}
final Boolean found = Pattern.compile(guid, Pattern.CASE_INSENSITIVE).matcher(page).find();
Log.i("cgCache.isGuidContainedInPage: guid '" + guid + "' " + (found ? "" : "not ") + "found");
return found;
}
public boolean isEventCache() {
return cacheType.isEvent();
}
public void logVisit(final IAbstractActivity fromActivity) {
if (StringUtils.isBlank(cacheId)) {
fromActivity.showToast(((Activity) fromActivity).getResources().getString(R.string.err_cannot_log_visit));
return;
}
Intent logVisitIntent = new Intent((Activity) fromActivity, VisitCacheActivity.class);
logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_ID, cacheId);
logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_GEOCODE, geocode);
logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_FOUND, found);
((Activity) fromActivity).startActivity(logVisitIntent);
}
public void logOffline(final Activity fromActivity, final LogType logType) {
final boolean mustIncludeSignature = StringUtils.isNotBlank(Settings.getSignature()) && Settings.isAutoInsertSignature();
final String initial = mustIncludeSignature ? LogTemplateProvider.applyTemplates(Settings.getSignature(), new LogContext(this, true)) : "";
logOffline(fromActivity, initial, Calendar.getInstance(), logType);
}
void logOffline(final Activity fromActivity, final String log, Calendar date, final LogType logType) {
if (logType == LogType.UNKNOWN) {
return;
}
cgeoapplication app = (cgeoapplication) fromActivity.getApplication();
final boolean status = app.saveLogOffline(geocode, date.getTime(), logType, log);
Resources res = fromActivity.getResources();
if (status) {
ActivityMixin.showToast(fromActivity, res.getString(R.string.info_log_saved));
app.saveVisitDate(geocode);
logOffline = true;
notifyChange();
} else {
ActivityMixin.showToast(fromActivity, res.getString(R.string.err_log_post_failed));
}
}
public List<LogType> getPossibleLogTypes() {
boolean isOwner = getOwnerUserId() != null && getOwnerUserId().equalsIgnoreCase(Settings.getUsername());
List<LogType> logTypes = new ArrayList<LogType>();
if (isEventCache()) {
logTypes.add(LogType.WILL_ATTEND);
logTypes.add(LogType.NOTE);
logTypes.add(LogType.ATTENDED);
logTypes.add(LogType.NEEDS_ARCHIVE);
if (isOwner) {
logTypes.add(LogType.ANNOUNCEMENT);
}
} else if (CacheType.WEBCAM == cacheType) {
logTypes.add(LogType.WEBCAM_PHOTO_TAKEN);
logTypes.add(LogType.DIDNT_FIND_IT);
logTypes.add(LogType.NOTE);
logTypes.add(LogType.NEEDS_ARCHIVE);
logTypes.add(LogType.NEEDS_MAINTENANCE);
} else {
logTypes.add(LogType.FOUND_IT);
logTypes.add(LogType.DIDNT_FIND_IT);
logTypes.add(LogType.NOTE);
logTypes.add(LogType.NEEDS_ARCHIVE);
logTypes.add(LogType.NEEDS_MAINTENANCE);
}
if (isOwner) {
logTypes.add(LogType.OWNER_MAINTENANCE);
logTypes.add(LogType.TEMP_DISABLE_LISTING);
logTypes.add(LogType.ENABLE_LISTING);
logTypes.add(LogType.ARCHIVE);
logTypes.remove(LogType.UPDATE_COORDINATES);
}
return logTypes;
}
public void openInBrowser(Activity fromActivity) {
fromActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getCacheUrl())));
}
private String getCacheUrl() {
return getConnector().getCacheUrl(this);
}
private IConnector getConnector() {
return ConnectorFactory.getConnector(this);
}
public boolean canOpenInBrowser() {
return getCacheUrl() != null;
}
public boolean supportsRefresh() {
return getConnector() instanceof ISearchByGeocode;
}
public boolean supportsWatchList() {
return getConnector().supportsWatchList();
}
public boolean supportsFavoritePoints() {
return getConnector().supportsFavoritePoints();
}
public boolean supportsLogging() {
return getConnector().supportsLogging();
}
@Override
public float getDifficulty() {
return difficulty;
}
@Override
public String getGeocode() {
return geocode;
}
@Override
public String getOwnerDisplayName() {
return ownerDisplayName;
}
@Override
public CacheSize getSize() {
if (size == null) {
return CacheSize.UNKNOWN;
}
return size;
}
@Override
public float getTerrain() {
return terrain;
}
@Override
public boolean isArchived() {
return archived;
}
@Override
public boolean isDisabled() {
return disabled;
}
@Override
public boolean isPremiumMembersOnly() {
return premiumMembersOnly;
}
public void setPremiumMembersOnly(boolean members) {
this.premiumMembersOnly = members;
}
@Override
public boolean isOwn() {
return own;
}
@Override
public String getOwnerUserId() {
return ownerUserId;
}
@Override
public String getHint() {
return hint;
}
@Override
public String getDescription() {
if (description == null) {
description = StringUtils.defaultString(cgeoapplication.getInstance().getCacheDescription(geocode));
}
return description;
}
@Override
public String getShortDescription() {
return shortdesc;
}
@Override
public String getName() {
return name;
}
@Override
public String getCacheId() {
if (StringUtils.isBlank(cacheId) && getConnector().equals(GCConnector.getInstance())) {
return String.valueOf(GCConstants.gccodeToGCId(geocode));
}
return cacheId;
}
@Override
public String getGuid() {
return guid;
}
@Override
public String getLocation() {
return location;
}
@Override
public String getPersonalNote() {
// non premium members have no personal notes, premium members have an empty string by default.
// map both to null, so other code doesn't need to differentiate
if (StringUtils.isBlank(personalNote)) {
return null;
}
return personalNote;
}
public boolean supportsUserActions() {
return getConnector().supportsUserActions();
}
public boolean supportsCachesAround() {
return getConnector() instanceof ISearchByCenter;
}
public void shareCache(Activity fromActivity, Resources res) {
if (geocode == null) {
return;
}
StringBuilder subject = new StringBuilder("Geocache ");
subject.append(geocode);
if (StringUtils.isNotBlank(name)) {
subject.append(" - ").append(name);
}
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString());
intent.putExtra(Intent.EXTRA_TEXT, getUrl());
fromActivity.startActivity(Intent.createChooser(intent, res.getText(R.string.action_bar_share_title)));
}
public String getUrl() {
return getConnector().getCacheUrl(this);
}
public boolean supportsGCVote() {
return StringUtils.startsWithIgnoreCase(geocode, "GC");
}
public void setDescription(final String description) {
this.description = description;
}
@Override
public boolean isFound() {
return found;
}
@Override
public boolean isFavorite() {
return favorite;
}
public void setFavorite(boolean favourite) {
this.favorite = favourite;
}
@Override
public boolean isWatchlist() {
return onWatchlist;
}
@Override
public Date getHiddenDate() {
return hidden;
}
@Override
public LazyInitializedList<String> getAttributes() {
return attributes;
}
@Override
public List<cgTrackable> getInventory() {
return inventory;
}
public void addSpoiler(final cgImage spoiler) {
if (spoilers == null) {
spoilers = new ArrayList<cgImage>();
}
spoilers.add(spoiler);
}
@Override
public List<cgImage> getSpoilers() {
if (spoilers == null) {
return Collections.emptyList();
}
return Collections.unmodifiableList(spoilers);
}
@Override
public Map<LogType, Integer> getLogCounts() {
return logCounts;
}
@Override
public int getFavoritePoints() {
return favoritePoints;
}
@Override
public String getNameForSorting() {
if (null == nameForSorting) {
final Matcher matcher = NUMBER_PATTERN.matcher(name);
if (matcher.find()) {
nameForSorting = name.replace(matcher.group(), StringUtils.leftPad(matcher.group(), 6, '0'));
}
else {
nameForSorting = name;
}
}
return nameForSorting;
}
public boolean isVirtual() {
return CacheType.VIRTUAL == cacheType || CacheType.WEBCAM == cacheType
|| CacheType.EARTH == cacheType;
}
public boolean showSize() {
return !((isEventCache() || isVirtual()) && size == CacheSize.NOT_CHOSEN);
}
public long getUpdated() {
return updated;
}
public void setUpdated(long updated) {
this.updated = updated;
}
public long getDetailedUpdate() {
return detailedUpdate;
}
public void setDetailedUpdate(long detailedUpdate) {
this.detailedUpdate = detailedUpdate;
}
public long getVisitedDate() {
return visitedDate;
}
public void setVisitedDate(long visitedDate) {
this.visitedDate = visitedDate;
}
public int getListId() {
return listId;
}
public void setListId(int listId) {
this.listId = listId;
}
public boolean isDetailed() {
return detailed;
}
public void setDetailed(boolean detailed) {
this.detailed = detailed;
}
public Spannable getNameSp() {
return nameSp;
}
public void setNameSp(Spannable nameSp) {
this.nameSp = nameSp;
}
public void setHidden(final Date hidden) {
if (hidden == null) {
this.hidden = null;
}
else {
this.hidden = new Date(hidden.getTime()); // avoid storing the external reference in this object
}
}
public Float getDirection() {
return direction;
}
public void setDirection(Float direction) {
this.direction = direction;
}
public Float getDistance() {
return distance;
}
public void setDistance(Float distance) {
this.distance = distance;
}
public String getLatlon() {
return latlon;
}
public void setLatlon(String latlon) {
this.latlon = latlon;
}
@Override
public Geopoint getCoords() {
return coords;
}
public void setCoords(Geopoint coords) {
this.coords = coords;
}
/**
* @return true if the coords are from the cache details page and the user has been logged in
*/
public boolean isReliableLatLon() {
return getConnector().isReliableLatLon(reliableLatLon);
}
public void setReliableLatLon(boolean reliableLatLon) {
this.reliableLatLon = reliableLatLon;
}
public Double getElevation() {
return elevation;
}
public void setElevation(Double elevation) {
this.elevation = elevation;
}
public String getShortdesc() {
return shortdesc;
}
public void setShortdesc(String shortdesc) {
this.shortdesc = shortdesc;
}
public void setFavoritePoints(int favoriteCnt) {
this.favoritePoints = favoriteCnt;
}
public float getRating() {
return rating;
}
public void setRating(float rating) {
this.rating = rating;
}
public int getVotes() {
return votes;
}
public void setVotes(int votes) {
this.votes = votes;
}
public float getMyVote() {
return myVote;
}
public void setMyVote(float myVote) {
this.myVote = myVote;
}
public int getInventoryItems() {
return inventoryItems;
}
public void setInventoryItems(int inventoryItems) {
this.inventoryItems = inventoryItems;
}
public boolean isOnWatchlist() {
return onWatchlist;
}
public void setOnWatchlist(boolean onWatchlist) {
this.onWatchlist = onWatchlist;
}
/**
* return an immutable list of waypoints.
*
* @return always non <code>null</code>
*/
public List<cgWaypoint> getWaypoints() {
return waypoints.asList();
}
/**
* @param waypoints
* List of waypoints to set for cache
* @param saveToDatabase
* Indicates whether to add the waypoints to the database. Should be false if
* called while loading or building a cache
* @return <code>true</code> if waypoints successfully added to waypoint database
*/
public boolean setWaypoints(List<cgWaypoint> waypoints, boolean saveToDatabase) {
this.waypoints.set(waypoints);
finalDefined = false;
if (waypoints != null) {
for (cgWaypoint waypoint : waypoints) {
waypoint.setGeocode(geocode);
if (waypoint.isFinalWithCoords()) {
finalDefined = true;
}
}
}
return saveToDatabase && cgeoapplication.getInstance().saveWaypoints(this);
}
/**
* @return never <code>null</code>
*/
public LazyInitializedList<LogEntry> getLogs() {
return logs;
}
/**
* @return only the logs of friends, never <code>null</code>
*/
public List<LogEntry> getFriendsLogs() {
ArrayList<LogEntry> friendLogs = new ArrayList<LogEntry>();
for (LogEntry log : logs) {
if (log.friend) {
friendLogs.add(log);
}
}
return Collections.unmodifiableList(friendLogs);
}
/**
* @param logs
* the log entries
*/
public void setLogs(List<LogEntry> logs) {
this.logs.set(logs);
}
public boolean isLogOffline() {
return logOffline;
}
public void setLogOffline(boolean logOffline) {
this.logOffline = logOffline;
}
public boolean isStatusChecked() {
return statusChecked;
}
public void setStatusChecked(boolean statusChecked) {
this.statusChecked = statusChecked;
}
public String getDirectionImg() {
return directionImg;
}
public void setDirectionImg(String directionImg) {
this.directionImg = directionImg;
}
public void setGeocode(String geocode) {
this.geocode = StringUtils.upperCase(geocode);
}
public void setCacheId(String cacheId) {
this.cacheId = cacheId;
}
public void setGuid(String guid) {
this.guid = guid;
}
public void setName(String name) {
this.name = name;
}
public void setOwnerDisplayName(String ownerDisplayName) {
this.ownerDisplayName = ownerDisplayName;
}
public void setOwnerUserId(String ownerUserId) {
this.ownerUserId = ownerUserId;
}
public void setHint(String hint) {
this.hint = hint;
}
public void setSize(CacheSize size) {
if (size == null) {
this.size = CacheSize.UNKNOWN;
}
else {
this.size = size;
}
}
public void setDifficulty(float difficulty) {
this.difficulty = difficulty;
}
public void setTerrain(float terrain) {
this.terrain = terrain;
}
public void setLocation(String location) {
this.location = location;
}
public void setPersonalNote(String personalNote) {
this.personalNote = personalNote;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public void setArchived(boolean archived) {
this.archived = archived;
}
public void setFound(boolean found) {
this.found = found;
}
public void setOwn(boolean own) {
this.own = own;
}
public void setAttributes(List<String> attributes) {
this.attributes.set(attributes);
}
public void setSpoilers(List<cgImage> spoilers) {
this.spoilers = spoilers;
}
public void setInventory(List<cgTrackable> inventory) {
this.inventory = inventory;
}
public void setLogCounts(Map<LogType, Integer> logCounts) {
this.logCounts = logCounts;
}
/*
* (non-Javadoc)
*
* @see cgeo.geocaching.IBasicCache#getType()
*
* @returns Never null
*/
@Override
public CacheType getType() {
return cacheType;
}
public void setType(CacheType cacheType) {
if (cacheType == null || CacheType.ALL == cacheType) {
throw new IllegalArgumentException("Illegal cache type");
}
this.cacheType = cacheType;
}
public boolean hasDifficulty() {
return difficulty > 0f;
}
public boolean hasTerrain() {
return terrain > 0f;
}
/**
* @return the storageLocation
*/
public EnumSet<StorageLocation> getStorageLocation() {
return storageLocation;
}
/**
* @param storageLocation
* the storageLocation to set
*/
public void addStorageLocation(final StorageLocation storageLocation) {
this.storageLocation.add(storageLocation);
}
/**
* @param waypoint
* Waypoint to add to the cache
* @param saveToDatabase
* Indicates whether to add the waypoint to the database. Should be false if
* called while loading or building a cache
* @return <code>true</code> if waypoint successfully added to waypoint database
*/
public boolean addOrChangeWaypoint(final cgWaypoint waypoint, boolean saveToDatabase) {
waypoint.setGeocode(geocode);
if (waypoint.getId() <= 0) { // this is a new waypoint
waypoints.add(waypoint);
if (waypoint.isFinalWithCoords()) {
finalDefined = true;
}
} else { // this is a waypoint being edited
final int index = getWaypointIndex(waypoint);
if (index >= 0) {
waypoints.remove(index);
}
waypoints.add(waypoint);
// when waypoint was edited, finalDefined may have changed
resetFinalDefined();
}
return saveToDatabase && cgeoapplication.getInstance().saveWaypoint(waypoint.getId(), geocode, waypoint);
}
public boolean hasWaypoints() {
return !waypoints.isEmpty();
}
public boolean hasFinalDefined() {
return finalDefined;
}
// Only for loading
public void setFinalDefined(boolean finalDefined) {
this.finalDefined = finalDefined;
}
/**
* Reset <code>finalDefined</code> based on current list of stored waypoints
*/
private void resetFinalDefined() {
finalDefined = false;
for (cgWaypoint wp : waypoints) {
if (wp.isFinalWithCoords()) {
finalDefined = true;
break;
}
}
}
public boolean hasUserModifiedCoords() {
return userModifiedCoords;
}
public void setUserModifiedCoords(boolean coordsChanged) {
this.userModifiedCoords = coordsChanged;
}
/**
* Duplicate a waypoint.
*
* @param index the waypoint to duplicate
* @return <code>true</code> if the waypoint was duplicated, <code>false</code> otherwise (invalid index)
*/
public boolean duplicateWaypoint(final int index) {
final cgWaypoint original = getWaypoint(index);
if (original == null) {
return false;
}
final cgWaypoint copy = new cgWaypoint(original);
copy.setUserDefined();
copy.setName(cgeoapplication.getInstance().getString(R.string.waypoint_copy_of) + " " + copy.getName());
waypoints.add(index + 1, copy);
return cgeoapplication.getInstance().saveWaypoint(-1, geocode, copy);
}
/**
* delete a user defined waypoint
*
* @param index
* of the waypoint in cache's waypoint list
* @return <code>true</code>, if the waypoint was deleted
*/
public boolean deleteWaypoint(final int index) {
final cgWaypoint waypoint = getWaypoint(index);
if (waypoint == null) {
return false;
}
if (waypoint.isUserDefined()) {
waypoints.remove(index);
cgeoapplication.getInstance().deleteWaypoint(waypoint.getId());
cgeoapplication.getInstance().removeCache(geocode, EnumSet.of(RemoveFlag.REMOVE_CACHE));
// Check status if Final is defined
if (waypoint.isFinalWithCoords()) {
resetFinalDefined();
}
return true;
}
return false;
}
/**
* delete a user defined waypoint
*
* @param waypoint
* to be removed from cache
* @return <code>true</code>, if the waypoint was deleted
*/
public boolean deleteWaypoint(final cgWaypoint waypoint) {
if (waypoint.getId() <= 0) {
return false;
}
final int index = getWaypointIndex(waypoint);
return index >= 0 && deleteWaypoint(index);
}
/**
* Find index of given <code>waypoint</code> in cache's <code>waypoints</code> list
*
* @param waypoint
* to find index for
* @return index in <code>waypoints</code> if found, -1 otherwise
*/
private int getWaypointIndex(final cgWaypoint waypoint) {
final int id = waypoint.getId();
for (int index = 0; index < waypoints.size(); index++) {
if (waypoints.get(index).getId() == id) {
return index;
}
}
return -1;
}
/**
* Retrieve a given waypoint.
*
* @param index the index of the waypoint
* @return waypoint or <code>null</code> if index is out of range
*/
public cgWaypoint getWaypoint(final int index) {
return index >= 0 && index < waypoints.size() ? waypoints.get(index) : null;
}
/**
* Lookup a waypoint by its id.
*
* @param id the id of the waypoint to look for
* @return waypoint or <code>null</code>
*/
public cgWaypoint getWaypointById(final int id) {
for (final cgWaypoint waypoint : waypoints) {
if (waypoint.getId() == id) {
return waypoint;
}
}
return null;
}
public void parseWaypointsFromNote() {
try {
if (StringUtils.isBlank(getPersonalNote())) {
return;
}
final Pattern coordPattern = Pattern.compile("\\b[nNsS]{1}\\s*\\d"); // begin of coordinates
int count = 1;
String note = getPersonalNote();
Matcher matcher = coordPattern.matcher(note);
while (matcher.find()) {
try {
final Geopoint point = new Geopoint(note.substring(matcher.start()));
// coords must have non zero latitude and longitude and at least one part shall have fractional degrees
if (point.getLatitudeE6() != 0 && point.getLongitudeE6() != 0 && ((point.getLatitudeE6() % 1000) != 0 || (point.getLongitudeE6() % 1000) != 0)) {
final String name = cgeoapplication.getInstance().getString(R.string.cache_personal_note) + " " + count;
final cgWaypoint waypoint = new cgWaypoint(name, WaypointType.WAYPOINT, false);
waypoint.setCoords(point);
addOrChangeWaypoint(waypoint, false);
count++;
}
} catch (Geopoint.ParseException e) {
// ignore
}
note = note.substring(matcher.start() + 1);
matcher = coordPattern.matcher(note);
}
} catch (Exception e) {
Log.e("cgCache.parseWaypointsFromNote: " + e.toString());
}
}
/*
* For working in the debugger
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.geocode + " " + this.name;
}
@Override
public int hashCode() {
return geocode.hashCode() * name.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof cgCache)) {
return false;
}
// just compare the geocode even if that is not what "equals" normally does
return StringUtils.isNotBlank(geocode) && geocode.equals(((cgCache) obj).geocode);
}
public void store(CancellableHandler handler) {
final int listId = Math.max(getListId(), StoredList.STANDARD_LIST_ID);
storeCache(this, null, listId, false, handler);
}
public void setZoomlevel(int zoomlevel) {
this.zoomlevel = zoomlevel;
}
@Override
public int getId() {
return 0;
}
@Override
public WaypointType getWaypointType() {
return null;
}
@Override
public String getCoordType() {
return "cache";
}
public void drop(Handler handler) {
try {
cgeoapplication.getInstance().markDropped(Collections.singletonList(this));
cgeoapplication.getInstance().removeCache(getGeocode(), EnumSet.of(RemoveFlag.REMOVE_CACHE));
handler.sendMessage(Message.obtain());
} catch (Exception e) {
Log.e("cache.drop: ", e);
}
}
public void checkFields() {
if (StringUtils.isBlank(getGeocode())) {
Log.e("geo code not parsed correctly");
}
if (StringUtils.isBlank(getName())) {
Log.e("name not parsed correctly");
}
if (StringUtils.isBlank(getGuid())) {
Log.e("guid not parsed correctly");
}
if (getTerrain() == 0.0) {
Log.e("terrain not parsed correctly");
}
if (getDifficulty() == 0.0) {
Log.e("difficulty not parsed correctly");
}
if (StringUtils.isBlank(getOwnerDisplayName())) {
Log.e("owner display name not parsed correctly");
}
if (StringUtils.isBlank(getOwnerUserId())) {
Log.e("owner user id real not parsed correctly");
}
if (getHiddenDate() == null) {
Log.e("hidden not parsed correctly");
}
if (getFavoritePoints() < 0) {
Log.e("favoriteCount not parsed correctly");
}
if (getSize() == null) {
Log.e("size not parsed correctly");
}
if (getType() == null || getType() == CacheType.UNKNOWN) {
Log.e("type not parsed correctly");
}
if (getCoords() == null) {
Log.e("coordinates not parsed correctly");
}
if (StringUtils.isBlank(getLocation())) {
Log.e("location not parsed correctly");
}
}
public void refresh(int newListId, CancellableHandler handler) {
cgeoapplication.getInstance().removeCache(geocode, EnumSet.of(RemoveFlag.REMOVE_CACHE));
storeCache(null, geocode, newListId, true, handler);
}
public static void storeCache(cgCache origCache, String geocode, int listId, boolean forceRedownload, CancellableHandler handler) {
try {
cgCache cache;
// get cache details, they may not yet be complete
if (origCache != null) {
// only reload the cache if it was already stored or doesn't have full details (by checking the description)
if (origCache.isOffline() || StringUtils.isBlank(origCache.getDescription())) {
final SearchResult search = searchByGeocode(origCache.getGeocode(), null, listId, false, handler);
cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB);
} else {
cache = origCache;
}
} else if (StringUtils.isNotBlank(geocode)) {
final SearchResult search = searchByGeocode(geocode, null, listId, forceRedownload, handler);
cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB);
} else {
cache = null;
}
if (cache == null) {
if (handler != null) {
handler.sendMessage(Message.obtain());
}
return;
}
if (CancellableHandler.isCancelled(handler)) {
return;
}
final HtmlImage imgGetter = new HtmlImage(cache.getGeocode(), false, listId, true);
// store images from description
if (StringUtils.isNotBlank(cache.getDescription())) {
Html.fromHtml(cache.getDescription(), imgGetter, null);
}
if (CancellableHandler.isCancelled(handler)) {
return;
}
// store spoilers
if (CollectionUtils.isNotEmpty(cache.getSpoilers())) {
for (cgImage oneSpoiler : cache.getSpoilers()) {
imgGetter.getDrawable(oneSpoiler.getUrl());
}
}
if (CancellableHandler.isCancelled(handler)) {
return;
}
// store images from logs
if (Settings.isStoreLogImages()) {
for (LogEntry log : cache.getLogs()) {
if (log.hasLogImages()) {
for (cgImage oneLogImg : log.getLogImages()) {
imgGetter.getDrawable(oneLogImg.getUrl());
}
}
}
}
if (CancellableHandler.isCancelled(handler)) {
return;
}
cache.setListId(listId);
cgeoapplication.getInstance().saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
if (CancellableHandler.isCancelled(handler)) {
return;
}
StaticMapsProvider.downloadMaps(cache);
if (handler != null) {
handler.sendMessage(Message.obtain());
}
} catch (Exception e) {
Log.e("cgBase.storeCache");
}
}
public static SearchResult searchByGeocode(final String geocode, final String guid, final int listId, final boolean forceReload, final CancellableHandler handler) {
if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) {
Log.e("cgCache.searchByGeocode: No geocode nor guid given");
return null;
}
final cgeoapplication app = cgeoapplication.getInstance();
if (!forceReload && listId == StoredList.TEMPORARY_LIST_ID && (app.isOffline(geocode, guid) || app.isThere(geocode, guid, true, true))) {
final SearchResult search = new SearchResult();
final String realGeocode = StringUtils.isNotBlank(geocode) ? geocode : app.getGeocode(guid);
search.addGeocode(realGeocode);
return search;
}
// if we have no geocode, we can't dynamically select the handler, but must explicitly use GC
if (geocode == null && guid != null) {
return GCConnector.getInstance().searchByGeocode(null, guid, handler);
}
final IConnector connector = ConnectorFactory.getConnector(geocode);
if (connector instanceof ISearchByGeocode) {
return ((ISearchByGeocode) connector).searchByGeocode(geocode, guid, handler);
}
return null;
}
public boolean isOffline() {
return listId >= StoredList.STANDARD_LIST_ID;
}
/**
* guess an event start time from the description
*
* @return start time in minutes after midnight
*/
public String guessEventTimeMinutes() {
if (!isEventCache()) {
return null;
}
// 12:34
final Pattern time = Pattern.compile("\\b(\\d{1,2})\\:(\\d\\d)\\b");
final Matcher matcher = time.matcher(getDescription());
while (matcher.find()) {
try {
final int hours = Integer.valueOf(matcher.group(1));
final int minutes = Integer.valueOf(matcher.group(2));
if (hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60) {
return String.valueOf(hours * 60 + minutes);
}
} catch (NumberFormatException e) {
// cannot happen, but static code analysis doesn't know
}
}
// 12 o'clock
final String hourLocalized = cgeoapplication.getInstance().getString(R.string.cache_time_full_hours);
if (StringUtils.isNotBlank(hourLocalized)) {
final Pattern fullHours = Pattern.compile("\\b(\\d{1,2})\\s+" + Pattern.quote(hourLocalized), Pattern.CASE_INSENSITIVE);
final Matcher matcherHours = fullHours.matcher(getDescription());
if (matcherHours.find()) {
try {
final int hours = Integer.valueOf(matcherHours.group(1));
if (hours >= 0 && hours < 24) {
return String.valueOf(hours * 60);
}
} catch (NumberFormatException e) {
// cannot happen, but static code analysis doesn't know
}
}
}
return null;
}
/**
* check whether the cache has a given attribute
*
* @param attribute
* @param yes
* true if we are looking for the attribute_yes version, false for the attribute_no version
* @return
*/
public boolean hasAttribute(CacheAttribute attribute, boolean yes) {
// lazy loading of attributes
cgCache fullCache = cgeoapplication.getInstance().loadCache(getGeocode(), EnumSet.of(LoadFlag.LOAD_ATTRIBUTES));
if (fullCache == null) {
fullCache = this;
}
return fullCache.getAttributes().contains(attribute.getAttributeName(yes));
}
public boolean hasStaticMap() {
return StaticMapsProvider.hasStaticMap(this);
}
public List<cgImage> getImages() {
List<cgImage> result = new ArrayList<cgImage>();
result.addAll(getSpoilers());
for (LogEntry log : getLogs()) {
result.addAll(log.getLogImages());
}
return result;
}
}
| false | true | public boolean gatherMissingFrom(final cgCache other) {
if (other == null) {
return false;
}
updated = System.currentTimeMillis();
if (!detailed && (other.detailed || zoomlevel < other.zoomlevel)) {
detailed = other.detailed;
detailedUpdate = other.detailedUpdate;
coords = other.coords;
cacheType = other.cacheType;
zoomlevel = other.zoomlevel;
// boolean values must be enumerated here. Other types are assigned outside this if-statement
premiumMembersOnly = other.premiumMembersOnly;
reliableLatLon = other.reliableLatLon;
archived = other.archived;
found = other.found;
own = other.own;
disabled = other.disabled;
favorite = other.favorite;
onWatchlist = other.onWatchlist;
logOffline = other.logOffline;
finalDefined = other.finalDefined;
}
/*
* No gathering for boolean members if other cache is not-detailed
* and does not have information with higher reliability (denoted by zoomlevel)
* - found
* - own
* - disabled
* - favorite
* - onWatchlist
* - logOffline
*/
if (visitedDate == 0) {
visitedDate = other.visitedDate;
}
if (listId == StoredList.TEMPORARY_LIST_ID) {
listId = other.listId;
}
if (StringUtils.isBlank(geocode)) {
geocode = other.geocode;
}
if (StringUtils.isBlank(cacheId)) {
cacheId = other.cacheId;
}
if (StringUtils.isBlank(guid)) {
guid = other.guid;
}
if (null == cacheType || CacheType.UNKNOWN == cacheType) {
cacheType = other.cacheType;
}
if (StringUtils.isBlank(name)) {
name = other.name;
}
if (StringUtils.isBlank(nameSp)) {
nameSp = other.nameSp;
}
if (StringUtils.isBlank(ownerDisplayName)) {
ownerDisplayName = other.ownerDisplayName;
}
if (StringUtils.isBlank(ownerUserId)) {
ownerUserId = other.ownerUserId;
}
if (hidden == null) {
hidden = other.hidden;
}
if (StringUtils.isBlank(hint)) {
hint = other.hint;
}
if (size == null || CacheSize.UNKNOWN == size) {
size = other.size;
}
if (difficulty == 0) {
difficulty = other.difficulty;
}
if (terrain == 0) {
terrain = other.terrain;
}
if (direction == null) {
direction = other.direction;
}
if (distance == null) {
distance = other.distance;
}
if (StringUtils.isBlank(latlon)) {
latlon = other.latlon;
}
if (StringUtils.isBlank(location)) {
location = other.location;
}
if (coords == null) {
coords = other.coords;
}
if (elevation == null) {
elevation = other.elevation;
}
if (personalNote == null) { // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC
personalNote = other.personalNote;
}
if (StringUtils.isBlank(shortdesc)) {
shortdesc = other.shortdesc;
}
if (StringUtils.isBlank(description)) {
description = other.description;
}
if (favoritePoints == 0) {
favoritePoints = other.favoritePoints;
}
if (rating == 0) {
rating = other.rating;
}
if (votes == 0) {
votes = other.votes;
}
if (myVote == 0) {
myVote = other.myVote;
}
if (attributes.isEmpty()) {
attributes.set(other.attributes);
}
if (waypoints.isEmpty()) {
waypoints.set(other.waypoints);
}
else {
ArrayList<cgWaypoint> newPoints = new ArrayList<cgWaypoint>(waypoints.asList());
cgWaypoint.mergeWayPoints(newPoints, other.getWaypoints(), false);
waypoints.set(newPoints);
}
if (spoilers == null) {
spoilers = other.spoilers;
}
if (inventory == null) {
// If inventoryItems is 0, it can mean both
// "don't know" or "0 items". Since we cannot distinguish
// them here, only populate inventoryItems from
// old data when we have to do it for inventory.
inventory = other.inventory;
inventoryItems = other.inventoryItems;
}
if (logs.isEmpty()) { // keep last known logs if none
logs.set(other.logs);
}
if (logCounts.size() == 0) {
logCounts = other.logCounts;
}
if (!userModifiedCoords) {
userModifiedCoords = other.userModifiedCoords;
}
if (!reliableLatLon) {
reliableLatLon = other.reliableLatLon;
}
if (zoomlevel == -1) {
zoomlevel = other.zoomlevel;
}
boolean isEqual = isEqualTo(other);
if (!isEqual) {
notifyChange();
}
return isEqual;
}
| public boolean gatherMissingFrom(final cgCache other) {
if (other == null) {
return false;
}
updated = System.currentTimeMillis();
if (!detailed && (other.detailed || zoomlevel < other.zoomlevel)) {
detailed = other.detailed;
detailedUpdate = other.detailedUpdate;
coords = other.coords;
cacheType = other.cacheType;
zoomlevel = other.zoomlevel;
// boolean values must be enumerated here. Other types are assigned outside this if-statement
premiumMembersOnly = other.premiumMembersOnly;
reliableLatLon = other.reliableLatLon;
archived = other.archived;
found = other.found;
own = other.own;
disabled = other.disabled;
favorite = other.favorite;
onWatchlist = other.onWatchlist;
logOffline = other.logOffline;
finalDefined = other.finalDefined;
}
/*
* No gathering for boolean members if other cache is not-detailed
* and does not have information with higher reliability (denoted by zoomlevel)
* - found
* - own
* - disabled
* - favorite
* - onWatchlist
* - logOffline
*/
if (visitedDate == 0) {
visitedDate = other.visitedDate;
}
if (listId == StoredList.TEMPORARY_LIST_ID) {
listId = other.listId;
}
if (StringUtils.isBlank(geocode)) {
geocode = other.geocode;
}
if (StringUtils.isBlank(cacheId)) {
cacheId = other.cacheId;
}
if (StringUtils.isBlank(guid)) {
guid = other.guid;
}
if (null == cacheType || CacheType.UNKNOWN == cacheType) {
cacheType = other.cacheType;
}
if (StringUtils.isBlank(name)) {
name = other.name;
}
if (StringUtils.isBlank(nameSp)) {
nameSp = other.nameSp;
}
if (StringUtils.isBlank(ownerDisplayName)) {
ownerDisplayName = other.ownerDisplayName;
}
if (StringUtils.isBlank(ownerUserId)) {
ownerUserId = other.ownerUserId;
}
if (hidden == null) {
hidden = other.hidden;
}
if (StringUtils.isBlank(hint)) {
hint = other.hint;
}
if (size == null || CacheSize.UNKNOWN == size) {
size = other.size;
}
if (difficulty == 0) {
difficulty = other.difficulty;
}
if (terrain == 0) {
terrain = other.terrain;
}
if (direction == null) {
direction = other.direction;
}
if (distance == null) {
distance = other.distance;
}
if (StringUtils.isBlank(latlon)) {
latlon = other.latlon;
}
if (StringUtils.isBlank(location)) {
location = other.location;
}
if (coords == null) {
coords = other.coords;
}
if (elevation == null) {
elevation = other.elevation;
}
if (personalNote == null) { // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC
personalNote = other.personalNote;
}
if (StringUtils.isBlank(shortdesc)) {
shortdesc = other.shortdesc;
}
if (StringUtils.isBlank(description)) {
description = other.description;
}
if (favoritePoints == 0) {
favoritePoints = other.favoritePoints;
}
if (rating == 0) {
rating = other.rating;
}
if (votes == 0) {
votes = other.votes;
}
if (myVote == 0) {
myVote = other.myVote;
}
if (attributes.isEmpty()) {
attributes.set(other.attributes);
}
if (waypoints.isEmpty()) {
this.setWaypoints(other.waypoints.asList(), false);
}
else {
ArrayList<cgWaypoint> newPoints = new ArrayList<cgWaypoint>(waypoints.asList());
cgWaypoint.mergeWayPoints(newPoints, other.waypoints.asList(), false);
this.setWaypoints(newPoints, false);
}
if (spoilers == null) {
spoilers = other.spoilers;
}
if (inventory == null) {
// If inventoryItems is 0, it can mean both
// "don't know" or "0 items". Since we cannot distinguish
// them here, only populate inventoryItems from
// old data when we have to do it for inventory.
inventory = other.inventory;
inventoryItems = other.inventoryItems;
}
if (logs.isEmpty()) { // keep last known logs if none
logs.set(other.logs);
}
if (logCounts.size() == 0) {
logCounts = other.logCounts;
}
if (!userModifiedCoords) {
userModifiedCoords = other.userModifiedCoords;
}
if (!reliableLatLon) {
reliableLatLon = other.reliableLatLon;
}
if (zoomlevel == -1) {
zoomlevel = other.zoomlevel;
}
boolean isEqual = isEqualTo(other);
if (!isEqual) {
notifyChange();
}
return isEqual;
}
|
diff --git a/persistence-geo-rest/src/main/java/com/emergya/persistenceGeo/web/RestLayersAdminController.java b/persistence-geo-rest/src/main/java/com/emergya/persistenceGeo/web/RestLayersAdminController.java
index 26c2eb9..6519bde 100644
--- a/persistence-geo-rest/src/main/java/com/emergya/persistenceGeo/web/RestLayersAdminController.java
+++ b/persistence-geo-rest/src/main/java/com/emergya/persistenceGeo/web/RestLayersAdminController.java
@@ -1,906 +1,909 @@
/*
* RestLayersAdminController.java
*
* Copyright (C) 2012
*
* This file is part of Proyecto persistenceGeo
*
* This software 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 software is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU 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., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* As a special exception, if you link this library with other files to produce
* an executable, this library does not by itself cause the resulting executable
* to be covered by the GNU General Public License. This exception does not
* however invalidate any other reasons why the executable file might be covered
* by the GNU General Public License.
*
* Authors:: Alejandro Díaz Torres (mailto:[email protected])
*/
package com.emergya.persistenceGeo.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.ListUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
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.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.emergya.persistenceGeo.dto.AuthorityDto;
import com.emergya.persistenceGeo.dto.FolderDto;
import com.emergya.persistenceGeo.dto.LayerDto;
import com.emergya.persistenceGeo.dto.MapConfigurationDto;
import com.emergya.persistenceGeo.dto.SimplePropertyDto;
import com.emergya.persistenceGeo.dto.UserDto;
import com.emergya.persistenceGeo.service.LayerAdminService;
import com.emergya.persistenceGeo.service.MapConfigurationAdminService;
import com.emergya.persistenceGeo.service.UserAdminService;
import com.emergya.persistenceGeo.utils.FolderStyle;
import com.emergya.persistenceGeo.utils.FoldersUtils;
/**
* Rest controller to admin and load layer and layers context
*
* @author <a href="mailto:[email protected]">adiaz</a>
*/
@Controller
public class RestLayersAdminController implements Serializable{
/**
*
*/
private static final long serialVersionUID = 3028127910300105478L;
@Resource
private UserAdminService userAdminService;
@Resource
private LayerAdminService layerAdminService;
@Resource
private MapConfigurationAdminService mapConfigurationAdminService;
private Map<Long, File> loadedLayers = new HashMap<Long, File>();
private Map<Long, File> loadFiles = new HashMap<Long, File>();
protected final String RESULTS= "results";
protected final String ROOT= "data";
protected final String SUCCESS= "success";
public static final String LOAD_FOLDERS_BY_USER = "user";
public static final String LOAD_FOLDERS_BY_GROUP = "group";
public static final String LOAD_FOLDERS_STYLE_TREE = "tree";
public static final String LOAD_FOLDERS_STYLE_STRING = "string";
/**
* This method loads mapConfiguration
*
* @return JSON file with map configuration
*/
@RequestMapping(value = "/persistenceGeo/loadMapConfiguration", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
Map<String, Object> loadMapConfiguration(){
Map<String, Object> result = new HashMap<String, Object>();
MapConfigurationDto mapConfiguration = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
mapConfiguration = mapConfigurationAdminService.loadConfiguration();
result.put(SUCCESS, true);
}catch (Exception e){
e.printStackTrace();
result.put(SUCCESS, false);
}
result.put(RESULTS, mapConfiguration != null ? 1: 0);
result.put(ROOT, mapConfiguration);
return result;
}
/**
* This method update mapConfiguration
*
* @return JSON file with map configuration updated
*/
@RequestMapping(value = "/persistenceGeo/updateMapConfiguration", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
Map<String, Object> updateMapConfiguration(@RequestParam("bbox") String bbox,
@RequestParam("iProj") String iProj,
@RequestParam("res") String res){
Map<String, Object> result = new HashMap<String, Object>();
MapConfigurationDto mapConfiguration = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
mapConfiguration = mapConfigurationAdminService.loadConfiguration();
mapConfigurationAdminService.updateMapConfiguration(mapConfiguration.getId(), bbox, iProj, res);
mapConfiguration = mapConfigurationAdminService.loadConfiguration();
result.put(SUCCESS, true);
}catch (Exception e){
e.printStackTrace();
result.put(SUCCESS, false);
}
result.put(RESULTS, mapConfiguration != null ? 1: 0);
result.put(ROOT, mapConfiguration);
return result;
}
/**
* This method loads layers.json related with a user
*
* @param username
*
* @return JSON file with layers
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/persistenceGeo/loadLayers/{username}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
Map<String, Object> loadLayers(@PathVariable String username){
Map<String, Object> result = new HashMap<String, Object>();
List<LayerDto> layers = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
if(username != null){
layers = new LinkedList<LayerDto>();
UserDto userDto = userAdminService.obtenerUsuario(username);
if(userDto.getId() != null){
layers = layerAdminService.getLayersByUser(userDto.getId());
}else{
layers = ListUtils.EMPTY_LIST;
}
for(LayerDto layer: layers){
if(layer.getId() != null && layer.getData() != null){
loadedLayers.put(layer.getId(), layer.getData());
layer.setData(null);
layer.setServer_resource("rest/persistenceGeo/getLayerResource/"+layer.getId());
}
}
}
result.put(SUCCESS, true);
}catch (Exception e){
e.printStackTrace();
result.put(SUCCESS, false);
}
result.put(RESULTS, layers.size());
result.put(ROOT, layers);
return result;
}
/**
* This method loads layers.json related with a user
*
* @param username
*
* @return JSON file with layers
*/
@SuppressWarnings("unchecked")
@RequestMapping(value = "/persistenceGeo/loadLayersByGroup/{groupId}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
Map<String, Object> loadLayersByGroup(@PathVariable String groupId){
Map<String, Object> result = new HashMap<String, Object>();
List<LayerDto> layers = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
if(groupId != null){
layers = layerAdminService.getLayersByAuthority(Long.decode(groupId));
}else{
layers = ListUtils.EMPTY_LIST;
}
for(LayerDto layer: layers){
if(layer.getId() != null && layer.getData() != null){
loadedLayers.put(layer.getId(), layer.getData());
layer.setData(null);
layer.setServer_resource("rest/persistenceGeo/getLayerResource/"+layer.getId());
}
}
result.put(SUCCESS, true);
}catch (Exception e){
e.printStackTrace();
result.put(SUCCESS, false);
}
result.put(RESULTS, layers.size());
result.put(ROOT, layers);
return result;
}
/**
* This method loads json file related with a user
*
* @param username
*
* @return JSON file with layer type properties
*/
@RequestMapping(value = "/persistenceGeo/getLayerTypeProperties/{layerType}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody
Map<String, Object> getLayerTypeProperties(@PathVariable String layerType) {
Map<String, Object> result = new HashMap<String, Object>();
List<String> listRes = layerAdminService
.getAllLayerTypeProperties(layerType);
List<SimplePropertyDto> list = new LinkedList<SimplePropertyDto>();
if(listRes != null){
for(String property: listRes){
list.add(new SimplePropertyDto(property));
}
}
result.put(SUCCESS, true);
result.put(RESULTS, list.size());
result.put(ROOT, list);
return result;
}
/**
* This method loads json file with layer types
*
* @param username
*
* @return JSON file with layer types
*/
@RequestMapping(value = "/persistenceGeo/getLayerTypes", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE })
public @ResponseBody
Map<String, Object> getLayerTypes() {
Map<String, Object> result = new HashMap<String, Object>();
List<String> listRes = layerAdminService.getAllLayerTypes();
List<SimplePropertyDto> list = new LinkedList<SimplePropertyDto>();
if(listRes != null){
for(String property: listRes){
list.add(new SimplePropertyDto(property));
}
}
result.put(SUCCESS, true);
result.put(RESULTS, list.size());
result.put(ROOT, list);
return result;
}
/**
* This method loads layers.json related with a user
*
* @param username
*
* @return JSON file with layers
*/
@RequestMapping(value = "/persistenceGeo/getLayerResource/{layerId}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public void loadLayer(@PathVariable String layerId,
HttpServletResponse response){
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
response.setContentType("application/xml");
response.setHeader("Content-Disposition",
"attachment; filename=test.xml");
IOUtils.copy(new FileInputStream(loadedLayers.get(Long.decode(layerId))), response
.getOutputStream());
response.flushBuffer();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* This method loads layers.json related with a group
*
* @param username
*
* @return JSON file with layers
*/
@RequestMapping(value = "/persistenceGeo/loadLayersGroup/{group}", method = RequestMethod.GET)
public @ResponseBody
List<LayerDto> loadLayersGroup(@PathVariable String group){
List<LayerDto> layers = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
if(group != null){
layers = new LinkedList<LayerDto>();
List<AuthorityDto> authosDto = userAdminService.obtenerGruposUsuarios();
List<String> namesList = null;
if(authosDto != null){
for(AuthorityDto authoDto: authosDto){
if(authoDto.getNombre().equals(group)){
namesList = authoDto.getLayerList();
break;
}
}
if(namesList != null){
layers = layerAdminService.getLayersByName(namesList);
}
}
}
}catch (Exception e){
e.printStackTrace();
}
return layers;
}
/**
* This method loads layers.json related with a folder
*
* @param username
*
* @return JSON file with layers
*/
@RequestMapping(value = "/persistenceGeo/loadLayersFolder/{folder}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
List<LayerDto> loadLayersFolder(@PathVariable String folder){
List<LayerDto> layers = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
}catch (Exception e){
e.printStackTrace();
}
return layers;
}
/**
* This method loads layers.json related with a folder
*
* @param username
*
* @return JSON file with layers
*/
@RequestMapping(value = "/persistenceGeo/moveLayerTo", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
List<LayerDto> moveLayerTo(@RequestParam("toFolder") String toFolder,
@RequestParam(value="toOrder",required=false) String toOrder){
List<LayerDto> layers = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
}catch (Exception e){
e.printStackTrace();
}
return layers;
}
private static final Random RANDOM = new Random();
/**
* This method saves a layer related with a user
*
* @param uploadfile
*/
@RequestMapping(value = "/persistenceGeo/uploadFile", method = RequestMethod.POST)
public ModelAndView uploadFile(
@RequestParam(value="uploadfile") MultipartFile uploadfile){
ModelAndView model = new ModelAndView();
String result = null;
if(uploadfile != null){
Long id = RANDOM.nextLong();
result = "{\"results\": 1, \"data\": \""+ id +"\", \"success\": true}";
byte[] data;
try {
data = IOUtils.toByteArray(uploadfile.getInputStream());
File temp = com.emergya.persistenceGeo.utils.FileUtils
.createFileTemp("tmp", "xml");
org.apache.commons.io.FileUtils.writeByteArrayToFile(temp, data);
loadFiles.put(id, temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
result = "{\"results\": 0, \"data\": \"\", \"success\": false}";
}
model.addObject("resultado", result);
model.setViewName("resultToJSON");
return model;
}
/**
* This method saves a layer related with a user
*
* @param username
* @param uploadfile
*/
@RequestMapping(value = "/persistenceGeo/saveLayerByUser/{username}", method = RequestMethod.POST)
public @ResponseBody
LayerDto saveLayerByUser(@PathVariable String username,
@RequestParam("name") String name,
@RequestParam("type") String type,
@RequestParam(value="properties", required=false) String properties,
@RequestParam(value="enabled", required=false) String enabled,
@RequestParam(value="order_layer", required=false) String order_layer,
@RequestParam(value="is_channel", required=false) String is_channel,
@RequestParam(value="publicized", required=false) String publicized,
@RequestParam(value="server_resource", required=false) String server_resource,
@RequestParam(value="folderId", required=false) String folderId,
@RequestParam(value="idFile", required=false) String idFile){
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
// Create the layerDto
LayerDto layer = new LayerDto();
// Assign the user
layer.setUser(username);
//Copy layerData
layer = copyDataToLayer(name, type, properties, enabled, order_layer,
is_channel, publicized, server_resource, idFile, layer, folderId);
return layer;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* This method saves a layer related with a user
*
* @param username
* @param uploadfile
*/
@RequestMapping(value = "/persistenceGeo/saveLayerByGroup/{idGroup}", method = RequestMethod.POST)
public @ResponseBody
LayerDto saveLayerByGroup(@PathVariable String idGroup,
@RequestParam("name") String name,
@RequestParam("type") String type,
@RequestParam(value="properties", required=false) String properties,
@RequestParam(value="enabled", required=false) String enabled,
@RequestParam(value="order_layer", required=false) String order_layer,
@RequestParam(value="is_channel", required=false) String is_channel,
@RequestParam(value="publicized", required=false) String publicized,
@RequestParam(value="server_resource", required=false) String server_resource,
@RequestParam(value="folderId", required=false) String folderId,
@RequestParam(value="idFile", required=false) String idFile){
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
// Create the layerDto
LayerDto layer = new LayerDto();
// Assign the user group
AuthorityDto group = userAdminService.obtenerGrupoUsuarios(Long.decode(idGroup));
layer.setAuthId(group.getId());
//Copy layerData
layer = copyDataToLayer(name, type, properties, enabled, order_layer,
is_channel, publicized, server_resource, idFile, layer, folderId);
return layer;
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* Copy layer data
*
* @param name
* @param type
* @param properties
* @param enabled
* @param order_layer
* @param is_channel
* @param publicized
* @param server_resource
* @param uploadfile
* @param layer
* @throws IOException
*/
private LayerDto copyDataToLayer(String name, String type, String properties,
String enabled, String order_layer, String is_channel,
String publicized, String server_resource,
String idFile, LayerDto layer, String folderId) throws IOException {
// Add request parameter
layer.setName(name);
layer.setType(type);
layer.setServer_resource(server_resource);
layer.setEnabled(enabled != null ? enabled.toLowerCase().equals("true")
: false);
layer.setOrder(order_layer);
layer.setPertenece_a_canal(is_channel != null ? is_channel
.toLowerCase().equals("true") : false);
layer.setPublicized(publicized != null ? publicized.toLowerCase()
.equals("true") : false);
//Folder id
if(!StringUtils.isEmpty(folderId)
&& StringUtils.isNumeric(folderId)){
layer.setFolderId(Long.decode(folderId));
}
// Layer properties
if (properties != null) {
layer.setProperties(getMapFromString(properties));
}
- File temp = loadFiles.get(Long.decode(idFile));
- // Layer data
- if (temp != null) {
- layer.setData(temp);
+ //Only if a file has been saved
+ if(idFile != null){
+ File temp = loadFiles.get(Long.decode(idFile));
+ // Layer data
+ if (temp != null) {
+ layer.setData(temp);
+ }
}
// Save the layer
layer = (LayerDto) layerAdminService.create(layer);
if(layer.getId() != null && layer.getData() != null){
loadedLayers.put(layer.getId(), layer.getData());
layer.setData(null);
layer.setServer_resource("rest/persistenceGeo/getLayerResource/"+layer.getId());
}
loadFiles.remove(idFile);
return layer;
}
private static final String PROPERTIES_SEPARATOR = ",,,";
private static final String PROPERTIES_NAM_VALUE_SEPARATOR = "===";
/**
* Parse a string as 'test===valueTest,,,test2===value2' to map of values
*
* @param properties to be parsed
*
* @return map with values
*/
private static Map<String, String> getMapFromString(String properties){
Map<String,String> map = new HashMap<String, String>();
if(properties.split(PROPERTIES_SEPARATOR) != null){
for(String property: properties.split(PROPERTIES_SEPARATOR)){
if(property != null
&& property.split(PROPERTIES_NAM_VALUE_SEPARATOR) != null
&& property.split(PROPERTIES_NAM_VALUE_SEPARATOR).length == 2){
map.put(property.split(PROPERTIES_NAM_VALUE_SEPARATOR)[0], property.split(PROPERTIES_NAM_VALUE_SEPARATOR)[1]);
}
}
}
return map;
}
/**
* This method saves a layer related with a group
*
* @param group
* @param uploadfile
*/
@RequestMapping(value = "/persistenceGeo/saveLayer/{group}", method = RequestMethod.POST)
public @ResponseBody
void saveLayerByGroup(@PathVariable Long group,
@RequestParam("name") String name,
@RequestParam("type") String type,
@RequestParam(value="layerData", required=false) LayerDto layerData,
@RequestParam(value="uploadfile", required=false) MultipartFile uploadfile){
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
// Get the group and his layers
AuthorityDto auth = userAdminService.obtenerGrupoUsuarios(group);
List<String> layersFromGroup = auth.getLayerList();
// Add the new layer
if(layersFromGroup != null){
layersFromGroup.add(name);
auth.setLayerList(layersFromGroup);
}
// Save the group
userAdminService.modificarGrupoUsuarios(auth);
// Create the layerDto
LayerDto layer = new LayerDto();
// Assign the authority
layer.setAuthId(auth.getId());
// Add the request parameters
layer.setName(name);
layer.setType(type);
// Load the layer depend on the layer type
// Save the layer
layerAdminService.create(layer);
}catch (Exception e){
e.printStackTrace();
}
}
/**
* This method saves a folder related with a group
*
* @param group
*/
@RequestMapping(value = "/persistenceGeo/saveFolderByGroup/{groupId}", method = RequestMethod.POST)
public @ResponseBody
FolderDto saveFolderByGroup(@PathVariable String groupId,
@RequestParam("name") String name,
@RequestParam("enabled") String enabled,
@RequestParam("isChannel") String isChannel,
@RequestParam("isPlain") String isPlain,
@RequestParam(value = "parentFolder", required = false) String parentFolder){
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
Long idGroup = Long.decode(groupId);
FolderDto rootFolder = layerAdminService.getRootGroupFolder(idGroup);
if(StringUtils.isEmpty(parentFolder) || !StringUtils.isNumeric(parentFolder)){
return saveFolderBy(name, enabled, isChannel, isPlain,
rootFolder != null ? rootFolder.getId() : null, null, idGroup);
}else{
return saveFolderBy(name, enabled, isChannel, isPlain, Long.decode(parentFolder), null, idGroup);
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
/**
* This method saves a folder related with a user
*
* @param user
*/
@RequestMapping(value = "/persistenceGeo/saveFolder/{username}", method = RequestMethod.POST)
public @ResponseBody
FolderDto saveFolder(@PathVariable String username,
@RequestParam("name") String name,
@RequestParam("enabled") String enabled,
@RequestParam("isChannel") String isChannel,
@RequestParam("isPlain") String isPlain,
@RequestParam(value = "parentFolder", required = false) String parentFolder){
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
UserDto user = userAdminService.obtenerUsuario(username);
if(StringUtils.isEmpty(parentFolder) || !StringUtils.isNumeric(parentFolder)){
FolderDto rootFolder = layerAdminService.getRootFolder(user.getId());
return saveFolderBy(name, enabled, isChannel, isPlain,
rootFolder != null ? rootFolder.getId() : null, user.getId(), null);
}else{
return saveFolderBy(name, enabled, isChannel, isPlain, Long.decode(parentFolder), user.getId(), null);
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
private FolderDto saveFolderBy(String name, String enabled, String isChannel,
String isPlain, Long parentFolder, Long userId, Long groupId){
FolderDto folder = new FolderDto();
folder.setName(name);
folder.setEnabled(enabled != null ? enabled.toLowerCase().equals("true") : false);
folder.setIsChannel(isChannel != null ? isChannel.toLowerCase().equals("true") : false);
folder.setIsPlain(isPlain != null ? isPlain.toLowerCase().equals("true") : false);
folder.setIdParent(parentFolder);
folder.setIdAuth(groupId);
folder.setIdUser(userId);
//TODO: folder.setZoneList(zoneList);
return layerAdminService.saveFolder(folder);
}
/**
* This method loads all folders related with a user
*
* @param username
*
* @return JSON file with folders
*/
@RequestMapping(value = "/persistenceGeo/loadFolders/{username}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
Map<String, Object> loadFolders(@PathVariable String username){
Map<String, Object> result = new HashMap<String, Object>();
List<FolderDto> folders = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
if(username != null){
folders = new LinkedList<FolderDto>();
UserDto user = userAdminService.obtenerUsuario(username);
FolderDto rootFolder = layerAdminService.getRootFolder(user.getId());
FoldersUtils.getFolderTree(rootFolder, folders);
}
result.put(SUCCESS, true);
}catch (Exception e){
e.printStackTrace();
result.put(SUCCESS, false);
}
result.put(RESULTS, folders != null ? folders.size(): 0);
result.put(ROOT, folders);
return result;
}
/**
* This method loads all folders related with a user
*
* @param username
*
* @return JSON file with folders
*/
@RequestMapping(value = "/persistenceGeo/loadFoldersByGroup/{idGroup}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
Map<String, Object> loadFoldersByGroup(@PathVariable String idGroup){
Map<String, Object> result = new HashMap<String, Object>();
List<FolderDto> folders = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
if(idGroup != null){
folders = new LinkedList<FolderDto>();
FolderDto rootFolder = layerAdminService.getRootGroupFolder(Long.decode(idGroup));
FoldersUtils.getFolderTree(rootFolder, folders);
}
result.put(SUCCESS, true);
}catch (Exception e){
e.printStackTrace();
result.put(SUCCESS, false);
}
result.put(RESULTS, folders != null ? folders.size(): 0);
result.put(ROOT, folders);
return result;
}
/**
* Load folder tree by user or group styled
*
* @param type user or group, default group
* @param style tree or string, default string
* @param userOrGroup id group or username
*
* @see FoldersUtils
* @see FolderStyle
*
* @return List of user or group folders parsed with style
*/
@RequestMapping(value = "/persistenceGeo/loadFolders/{type}/{style}/{userOrGroup}", method = RequestMethod.GET,
produces = {MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody
Map<String, Object> loadFolders(@PathVariable String type,
@PathVariable String style,
@PathVariable String userOrGroup){
Map<String, Object> result = new HashMap<String, Object>();
List<FolderDto> folders = null;
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
FolderDto rootFolder;
folders = new LinkedList<FolderDto>();
if(LOAD_FOLDERS_BY_USER.equals(type)){
UserDto user = userAdminService.obtenerUsuario(userOrGroup);
rootFolder = layerAdminService.getRootFolder(user.getId());
}else{
rootFolder = layerAdminService.getRootGroupFolder(Long.decode(userOrGroup));
}
if(LOAD_FOLDERS_STYLE_TREE.equals(style)){
FoldersUtils.getFolderTree(rootFolder, folders, FolderStyle.TREE);
}else{
FoldersUtils.getFolderTree(rootFolder, folders);
}
result.put(SUCCESS, true);
}catch (Exception e){
e.printStackTrace();
result.put(SUCCESS, false);
}
result.put(RESULTS, folders != null ? folders.size(): 0);
result.put(ROOT, folders);
return result;
}
@RequestMapping(value = "/persistenceGeo/deleteLayerByLayerId/{layerId}", method = RequestMethod.POST)
public @ResponseBody
Map<String, Object> DeleteLayerByLayerId(@PathVariable String layerId){
Map<String, Object> result = new HashMap<String, Object>();
try{
/*
//TODO: Secure with logged user
String username = ((UserDetails) SecurityContextHolder.getContext()
.getAuthentication().getPrincipal()).getUsername();
*/
Long idLayer = Long.decode(layerId);
layerAdminService.deleteLayerById(idLayer);
result.put(SUCCESS, true);
result.put(ROOT, new HashMap<String, Object>());
}catch (Exception e) {
e.printStackTrace();
result.put(SUCCESS, false);
result.put(ROOT, "No se ha podido borrar la capa");
}
return result;
}
}
| true | true | private LayerDto copyDataToLayer(String name, String type, String properties,
String enabled, String order_layer, String is_channel,
String publicized, String server_resource,
String idFile, LayerDto layer, String folderId) throws IOException {
// Add request parameter
layer.setName(name);
layer.setType(type);
layer.setServer_resource(server_resource);
layer.setEnabled(enabled != null ? enabled.toLowerCase().equals("true")
: false);
layer.setOrder(order_layer);
layer.setPertenece_a_canal(is_channel != null ? is_channel
.toLowerCase().equals("true") : false);
layer.setPublicized(publicized != null ? publicized.toLowerCase()
.equals("true") : false);
//Folder id
if(!StringUtils.isEmpty(folderId)
&& StringUtils.isNumeric(folderId)){
layer.setFolderId(Long.decode(folderId));
}
// Layer properties
if (properties != null) {
layer.setProperties(getMapFromString(properties));
}
File temp = loadFiles.get(Long.decode(idFile));
// Layer data
if (temp != null) {
layer.setData(temp);
}
// Save the layer
layer = (LayerDto) layerAdminService.create(layer);
if(layer.getId() != null && layer.getData() != null){
loadedLayers.put(layer.getId(), layer.getData());
layer.setData(null);
layer.setServer_resource("rest/persistenceGeo/getLayerResource/"+layer.getId());
}
loadFiles.remove(idFile);
return layer;
}
| private LayerDto copyDataToLayer(String name, String type, String properties,
String enabled, String order_layer, String is_channel,
String publicized, String server_resource,
String idFile, LayerDto layer, String folderId) throws IOException {
// Add request parameter
layer.setName(name);
layer.setType(type);
layer.setServer_resource(server_resource);
layer.setEnabled(enabled != null ? enabled.toLowerCase().equals("true")
: false);
layer.setOrder(order_layer);
layer.setPertenece_a_canal(is_channel != null ? is_channel
.toLowerCase().equals("true") : false);
layer.setPublicized(publicized != null ? publicized.toLowerCase()
.equals("true") : false);
//Folder id
if(!StringUtils.isEmpty(folderId)
&& StringUtils.isNumeric(folderId)){
layer.setFolderId(Long.decode(folderId));
}
// Layer properties
if (properties != null) {
layer.setProperties(getMapFromString(properties));
}
//Only if a file has been saved
if(idFile != null){
File temp = loadFiles.get(Long.decode(idFile));
// Layer data
if (temp != null) {
layer.setData(temp);
}
}
// Save the layer
layer = (LayerDto) layerAdminService.create(layer);
if(layer.getId() != null && layer.getData() != null){
loadedLayers.put(layer.getId(), layer.getData());
layer.setData(null);
layer.setServer_resource("rest/persistenceGeo/getLayerResource/"+layer.getId());
}
loadFiles.remove(idFile);
return layer;
}
|
diff --git a/core/jar/src/main/java/org/mobicents/slee/resource/TCKResourceAdaptorWrapper.java b/core/jar/src/main/java/org/mobicents/slee/resource/TCKResourceAdaptorWrapper.java
index 1d93160c8..4776c5d45 100755
--- a/core/jar/src/main/java/org/mobicents/slee/resource/TCKResourceAdaptorWrapper.java
+++ b/core/jar/src/main/java/org/mobicents/slee/resource/TCKResourceAdaptorWrapper.java
@@ -1,304 +1,304 @@
/*
* Created on Nov 19, 2004
*
* The Open SLEE Project
*
* A SLEE for the People
*
* The source code contained in this file is in in the public domain.
* It can be used in any project or product without prior permission,
* license or royalty payments. There is no claim of correctness and
* NO WARRANTY OF ANY KIND provided with this code.
*/
package org.mobicents.slee.resource;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Properties;
import javax.slee.Address;
import javax.slee.InvalidStateException;
import javax.slee.resource.ActivityHandle;
import javax.slee.resource.BootstrapContext;
import javax.slee.resource.FailureReason;
import javax.slee.resource.Marshaler;
import javax.slee.resource.ResourceException;
import org.jboss.logging.Logger;
import org.mobicents.slee.container.SleeContainer;
import org.mobicents.slee.resource.tck.TCKActivityHandle;
import org.mobicents.slee.resource.tck.TCKMarshaller;
import com.opencloud.logging.LogLevel;
import com.opencloud.logging.PrintWriterLog;
import com.opencloud.sleetck.lib.TCKTestErrorException;
import com.opencloud.sleetck.lib.resource.adaptor.TCKResourceAdaptorInterface;
import com.opencloud.sleetck.lib.resource.adaptor.TCKResourceFactory;
import com.opencloud.sleetck.lib.resource.adaptor.TCKResourceSetupInterface;
import com.opencloud.sleetck.lib.resource.events.TCKResourceEvent;
import com.opencloud.sleetck.lib.resource.sbbapi.TCKActivityContextInterfaceFactory;
import com.opencloud.sleetck.lib.resource.sbbapi.TCKResourceAdaptorSbbInterface;
import com.opencloud.sleetck.lib.resource.sbbapi.TCKResourceSbbInterface;
import com.opencloud.sleetck.lib.resource.sbbapi.TransactionIDAccess;
import com.opencloud.sleetck.lib.resource.testapi.TCKResourceTestInterface;
/**
* Resource adaptor for the TCK.
*
* @author F.Moggia
* @author M. Ranganathan ( hacks )
*/
public class TCKResourceAdaptorWrapper implements javax.slee.resource.ResourceAdaptor,
TCKResourceAdaptorSbbInterface, Serializable {
private static TCKResourceSetupInterface tckResourceSetup;
private transient TCKResourceEventHandlerImpl eventHandler;
private TCKResourceAdaptorInterface tckResourceAdaptor;
private TCKResourceAdaptorSbbInterface factoryInterface;
private TCKResourceSbbInterface sbbInterface;
private TCKActivityContextInterfaceFactory tckACIFactory;
//private transient ResourceAdaptorEntity resourceAdaptorEntity;
private static Logger log;
private Marshaler marshaller;
static {
log = Logger.getLogger(TCKResourceAdaptorWrapper.class);
}
public TCKResourceAdaptorWrapper() {
//new Exception().printStackTrace();
marshaller = new TCKMarshaller();
try {
tckResourceSetup = TCKResourceFactory.createResource();
tckResourceAdaptor = tckResourceSetup.getResourceAdaptorInterface();
try {
- tckResourceSetup.setLog(new PrintWriterLog(new PrintWriter(new FileWriter("TCKRA.log")),LogLevel.FINEST,true,true));
+ tckResourceSetup.setLog(new PrintWriterLog(new PrintWriter(new FileWriter(SleeContainer.getDeployPath() + "/TCKRA.log")),LogLevel.FINEST,true,true));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//factoryInterface = this;
sbbInterface = this.tckResourceAdaptor.getSbbInterface();
} catch (TCKTestErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void init(BootstrapContext context) throws ResourceException, NullPointerException {
eventHandler = new TCKResourceEventHandlerImpl(context, this.tckResourceAdaptor);
try {
this.tckResourceAdaptor = tckResourceSetup.getResourceAdaptorInterface();
} catch (TCKTestErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void configure(Properties properties) throws InvalidStateException {
}
public void start() throws ResourceException {
try {
TCKResourceTestInterface testInterface = tckResourceSetup.getTestInterface();
SleeContainer slee = SleeContainer.lookupFromJndi();
int port = slee.getRmiRegistryPort();
Registry rmiRegistry = LocateRegistry.getRegistry(port);
Class tcktest = Thread.currentThread().getContextClassLoader().loadClass("com.opencloud.sleetck.lib.resource.impl.TCKResourceTestInterfaceImpl");
rmiRegistry.rebind("TCKResourceTestInterface", testInterface);
log.debug("bound TCKResourceTestInterface");
} catch (Exception e) {
throw new ResourceException("Error binding test interface", e);
}
try {
this.tckResourceAdaptor.addEventHandler(eventHandler);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
}
public void stopping() {
// TODO Auto-generated method stub
}
public Object getInterface() {
// TODO Auto-generated method stub
return null;
}
public Object getFactoryInterface() {
// TODO Auto-generated method stub
return this;
}
public TCKResourceSbbInterface getResource() {
return sbbInterface;
}
public TransactionIDAccess getTransactionIDAccess() {
return SleeContainer.lookupFromJndi().getTransactionIDAccess();
}
public Object getActivityContextInterfaceFactory() {
return this.tckACIFactory;
}
public void setActivityContextInterfaceFactory(TCKActivityContextInterfaceFactory acif) {
this.tckACIFactory = acif;
}
/* (non-Javadoc)
* @see org.mobicents.slee.resource.ResourceAdaptor#setResourceAdaptorEntity(gov.nist.slee.resource.ResourceAdaptorEntity)
*/
/*public void setResourceAdaptorEntity(ResourceAdaptorEntity resourceAdaptorEntity) {
this.resourceAdaptorEntity = resourceAdaptorEntity;
}*/
public void entityCreated(BootstrapContext ctx) throws ResourceException {
init(ctx);
}
public void entityRemoved() {
// TODO Auto-generated method stub
}
public void entityActivated() throws ResourceException {
this.start();
}
public void entityDeactivating() {
// TODO Auto-generated method stub
}
public void entityDeactivated() {
// TODO Auto-generated method stub
}
public void eventProcessingSuccessful(ActivityHandle activityHandle,
Object event, int eventId, Address address, int arg4) {
try {
if ( event instanceof TCKResourceEvent) {
this.tckResourceAdaptor.onEventProcessingSuccessful(((TCKResourceEvent) event).getEventObjectID());
if ( log.isDebugEnabled())
log.debug("eventProcessingSuccessfull called for " + event);
} else {
if (log.isDebugEnabled())
log.debug("eventProcessingSucessful for " + event);
}
} catch ( Exception ex) {
throw new RuntimeException("Unexpected exception ", ex);
}
}
public void eventProcessingFailed(ActivityHandle arg0, Object arg1, int arg2, Address arg3, int arg4, FailureReason arg5) {
// TODO Auto-generated method stub
}
public void activityEnded(ActivityHandle ah) {
try {
TCKActivityHandle tckh = (TCKActivityHandle)ah;
this.tckResourceAdaptor.onActivityContextInvalid(tckh.getActivityID());
} catch (RemoteException e) {
log.error("Failed activityEnded", e);
}
}
public void activityUnreferenced(ActivityHandle arg0) {
// TODO Auto-generated method stub
}
public void queryLiveness(ActivityHandle arg0) {
// TODO Auto-generated method stub
}
public Object getActivity(ActivityHandle handle) {
TCKActivityHandle tckHandle = (TCKActivityHandle) handle;
try {
Object retval = this.tckResourceAdaptor.getActivity(tckHandle.getActivityID());
if ( log.isDebugEnabled()) {
log.debug("getActivity(): returning " + retval);
}
return retval;
} catch (RemoteException e) {
e.printStackTrace();
throw new RuntimeException("Failed to retrieve Activty!", e);
}
}
public ActivityHandle getActivityHandle(Object arg0) {
// TODO Auto-generated method stub
return null;
}
public Object getSBBResourceAdaptorInterface(String arg0) {
// TODO Auto-generated method stub
return this;
}
public Marshaler getMarshaler() {
// TODO Auto-generated method stub
return null;
}
public void serviceInstalled(String arg0, int[] arg1, String[] arg2) {
// TODO Auto-generated method stub
}
public void serviceUninstalled(String arg0) {
// TODO Auto-generated method stub
}
public void serviceActivated(String arg0) {
// TODO Auto-generated method stub
}
public void serviceDeactivated(String arg0) {
// TODO Auto-generated method stub
}
}
| true | true | public TCKResourceAdaptorWrapper() {
//new Exception().printStackTrace();
marshaller = new TCKMarshaller();
try {
tckResourceSetup = TCKResourceFactory.createResource();
tckResourceAdaptor = tckResourceSetup.getResourceAdaptorInterface();
try {
tckResourceSetup.setLog(new PrintWriterLog(new PrintWriter(new FileWriter("TCKRA.log")),LogLevel.FINEST,true,true));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//factoryInterface = this;
sbbInterface = this.tckResourceAdaptor.getSbbInterface();
} catch (TCKTestErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public TCKResourceAdaptorWrapper() {
//new Exception().printStackTrace();
marshaller = new TCKMarshaller();
try {
tckResourceSetup = TCKResourceFactory.createResource();
tckResourceAdaptor = tckResourceSetup.getResourceAdaptorInterface();
try {
tckResourceSetup.setLog(new PrintWriterLog(new PrintWriter(new FileWriter(SleeContainer.getDeployPath() + "/TCKRA.log")),LogLevel.FINEST,true,true));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//factoryInterface = this;
sbbInterface = this.tckResourceAdaptor.getSbbInterface();
} catch (TCKTestErrorException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/CommandCenter/src/com/asksven/commandcenter/valueobjects/CommandsIO.java b/CommandCenter/src/com/asksven/commandcenter/valueobjects/CommandsIO.java
index 3d000e3..b8379f3 100644
--- a/CommandCenter/src/com/asksven/commandcenter/valueobjects/CommandsIO.java
+++ b/CommandCenter/src/com/asksven/commandcenter/valueobjects/CommandsIO.java
@@ -1,227 +1,227 @@
/*
* Copyright (C) 2011 asksven
*
* 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.asksven.commandcenter.valueobjects;
import java.io.File;
import java.io.FileFilter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Environment;
import android.util.Log;
import com.asksven.commandcenter.exec.DataStorage;
/**
* @author sven
*
*/
@SuppressLint("NewApi")
public class CommandsIO
{
private static String TAG = "CommandsIo";
private static CommandsIO m_instance = null;
private static Context m_ctx = null;
public static CommandsIO getInstance(Context ctx)
{
if (m_instance == null)
{
m_instance = new CommandsIO();
m_ctx = ctx;
}
return m_instance;
}
private CommandsIO()
{
}
protected ArrayList<String> getCollectionFilenames()
{
ArrayList<String> myFiles = new ArrayList<String>();
// create directories if the do not exist
if (!externalStorageEnvironmentReady())
{
createExternalStorageEnvironment();
}
File path = getFileDir(m_ctx);
if (path != null)
{
// list the files using our FileFilter
File[] files = path.listFiles(new CommandCollectionFileFilter());
for (File f : files)
{
myFiles.add(f.getName());
}
}
return myFiles;
}
protected boolean externalStorageEnvironmentReady()
{
File path = getFileDir(m_ctx);
if (path != null)
{
return (path.exists());
}
else
{
return false;
}
}
protected void createExternalStorageEnvironment()
{
File path = getFileDir(m_ctx);
if (!DataStorage.isExternalStorageWritable())
{
Log.e(TAG, "External storage is not mounted or writable, aborting");
return;
}
try {
// Make sure the application directory exists.
path.mkdirs();
// Very simple code to copy a picture from the application's
// resource into the external file. Note that this code does
// no error checking, and assumes the picture is small (does not
// try to copy it in chunks). Note that if external storage is
// not currently mounted this will silently fail.
// InputStream is = ctx.getResources().openRawResource(R.drawable.balloons);
// OutputStream os = new FileOutputStream(file);
// byte[] data = new byte[is.available()];
// is.read(data);
// os.write(data);
// is.close();
// os.close();
} catch (Exception e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.e("TAG", "Error creating environment on external storage");
}
}
/**
* A class that implements the Java FileFilter interface for CommandCollections.
*/
public class CommandCollectionFileFilter implements FileFilter
{
private final String[] okFileExtensions =
new String[] {"json"};
public boolean accept(File file)
{
for (String extension : okFileExtensions)
{
if (file.getName().toLowerCase().endsWith(extension))
{
return true;
}
}
return false;
}
}
/**
* Copy the *.json files to the private storage
*/
protected void CopyAssets()
{
AssetManager assetManager = m_ctx.getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(String filename : files)
{
// consider only *.json files
if (filename.endsWith(".json"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(filename);
String strOutFile = DataStorage.getExternalStoragePath(m_ctx) + "/" + filename;
out = new FileOutputStream(strOutFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
- Log.e(TAG, "An error occured while reading " + filename +": " + e.getMessage());
+ Log.e(TAG, "An error occured while reading " + filename);
}
}
}
}
/**
* Write a single file
* @param in the source (in assets)
* @param out the target
* @throws IOException
*/
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
private File getFileDir(Context ctx)
{
File path = null;
try
{
path = m_ctx.getExternalFilesDir(null);
}
catch (NoSuchMethodError e)
{
// on Android 2.1 this method does not exist: alternate method
String packageName = ctx.getPackageName();
File externalPath = Environment.getExternalStorageDirectory();
path = new File(externalPath.getAbsolutePath() +
"/Android/data/" + packageName + "/files");
}
return path;
}
}
| true | true | protected void CopyAssets()
{
AssetManager assetManager = m_ctx.getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(String filename : files)
{
// consider only *.json files
if (filename.endsWith(".json"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(filename);
String strOutFile = DataStorage.getExternalStoragePath(m_ctx) + "/" + filename;
out = new FileOutputStream(strOutFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
Log.e(TAG, "An error occured while reading " + filename +": " + e.getMessage());
}
}
}
}
| protected void CopyAssets()
{
AssetManager assetManager = m_ctx.getAssets();
String[] files = null;
try
{
files = assetManager.list("");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for(String filename : files)
{
// consider only *.json files
if (filename.endsWith(".json"))
{
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open(filename);
String strOutFile = DataStorage.getExternalStoragePath(m_ctx) + "/" + filename;
out = new FileOutputStream(strOutFile);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
Log.e(TAG, "An error occured while reading " + filename);
}
}
}
}
|
diff --git a/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/ConfigWorldBorder.java b/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/ConfigWorldBorder.java
index 318e03d4d..082e0587e 100644
--- a/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/ConfigWorldBorder.java
+++ b/src/FE_SRC_COMMON/com/ForgeEssentials/WorldBorder/ConfigWorldBorder.java
@@ -1,113 +1,113 @@
package com.ForgeEssentials.WorldBorder;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.Property;
import com.ForgeEssentials.WorldBorder.Effects.IEffect;
import com.ForgeEssentials.core.ForgeEssentials;
import com.ForgeEssentials.util.OutputHandler;
/**
* This generates the configuration structure
*
* @author Dries007
*
*/
public class ConfigWorldBorder
{
public static final File wbconfig = new File(ForgeEssentials.FEDIR, "WorldBorder.cfg");
public final Configuration config;
/**
* This list makes sure the effect is in the example file.
* Not used for parsing the list from the config.
*/
public static final List<String> PossibleEffects = Arrays.asList("knockback", "message", "potion", "damage", "smite", "serverkick", "executecommand");
public ConfigWorldBorder()
{
config = new Configuration(wbconfig, true);
penaltiesConfig(config);
commonConfig(config);
config.save();
}
/**
* Does all the rest of the config
* @param config
*/
public static void commonConfig(Configuration config)
{
String category = "Settings";
config.addCustomCategoryComment(category, "Common settings.");
ModuleWorldBorder.logToConsole = config.get(category, "LogToConsole", true, "Enable logging to the server console & the log file").getBoolean(true);
Property prop = config.get(category, "overGenerate", 345);
prop.comment = "The amount of blocks that will be generated outside the radius of the border. This is important!" +
" \nIf you set this high, you will need exponentially more time while generating, but you won't get extra land if a player does pass the border." +
" \nIf you use something like Dynmap you should put this number higher, if the border is not there for aesthetic purposes, then you don't need that." +
" \nThe default value (345) is calcultated like this: (20 chuncks for vieuw distance * 16 blocks per chunck) + 25 as backup" +
" \nThis allows players to pass the border 25 blocks before generating new land.";
ModuleWorldBorder.overGenerate = prop.getInt(345);
}
/**
* Does penalty part on config
* @param config
*/
public static void penaltiesConfig(Configuration config)
{
- String penaltyBasePackage = IEffect.class.getPackage().getName() + ".";
+ String penaltyBasePackage = "com.ForgeEssentials.WorldBorder.Effects.";
config.addCustomCategoryComment("Penalties", "This is what will happen to the player if he passes the world boder.");
String[] stages = {"Stage1"};
stages = config.get("Penalties", "stages", stages, "If you add an item here, a subcategory will be generated").valueList;
for(String stage : stages)
{
String cat = "Penalties." + stage;
int dist = config.get(cat, "Distance", 0, "The distance outside the border when this gets activated. WARING this needs to be unique! You can specify 2 penalties in 1 stage.").getInt();
String[] effects = {"message", "knockback", "damage"};
effects = config.get(cat, "effects", effects, "Get the list of possibilitys in the example file").valueList;
IEffect[] effctList = new IEffect[effects.length];
int i = 0;
for(String effect : effects)
{
try
{
Class c = Class.forName(penaltyBasePackage + effect.toLowerCase());
try
{
IEffect pentalty = (IEffect) c.newInstance();
pentalty.registerConfig(config, cat + "." + effect);
effctList[i] = pentalty;
i++;
}
catch (Exception e)
{
OutputHandler.SOP("Could not initialize '" + effect + "' in stage '" + stage + "'");
}
}
catch (ClassNotFoundException e)
{
OutputHandler.SOP("'" + effect + "' in the stage '" + stage + "' does not exist!");
}
}
ModuleWorldBorder.registerEffects(dist, effctList);
}
}
}
| true | true | public static void penaltiesConfig(Configuration config)
{
String penaltyBasePackage = IEffect.class.getPackage().getName() + ".";
config.addCustomCategoryComment("Penalties", "This is what will happen to the player if he passes the world boder.");
String[] stages = {"Stage1"};
stages = config.get("Penalties", "stages", stages, "If you add an item here, a subcategory will be generated").valueList;
for(String stage : stages)
{
String cat = "Penalties." + stage;
int dist = config.get(cat, "Distance", 0, "The distance outside the border when this gets activated. WARING this needs to be unique! You can specify 2 penalties in 1 stage.").getInt();
String[] effects = {"message", "knockback", "damage"};
effects = config.get(cat, "effects", effects, "Get the list of possibilitys in the example file").valueList;
IEffect[] effctList = new IEffect[effects.length];
int i = 0;
for(String effect : effects)
{
try
{
Class c = Class.forName(penaltyBasePackage + effect.toLowerCase());
try
{
IEffect pentalty = (IEffect) c.newInstance();
pentalty.registerConfig(config, cat + "." + effect);
effctList[i] = pentalty;
i++;
}
catch (Exception e)
{
OutputHandler.SOP("Could not initialize '" + effect + "' in stage '" + stage + "'");
}
}
catch (ClassNotFoundException e)
{
OutputHandler.SOP("'" + effect + "' in the stage '" + stage + "' does not exist!");
}
}
ModuleWorldBorder.registerEffects(dist, effctList);
}
}
| public static void penaltiesConfig(Configuration config)
{
String penaltyBasePackage = "com.ForgeEssentials.WorldBorder.Effects.";
config.addCustomCategoryComment("Penalties", "This is what will happen to the player if he passes the world boder.");
String[] stages = {"Stage1"};
stages = config.get("Penalties", "stages", stages, "If you add an item here, a subcategory will be generated").valueList;
for(String stage : stages)
{
String cat = "Penalties." + stage;
int dist = config.get(cat, "Distance", 0, "The distance outside the border when this gets activated. WARING this needs to be unique! You can specify 2 penalties in 1 stage.").getInt();
String[] effects = {"message", "knockback", "damage"};
effects = config.get(cat, "effects", effects, "Get the list of possibilitys in the example file").valueList;
IEffect[] effctList = new IEffect[effects.length];
int i = 0;
for(String effect : effects)
{
try
{
Class c = Class.forName(penaltyBasePackage + effect.toLowerCase());
try
{
IEffect pentalty = (IEffect) c.newInstance();
pentalty.registerConfig(config, cat + "." + effect);
effctList[i] = pentalty;
i++;
}
catch (Exception e)
{
OutputHandler.SOP("Could not initialize '" + effect + "' in stage '" + stage + "'");
}
}
catch (ClassNotFoundException e)
{
OutputHandler.SOP("'" + effect + "' in the stage '" + stage + "' does not exist!");
}
}
ModuleWorldBorder.registerEffects(dist, effctList);
}
}
|
diff --git a/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/validate/AllValidateTests.java b/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/validate/AllValidateTests.java
index 8f0b42523..0a6456624 100644
--- a/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/validate/AllValidateTests.java
+++ b/tests/org.eclipse.gmf.tests/src/org/eclipse/gmf/tests/validate/AllValidateTests.java
@@ -1,31 +1,32 @@
/**
* Copyright (c) 2006 Borland Software Corporation
*
* 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:
* dvorak - initial API and implementation
*/
package org.eclipse.gmf.tests.validate;
import junit.framework.Test;
import junit.framework.TestSuite;
public class AllValidateTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.gmf.tests.validate"); //$NON-NLS-1$
//$JUnit-BEGIN$
suite.addTestSuite(ConstraintSeverityTest.class);
- suite.addTestSuite(OCLExpressionAdapterTest.class);
- suite.addTestSuite(ConstraintDefTest.class);
- suite.addTestSuite(ValueSpecDefTest.class);
+ suite.addTestSuite(OCLExpressionAdapterTest.class);
+// FIXME next two tests were commented out due to bug #230418
+// suite.addTestSuite(ConstraintDefTest.class);
+// suite.addTestSuite(ValueSpecDefTest.class);
//$JUnit-END$
return suite;
}
}
| true | true | public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.gmf.tests.validate"); //$NON-NLS-1$
//$JUnit-BEGIN$
suite.addTestSuite(ConstraintSeverityTest.class);
suite.addTestSuite(OCLExpressionAdapterTest.class);
suite.addTestSuite(ConstraintDefTest.class);
suite.addTestSuite(ValueSpecDefTest.class);
//$JUnit-END$
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite("Test for org.eclipse.gmf.tests.validate"); //$NON-NLS-1$
//$JUnit-BEGIN$
suite.addTestSuite(ConstraintSeverityTest.class);
suite.addTestSuite(OCLExpressionAdapterTest.class);
// FIXME next two tests were commented out due to bug #230418
// suite.addTestSuite(ConstraintDefTest.class);
// suite.addTestSuite(ValueSpecDefTest.class);
//$JUnit-END$
return suite;
}
|
diff --git a/h2/src/main/org/h2/command/ddl/AlterTableAddConstraint.java b/h2/src/main/org/h2/command/ddl/AlterTableAddConstraint.java
index 5c8f4d242..455a785cf 100644
--- a/h2/src/main/org/h2/command/ddl/AlterTableAddConstraint.java
+++ b/h2/src/main/org/h2/command/ddl/AlterTableAddConstraint.java
@@ -1,399 +1,400 @@
/*
* Copyright 2004-2011 H2 Group. Multiple-Licensed under the H2 License,
* Version 1.0, and under the Eclipse Public License, Version 1.0
* (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.command.ddl;
import java.util.ArrayList;
import java.util.HashSet;
import org.h2.command.CommandInterface;
import org.h2.constant.ErrorCode;
import org.h2.constraint.Constraint;
import org.h2.constraint.ConstraintCheck;
import org.h2.constraint.ConstraintReferential;
import org.h2.constraint.ConstraintUnique;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.New;
/**
* This class represents the statement
* ALTER TABLE ADD CONSTRAINT
*/
public class AlterTableAddConstraint extends SchemaCommand {
private int type;
private String constraintName;
private String tableName;
private IndexColumn[] indexColumns;
private int deleteAction;
private int updateAction;
private Schema refSchema;
private String refTableName;
private IndexColumn[] refIndexColumns;
private Expression checkExpression;
private Index index, refIndex;
private String comment;
private boolean checkExisting;
private boolean primaryKeyHash;
private boolean ifNotExists;
public AlterTableAddConstraint(Session session, Schema schema, boolean ifNotExists) {
super(session, schema);
this.ifNotExists = ifNotExists;
}
private String generateConstraintName(Table table) {
if (constraintName == null) {
constraintName = getSchema().getUniqueConstraintName(session, table);
}
return constraintName;
}
public int update() {
try {
return tryUpdate();
} finally {
getSchema().freeUniqueName(constraintName);
}
}
/**
* Try to execute the statement.
*
* @return the update count
*/
private int tryUpdate() {
if (!transactional) {
session.commit(true);
}
Database db = session.getDatabase();
Table table = getSchema().getTableOrView(session, tableName);
if (getSchema().findConstraint(session, constraintName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, constraintName);
}
session.getUser().checkRight(table, Right.ALL);
db.lockMeta(session);
table.lock(session, true, true);
Constraint constraint;
switch (type) {
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY: {
IndexColumn.mapColumns(indexColumns, table);
index = table.findPrimaryKey();
ArrayList<Constraint> constraints = table.getConstraints();
for (int i = 0; constraints != null && i < constraints.size(); i++) {
Constraint c = constraints.get(i);
if (Constraint.PRIMARY_KEY.equals(c.getConstraintType())) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
}
if (index != null) {
// if there is an index, it must match with the one declared
// we don't test ascending / descending
IndexColumn[] pkCols = index.getIndexColumns();
if (pkCols.length != indexColumns.length) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
for (int i = 0; i < pkCols.length; i++) {
if (pkCols[i].column != indexColumns[i].column) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
}
}
if (index == null) {
IndexType indexType = IndexType.createPrimaryKey(table.isPersistIndexes(), primaryKeyHash);
String indexName = table.getSchema().getUniqueIndexName(session, table, Constants.PREFIX_PRIMARY_KEY);
int id = getObjectId();
try {
index = table.addIndex(session, indexName, id, indexColumns, indexType, true, null);
} finally {
getSchema().freeUniqueName(indexName);
}
}
index.getIndexType().setBelongsToConstraint(true);
int constraintId = getObjectId();
String name = generateConstraintName(table);
ConstraintUnique pk = new ConstraintUnique(getSchema(), constraintId, name, table, true);
pk.setColumns(indexColumns);
pk.setIndex(index, true);
constraint = pk;
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE: {
IndexColumn.mapColumns(indexColumns, table);
boolean isOwner = false;
if (index != null && canUseUniqueIndex(index, table, indexColumns)) {
isOwner = true;
index.getIndexType().setBelongsToConstraint(true);
} else {
index = getUniqueIndex(table, indexColumns);
if (index == null) {
index = createIndex(table, indexColumns, true);
isOwner = true;
}
}
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintUnique unique = new ConstraintUnique(getSchema(), id, name, table, false);
unique.setColumns(indexColumns);
unique.setIndex(index, isOwner);
constraint = unique;
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_CHECK: {
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintCheck check = new ConstraintCheck(getSchema(), id, name, table);
TableFilter filter = new TableFilter(session, table, null, false, null);
checkExpression.mapColumns(filter, 0);
checkExpression = checkExpression.optimize(session);
check.setExpression(checkExpression);
check.setTableFilter(filter);
constraint = check;
if (checkExisting) {
check.checkExistingData(session);
}
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL: {
Table refTable = refSchema.getTableOrView(session, refTableName);
session.getUser().checkRight(refTable, Right.ALL);
if (!refTable.canReference()) {
throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, "Reference " + refTable.getSQL());
}
boolean isOwner = false;
IndexColumn.mapColumns(indexColumns, table);
if (index != null && canUseIndex(index, table, indexColumns)) {
isOwner = true;
index.getIndexType().setBelongsToConstraint(true);
} else {
index = getIndex(table, indexColumns);
if (index == null) {
index = createIndex(table, indexColumns, false);
isOwner = true;
}
}
if (refIndexColumns == null) {
Index refIdx = refTable.getPrimaryKey();
refIndexColumns = refIdx.getIndexColumns();
} else {
IndexColumn.mapColumns(refIndexColumns, refTable);
}
if (refIndexColumns.length != indexColumns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
boolean isRefOwner = false;
- if (refIndex != null && refIndex.getTable() == refTable) {
+ if (refIndex != null && refIndex.getTable() == refTable &&
+ canUseIndex(refIndex, refTable, refIndexColumns)) {
isRefOwner = true;
refIndex.getIndexType().setBelongsToConstraint(true);
} else {
refIndex = null;
}
if (refIndex == null) {
refIndex = getUniqueIndex(refTable, refIndexColumns);
if (refIndex == null) {
refIndex = createIndex(refTable, refIndexColumns, true);
isRefOwner = true;
}
}
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintReferential ref = new ConstraintReferential(getSchema(), id, name, table);
ref.setColumns(indexColumns);
ref.setIndex(index, isOwner);
ref.setRefTable(refTable);
ref.setRefColumns(refIndexColumns);
ref.setRefIndex(refIndex, isRefOwner);
if (checkExisting) {
ref.checkExistingData(session);
}
constraint = ref;
refTable.addConstraint(constraint);
ref.setDeleteAction(deleteAction);
ref.setUpdateAction(updateAction);
break;
}
default:
throw DbException.throwInternalError("type=" + type);
}
// parent relationship is already set with addConstraint
constraint.setComment(comment);
if (table.isTemporary() && !table.isGlobalTemporary()) {
session.addLocalTempTableConstraint(constraint);
} else {
db.addSchemaObject(session, constraint);
}
table.addConstraint(constraint);
return 0;
}
private Index createIndex(Table t, IndexColumn[] cols, boolean unique) {
int indexId = getObjectId();
IndexType indexType;
if (unique) {
// for unique constraints
indexType = IndexType.createUnique(t.isPersistIndexes(), false);
} else {
// constraints
indexType = IndexType.createNonUnique(t.isPersistIndexes());
}
indexType.setBelongsToConstraint(true);
String prefix = constraintName == null ? "CONSTRAINT" : constraintName;
String indexName = t.getSchema().getUniqueIndexName(session, t, prefix + "_INDEX_");
try {
return t.addIndex(session, indexName, indexId, cols, indexType, true, null);
} finally {
getSchema().freeUniqueName(indexName);
}
}
public void setDeleteAction(int action) {
this.deleteAction = action;
}
public void setUpdateAction(int action) {
this.updateAction = action;
}
private static Index getUniqueIndex(Table t, IndexColumn[] cols) {
for (Index idx : t.getIndexes()) {
if (canUseUniqueIndex(idx, t, cols)) {
return idx;
}
}
return null;
}
private static Index getIndex(Table t, IndexColumn[] cols) {
for (Index idx : t.getIndexes()) {
if (canUseIndex(idx, t, cols)) {
return idx;
}
}
return null;
}
private static boolean canUseUniqueIndex(Index idx, Table table, IndexColumn[] cols) {
if (idx.getTable() != table || !idx.getIndexType().isUnique()) {
return false;
}
Column[] indexCols = idx.getColumns();
if (indexCols.length > cols.length) {
return false;
}
HashSet<Column> set = New.hashSet();
for (IndexColumn c : cols) {
set.add(c.column);
}
for (Column c : indexCols) {
// all columns of the index must be part of the list,
// but not all columns of the list need to be part of the index
if (!set.contains(c)) {
return false;
}
}
return true;
}
private static boolean canUseIndex(Index existingIndex, Table table, IndexColumn[] cols) {
if (existingIndex.getTable() != table || existingIndex.getCreateSQL() == null) {
// can't use the scan index or index of another table
return false;
}
Column[] indexCols = existingIndex.getColumns();
if (indexCols.length < cols.length) {
return false;
}
for (IndexColumn col : cols) {
// all columns of the list must be part of the index,
// but not all columns of the index need to be part of the list
// holes are not allowed (index=a,b,c & list=a,b is ok; but list=a,c
// is not)
int idx = existingIndex.getColumnIndex(col.column);
if (idx < 0 || idx >= cols.length) {
return false;
}
}
return true;
}
public void setConstraintName(String constraintName) {
this.constraintName = constraintName;
}
public void setType(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setCheckExpression(Expression expression) {
this.checkExpression = expression;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setIndexColumns(IndexColumn[] indexColumns) {
this.indexColumns = indexColumns;
}
public IndexColumn[] getIndexColumns() {
return indexColumns;
}
/**
* Set the referenced table.
*
* @param refSchema the schema
* @param ref the table name
*/
public void setRefTableName(Schema refSchema, String ref) {
this.refSchema = refSchema;
this.refTableName = ref;
}
public void setRefIndexColumns(IndexColumn[] indexColumns) {
this.refIndexColumns = indexColumns;
}
public void setIndex(Index index) {
this.index = index;
}
public void setRefIndex(Index refIndex) {
this.refIndex = refIndex;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setCheckExisting(boolean b) {
this.checkExisting = b;
}
public void setPrimaryKeyHash(boolean b) {
this.primaryKeyHash = b;
}
}
| true | true | private int tryUpdate() {
if (!transactional) {
session.commit(true);
}
Database db = session.getDatabase();
Table table = getSchema().getTableOrView(session, tableName);
if (getSchema().findConstraint(session, constraintName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, constraintName);
}
session.getUser().checkRight(table, Right.ALL);
db.lockMeta(session);
table.lock(session, true, true);
Constraint constraint;
switch (type) {
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY: {
IndexColumn.mapColumns(indexColumns, table);
index = table.findPrimaryKey();
ArrayList<Constraint> constraints = table.getConstraints();
for (int i = 0; constraints != null && i < constraints.size(); i++) {
Constraint c = constraints.get(i);
if (Constraint.PRIMARY_KEY.equals(c.getConstraintType())) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
}
if (index != null) {
// if there is an index, it must match with the one declared
// we don't test ascending / descending
IndexColumn[] pkCols = index.getIndexColumns();
if (pkCols.length != indexColumns.length) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
for (int i = 0; i < pkCols.length; i++) {
if (pkCols[i].column != indexColumns[i].column) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
}
}
if (index == null) {
IndexType indexType = IndexType.createPrimaryKey(table.isPersistIndexes(), primaryKeyHash);
String indexName = table.getSchema().getUniqueIndexName(session, table, Constants.PREFIX_PRIMARY_KEY);
int id = getObjectId();
try {
index = table.addIndex(session, indexName, id, indexColumns, indexType, true, null);
} finally {
getSchema().freeUniqueName(indexName);
}
}
index.getIndexType().setBelongsToConstraint(true);
int constraintId = getObjectId();
String name = generateConstraintName(table);
ConstraintUnique pk = new ConstraintUnique(getSchema(), constraintId, name, table, true);
pk.setColumns(indexColumns);
pk.setIndex(index, true);
constraint = pk;
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE: {
IndexColumn.mapColumns(indexColumns, table);
boolean isOwner = false;
if (index != null && canUseUniqueIndex(index, table, indexColumns)) {
isOwner = true;
index.getIndexType().setBelongsToConstraint(true);
} else {
index = getUniqueIndex(table, indexColumns);
if (index == null) {
index = createIndex(table, indexColumns, true);
isOwner = true;
}
}
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintUnique unique = new ConstraintUnique(getSchema(), id, name, table, false);
unique.setColumns(indexColumns);
unique.setIndex(index, isOwner);
constraint = unique;
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_CHECK: {
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintCheck check = new ConstraintCheck(getSchema(), id, name, table);
TableFilter filter = new TableFilter(session, table, null, false, null);
checkExpression.mapColumns(filter, 0);
checkExpression = checkExpression.optimize(session);
check.setExpression(checkExpression);
check.setTableFilter(filter);
constraint = check;
if (checkExisting) {
check.checkExistingData(session);
}
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL: {
Table refTable = refSchema.getTableOrView(session, refTableName);
session.getUser().checkRight(refTable, Right.ALL);
if (!refTable.canReference()) {
throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, "Reference " + refTable.getSQL());
}
boolean isOwner = false;
IndexColumn.mapColumns(indexColumns, table);
if (index != null && canUseIndex(index, table, indexColumns)) {
isOwner = true;
index.getIndexType().setBelongsToConstraint(true);
} else {
index = getIndex(table, indexColumns);
if (index == null) {
index = createIndex(table, indexColumns, false);
isOwner = true;
}
}
if (refIndexColumns == null) {
Index refIdx = refTable.getPrimaryKey();
refIndexColumns = refIdx.getIndexColumns();
} else {
IndexColumn.mapColumns(refIndexColumns, refTable);
}
if (refIndexColumns.length != indexColumns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
boolean isRefOwner = false;
if (refIndex != null && refIndex.getTable() == refTable) {
isRefOwner = true;
refIndex.getIndexType().setBelongsToConstraint(true);
} else {
refIndex = null;
}
if (refIndex == null) {
refIndex = getUniqueIndex(refTable, refIndexColumns);
if (refIndex == null) {
refIndex = createIndex(refTable, refIndexColumns, true);
isRefOwner = true;
}
}
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintReferential ref = new ConstraintReferential(getSchema(), id, name, table);
ref.setColumns(indexColumns);
ref.setIndex(index, isOwner);
ref.setRefTable(refTable);
ref.setRefColumns(refIndexColumns);
ref.setRefIndex(refIndex, isRefOwner);
if (checkExisting) {
ref.checkExistingData(session);
}
constraint = ref;
refTable.addConstraint(constraint);
ref.setDeleteAction(deleteAction);
ref.setUpdateAction(updateAction);
break;
}
default:
throw DbException.throwInternalError("type=" + type);
}
// parent relationship is already set with addConstraint
constraint.setComment(comment);
if (table.isTemporary() && !table.isGlobalTemporary()) {
session.addLocalTempTableConstraint(constraint);
} else {
db.addSchemaObject(session, constraint);
}
table.addConstraint(constraint);
return 0;
}
| private int tryUpdate() {
if (!transactional) {
session.commit(true);
}
Database db = session.getDatabase();
Table table = getSchema().getTableOrView(session, tableName);
if (getSchema().findConstraint(session, constraintName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, constraintName);
}
session.getUser().checkRight(table, Right.ALL);
db.lockMeta(session);
table.lock(session, true, true);
Constraint constraint;
switch (type) {
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY: {
IndexColumn.mapColumns(indexColumns, table);
index = table.findPrimaryKey();
ArrayList<Constraint> constraints = table.getConstraints();
for (int i = 0; constraints != null && i < constraints.size(); i++) {
Constraint c = constraints.get(i);
if (Constraint.PRIMARY_KEY.equals(c.getConstraintType())) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
}
if (index != null) {
// if there is an index, it must match with the one declared
// we don't test ascending / descending
IndexColumn[] pkCols = index.getIndexColumns();
if (pkCols.length != indexColumns.length) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
for (int i = 0; i < pkCols.length; i++) {
if (pkCols[i].column != indexColumns[i].column) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
}
}
if (index == null) {
IndexType indexType = IndexType.createPrimaryKey(table.isPersistIndexes(), primaryKeyHash);
String indexName = table.getSchema().getUniqueIndexName(session, table, Constants.PREFIX_PRIMARY_KEY);
int id = getObjectId();
try {
index = table.addIndex(session, indexName, id, indexColumns, indexType, true, null);
} finally {
getSchema().freeUniqueName(indexName);
}
}
index.getIndexType().setBelongsToConstraint(true);
int constraintId = getObjectId();
String name = generateConstraintName(table);
ConstraintUnique pk = new ConstraintUnique(getSchema(), constraintId, name, table, true);
pk.setColumns(indexColumns);
pk.setIndex(index, true);
constraint = pk;
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE: {
IndexColumn.mapColumns(indexColumns, table);
boolean isOwner = false;
if (index != null && canUseUniqueIndex(index, table, indexColumns)) {
isOwner = true;
index.getIndexType().setBelongsToConstraint(true);
} else {
index = getUniqueIndex(table, indexColumns);
if (index == null) {
index = createIndex(table, indexColumns, true);
isOwner = true;
}
}
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintUnique unique = new ConstraintUnique(getSchema(), id, name, table, false);
unique.setColumns(indexColumns);
unique.setIndex(index, isOwner);
constraint = unique;
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_CHECK: {
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintCheck check = new ConstraintCheck(getSchema(), id, name, table);
TableFilter filter = new TableFilter(session, table, null, false, null);
checkExpression.mapColumns(filter, 0);
checkExpression = checkExpression.optimize(session);
check.setExpression(checkExpression);
check.setTableFilter(filter);
constraint = check;
if (checkExisting) {
check.checkExistingData(session);
}
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL: {
Table refTable = refSchema.getTableOrView(session, refTableName);
session.getUser().checkRight(refTable, Right.ALL);
if (!refTable.canReference()) {
throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, "Reference " + refTable.getSQL());
}
boolean isOwner = false;
IndexColumn.mapColumns(indexColumns, table);
if (index != null && canUseIndex(index, table, indexColumns)) {
isOwner = true;
index.getIndexType().setBelongsToConstraint(true);
} else {
index = getIndex(table, indexColumns);
if (index == null) {
index = createIndex(table, indexColumns, false);
isOwner = true;
}
}
if (refIndexColumns == null) {
Index refIdx = refTable.getPrimaryKey();
refIndexColumns = refIdx.getIndexColumns();
} else {
IndexColumn.mapColumns(refIndexColumns, refTable);
}
if (refIndexColumns.length != indexColumns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
boolean isRefOwner = false;
if (refIndex != null && refIndex.getTable() == refTable &&
canUseIndex(refIndex, refTable, refIndexColumns)) {
isRefOwner = true;
refIndex.getIndexType().setBelongsToConstraint(true);
} else {
refIndex = null;
}
if (refIndex == null) {
refIndex = getUniqueIndex(refTable, refIndexColumns);
if (refIndex == null) {
refIndex = createIndex(refTable, refIndexColumns, true);
isRefOwner = true;
}
}
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintReferential ref = new ConstraintReferential(getSchema(), id, name, table);
ref.setColumns(indexColumns);
ref.setIndex(index, isOwner);
ref.setRefTable(refTable);
ref.setRefColumns(refIndexColumns);
ref.setRefIndex(refIndex, isRefOwner);
if (checkExisting) {
ref.checkExistingData(session);
}
constraint = ref;
refTable.addConstraint(constraint);
ref.setDeleteAction(deleteAction);
ref.setUpdateAction(updateAction);
break;
}
default:
throw DbException.throwInternalError("type=" + type);
}
// parent relationship is already set with addConstraint
constraint.setComment(comment);
if (table.isTemporary() && !table.isGlobalTemporary()) {
session.addLocalTempTableConstraint(constraint);
} else {
db.addSchemaObject(session, constraint);
}
table.addConstraint(constraint);
return 0;
}
|
diff --git a/modules/axiom-tests/src/test/java/org/apache/axiom/om/impl/llom/OMStAXWrapperTest.java b/modules/axiom-tests/src/test/java/org/apache/axiom/om/impl/llom/OMStAXWrapperTest.java
index 703a54ea3..3fd0c00cf 100644
--- a/modules/axiom-tests/src/test/java/org/apache/axiom/om/impl/llom/OMStAXWrapperTest.java
+++ b/modules/axiom-tests/src/test/java/org/apache/axiom/om/impl/llom/OMStAXWrapperTest.java
@@ -1,95 +1,95 @@
/*
* 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.axiom.om.impl.llom;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamReader;
import junit.framework.TestCase;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMText;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.impl.llom.factory.OMLinkedListImplFactory;
import org.apache.axiom.om.util.StAXUtils;
public class OMStAXWrapperTest extends TestCase {
// Regression test for WSCOMMONS-338 and WSCOMMONS-341
public void testCDATAEvent_FromParser() throws Exception {
// Make sure that the parser is non coalescing (otherwise no CDATA events will be
// reported). This is not the default for Woodstox (see WSTX-140).
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
// Create an element with a CDATA section.
InputStream is = new ByteArrayInputStream("<test><![CDATA[hello world]]></test>".getBytes());
XMLStreamReader reader = factory.createXMLStreamReader(is);
OMFactory omfactory = new OMLinkedListImplFactory();
OMElement element = new StAXOMBuilder(omfactory, reader).getDocumentElement();
// Build the element so we have a full StAX tree
element.build();
// Get the XMLStreamReader for the element. This will return an OMStAXWrapper.
XMLStreamReader reader2 = element.getXMLStreamReader();
// Check the sequence of events
int event = reader2.next();
assertEquals(XMLStreamReader.START_ELEMENT, event);
while (reader2.hasNext() && event != XMLStreamReader.CDATA) {
event = reader2.next();
}
// Only woodstox is guaranteed to generate CDATA events if javax.xml.stream.isCoalescing=false
- if (reader.toString().contains("wstx")) {
+ if (reader.toString().indexOf("wstx")!=-1) {
assertEquals(XMLStreamReader.CDATA, event);
assertEquals("hello world", reader2.getText()); // WSCOMMONS-341
assertTrue(Arrays.equals("hello world".toCharArray(), reader2.getTextCharacters())); // WSCOMMONS-338
assertEquals(XMLStreamReader.END_ELEMENT, reader2.next());
}
}
public void testCDATAEvent_FromElement() throws Exception {
OMFactory omfactory = new OMLinkedListImplFactory();
OMElement element = omfactory.createOMElement("test", null);
OMText cdata = omfactory.createOMText("hello world", OMNode.CDATA_SECTION_NODE);
element.addChild(cdata);
// Get the XMLStreamReader for the element. This will return an OMStAXWrapper.
XMLStreamReader reader2 = element.getXMLStreamReader();
// Check the sequence of events
int event = reader2.next();
assertEquals(XMLStreamReader.START_ELEMENT, event);
while (reader2.hasNext() && event != XMLStreamReader.CDATA) {
event = reader2.next();
}
assertEquals(XMLStreamReader.CDATA, event);
assertEquals("hello world", reader2.getText()); // WSCOMMONS-341
assertTrue(Arrays.equals("hello world".toCharArray(), reader2.getTextCharacters())); // WSCOMMONS-338
assertEquals(XMLStreamReader.END_ELEMENT, reader2.next());
}
}
| true | true | public void testCDATAEvent_FromParser() throws Exception {
// Make sure that the parser is non coalescing (otherwise no CDATA events will be
// reported). This is not the default for Woodstox (see WSTX-140).
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
// Create an element with a CDATA section.
InputStream is = new ByteArrayInputStream("<test><![CDATA[hello world]]></test>".getBytes());
XMLStreamReader reader = factory.createXMLStreamReader(is);
OMFactory omfactory = new OMLinkedListImplFactory();
OMElement element = new StAXOMBuilder(omfactory, reader).getDocumentElement();
// Build the element so we have a full StAX tree
element.build();
// Get the XMLStreamReader for the element. This will return an OMStAXWrapper.
XMLStreamReader reader2 = element.getXMLStreamReader();
// Check the sequence of events
int event = reader2.next();
assertEquals(XMLStreamReader.START_ELEMENT, event);
while (reader2.hasNext() && event != XMLStreamReader.CDATA) {
event = reader2.next();
}
// Only woodstox is guaranteed to generate CDATA events if javax.xml.stream.isCoalescing=false
if (reader.toString().contains("wstx")) {
assertEquals(XMLStreamReader.CDATA, event);
assertEquals("hello world", reader2.getText()); // WSCOMMONS-341
assertTrue(Arrays.equals("hello world".toCharArray(), reader2.getTextCharacters())); // WSCOMMONS-338
assertEquals(XMLStreamReader.END_ELEMENT, reader2.next());
}
}
| public void testCDATAEvent_FromParser() throws Exception {
// Make sure that the parser is non coalescing (otherwise no CDATA events will be
// reported). This is not the default for Woodstox (see WSTX-140).
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
// Create an element with a CDATA section.
InputStream is = new ByteArrayInputStream("<test><![CDATA[hello world]]></test>".getBytes());
XMLStreamReader reader = factory.createXMLStreamReader(is);
OMFactory omfactory = new OMLinkedListImplFactory();
OMElement element = new StAXOMBuilder(omfactory, reader).getDocumentElement();
// Build the element so we have a full StAX tree
element.build();
// Get the XMLStreamReader for the element. This will return an OMStAXWrapper.
XMLStreamReader reader2 = element.getXMLStreamReader();
// Check the sequence of events
int event = reader2.next();
assertEquals(XMLStreamReader.START_ELEMENT, event);
while (reader2.hasNext() && event != XMLStreamReader.CDATA) {
event = reader2.next();
}
// Only woodstox is guaranteed to generate CDATA events if javax.xml.stream.isCoalescing=false
if (reader.toString().indexOf("wstx")!=-1) {
assertEquals(XMLStreamReader.CDATA, event);
assertEquals("hello world", reader2.getText()); // WSCOMMONS-341
assertTrue(Arrays.equals("hello world".toCharArray(), reader2.getTextCharacters())); // WSCOMMONS-338
assertEquals(XMLStreamReader.END_ELEMENT, reader2.next());
}
}
|
diff --git a/src/com/herocraftonline/dev/heroes/command/commands/AssignSkillCommand.java b/src/com/herocraftonline/dev/heroes/command/commands/AssignSkillCommand.java
index abb9c6d..89102fc 100644
--- a/src/com/herocraftonline/dev/heroes/command/commands/AssignSkillCommand.java
+++ b/src/com/herocraftonline/dev/heroes/command/commands/AssignSkillCommand.java
@@ -1,40 +1,41 @@
package com.herocraftonline.dev.heroes.command.commands;
import java.util.Arrays;
import org.bukkit.Material;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.herocraftonline.dev.heroes.Heroes;
import com.herocraftonline.dev.heroes.command.BaseCommand;
public class AssignSkillCommand extends BaseCommand {
public AssignSkillCommand(Heroes plugin) {
super(plugin);
name = "AssignSkill";
description = "Assigns a skill to an item";
usage = "/assign <spell>";
minArgs = 1;
maxArgs = 1000;
identifiers.add("assign");
}
@Override
public void execute(CommandSender sender, String[] args) {
if (sender instanceof Player) {
- if (args.length>0) {
- if (plugin.getHeroManager().getHero((Player) sender).getPlayerClass().getSkills().contains(args[0])) {
- plugin.getHeroManager().getHero((Player) sender).bind(Material.getMaterial(args[0]), Arrays.copyOf(args, 1));
+ Player player = (Player) sender;
+ if (args.length > 0) {
+ if (plugin.getHeroManager().getHero(player).getPlayerClass().getSkills().contains(args[0])) {
+ plugin.getHeroManager().getHero(player).bind(Material.getMaterial(args[0]), Arrays.copyOf(args, 1));
plugin.getMessager().send(sender, "That has been assigned as your skill", (String[]) null);
} else {
plugin.getMessager().send(sender, "That skill does not exist for your class", (String[]) null);
}
} else {
- plugin.getHeroManager().getHero((Player) sender).unbind(Material.getMaterial(args[0]));
+ plugin.getHeroManager().getHero(player).unbind(Material.getMaterial(args[0]));
plugin.getMessager().send(sender, "Your equipped item is no longer bound to a skill.", (String[]) null);
}
}
}
}
| false | true | public void execute(CommandSender sender, String[] args) {
if (sender instanceof Player) {
if (args.length>0) {
if (plugin.getHeroManager().getHero((Player) sender).getPlayerClass().getSkills().contains(args[0])) {
plugin.getHeroManager().getHero((Player) sender).bind(Material.getMaterial(args[0]), Arrays.copyOf(args, 1));
plugin.getMessager().send(sender, "That has been assigned as your skill", (String[]) null);
} else {
plugin.getMessager().send(sender, "That skill does not exist for your class", (String[]) null);
}
} else {
plugin.getHeroManager().getHero((Player) sender).unbind(Material.getMaterial(args[0]));
plugin.getMessager().send(sender, "Your equipped item is no longer bound to a skill.", (String[]) null);
}
}
}
| public void execute(CommandSender sender, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
if (args.length > 0) {
if (plugin.getHeroManager().getHero(player).getPlayerClass().getSkills().contains(args[0])) {
plugin.getHeroManager().getHero(player).bind(Material.getMaterial(args[0]), Arrays.copyOf(args, 1));
plugin.getMessager().send(sender, "That has been assigned as your skill", (String[]) null);
} else {
plugin.getMessager().send(sender, "That skill does not exist for your class", (String[]) null);
}
} else {
plugin.getHeroManager().getHero(player).unbind(Material.getMaterial(args[0]));
plugin.getMessager().send(sender, "Your equipped item is no longer bound to a skill.", (String[]) null);
}
}
}
|
diff --git a/commons/src/main/java/org/wikimedia/commons/media/MediaDetailFragment.java b/commons/src/main/java/org/wikimedia/commons/media/MediaDetailFragment.java
index 14519326..f12779a3 100644
--- a/commons/src/main/java/org/wikimedia/commons/media/MediaDetailFragment.java
+++ b/commons/src/main/java/org/wikimedia/commons/media/MediaDetailFragment.java
@@ -1,102 +1,102 @@
package org.wikimedia.commons.media;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.actionbarsherlock.app.SherlockFragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import org.wikimedia.commons.Media;
import org.wikimedia.commons.R;
import org.wikimedia.commons.Utils;
public class MediaDetailFragment extends SherlockFragment {
private Media media;
private DisplayImageOptions displayOptions;
public static MediaDetailFragment forMedia(Media media) {
MediaDetailFragment mf = new MediaDetailFragment();
mf.media = media;
return mf;
}
private ImageView image;
private TextView title;
private ProgressBar loadingProgress;
private ImageView loadingFailed;
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable("media", media);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(media == null) {
- media = (Media)savedInstanceState.get("media");
+ media = (Media)savedInstanceState.getParcelable("media");
}
View view = inflater.inflate(R.layout.fragment_media_detail, container, false);
image = (ImageView) view.findViewById(R.id.mediaDetailImage);
title = (TextView) view.findViewById(R.id.mediaDetailTitle);
loadingProgress = (ProgressBar) view.findViewById(R.id.mediaDetailImageLoading);
loadingFailed = (ImageView) view.findViewById(R.id.mediaDetailImageFailed);
String actualUrl = TextUtils.isEmpty(media.getImageUrl()) ? media.getLocalUri().toString() : media.getThumbnailUrl(640);
ImageLoader.getInstance().displayImage(actualUrl, image, displayOptions, new ImageLoadingListener() {
public void onLoadingStarted() {
loadingProgress.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
loadingProgress.setVisibility(View.GONE);
loadingFailed.setVisibility(View.VISIBLE);
}
public void onLoadingComplete(Bitmap bitmap) {
loadingProgress.setVisibility(View.GONE);
loadingFailed.setVisibility(View.GONE);
image.setVisibility(View.VISIBLE);
if(bitmap.hasAlpha()) {
image.setBackgroundResource(android.R.color.white);
}
}
public void onLoadingCancelled() {
// wat?
throw new RuntimeException("Image loading cancelled. But why?");
}
});
title.setText(Utils.displayTitleFromTitle(media.getFilename()));
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
displayOptions = new DisplayImageOptions.Builder().cacheInMemory()
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.displayer(new FadeInBitmapDisplayer(300))
.cacheInMemory()
.cacheOnDisc()
.resetViewBeforeLoading().build();
}
}
| true | true | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(media == null) {
media = (Media)savedInstanceState.get("media");
}
View view = inflater.inflate(R.layout.fragment_media_detail, container, false);
image = (ImageView) view.findViewById(R.id.mediaDetailImage);
title = (TextView) view.findViewById(R.id.mediaDetailTitle);
loadingProgress = (ProgressBar) view.findViewById(R.id.mediaDetailImageLoading);
loadingFailed = (ImageView) view.findViewById(R.id.mediaDetailImageFailed);
String actualUrl = TextUtils.isEmpty(media.getImageUrl()) ? media.getLocalUri().toString() : media.getThumbnailUrl(640);
ImageLoader.getInstance().displayImage(actualUrl, image, displayOptions, new ImageLoadingListener() {
public void onLoadingStarted() {
loadingProgress.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
loadingProgress.setVisibility(View.GONE);
loadingFailed.setVisibility(View.VISIBLE);
}
public void onLoadingComplete(Bitmap bitmap) {
loadingProgress.setVisibility(View.GONE);
loadingFailed.setVisibility(View.GONE);
image.setVisibility(View.VISIBLE);
if(bitmap.hasAlpha()) {
image.setBackgroundResource(android.R.color.white);
}
}
public void onLoadingCancelled() {
// wat?
throw new RuntimeException("Image loading cancelled. But why?");
}
});
title.setText(Utils.displayTitleFromTitle(media.getFilename()));
return view;
}
| public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if(media == null) {
media = (Media)savedInstanceState.getParcelable("media");
}
View view = inflater.inflate(R.layout.fragment_media_detail, container, false);
image = (ImageView) view.findViewById(R.id.mediaDetailImage);
title = (TextView) view.findViewById(R.id.mediaDetailTitle);
loadingProgress = (ProgressBar) view.findViewById(R.id.mediaDetailImageLoading);
loadingFailed = (ImageView) view.findViewById(R.id.mediaDetailImageFailed);
String actualUrl = TextUtils.isEmpty(media.getImageUrl()) ? media.getLocalUri().toString() : media.getThumbnailUrl(640);
ImageLoader.getInstance().displayImage(actualUrl, image, displayOptions, new ImageLoadingListener() {
public void onLoadingStarted() {
loadingProgress.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
loadingProgress.setVisibility(View.GONE);
loadingFailed.setVisibility(View.VISIBLE);
}
public void onLoadingComplete(Bitmap bitmap) {
loadingProgress.setVisibility(View.GONE);
loadingFailed.setVisibility(View.GONE);
image.setVisibility(View.VISIBLE);
if(bitmap.hasAlpha()) {
image.setBackgroundResource(android.R.color.white);
}
}
public void onLoadingCancelled() {
// wat?
throw new RuntimeException("Image loading cancelled. But why?");
}
});
title.setText(Utils.displayTitleFromTitle(media.getFilename()));
return view;
}
|
diff --git a/lucene/src/test/org/apache/lucene/search/QueryUtils.java b/lucene/src/test/org/apache/lucene/search/QueryUtils.java
index 26d02213e..2bbebde0a 100644
--- a/lucene/src/test/org/apache/lucene/search/QueryUtils.java
+++ b/lucene/src/test/org/apache/lucene/search/QueryUtils.java
@@ -1,447 +1,447 @@
package org.apache.lucene.search;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import junit.framework.Assert;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.store.RAMDirectory;
import static org.apache.lucene.util.LuceneTestCaseJ4.TEST_VERSION_CURRENT;
/**
* Copyright 2005 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.
*/
public class QueryUtils {
/** Check the types of things query objects should be able to do. */
public static void check(Query q) {
checkHashEquals(q);
}
/** check very basic hashCode and equals */
public static void checkHashEquals(Query q) {
Query q2 = (Query)q.clone();
checkEqual(q,q2);
Query q3 = (Query)q.clone();
q3.setBoost(7.21792348f);
checkUnequal(q,q3);
// test that a class check is done so that no exception is thrown
// in the implementation of equals()
Query whacky = new Query() {
@Override
public String toString(String field) {
return "My Whacky Query";
}
};
whacky.setBoost(q.getBoost());
checkUnequal(q, whacky);
}
public static void checkEqual(Query q1, Query q2) {
Assert.assertEquals(q1, q2);
Assert.assertEquals(q1.hashCode(), q2.hashCode());
}
public static void checkUnequal(Query q1, Query q2) {
Assert.assertTrue(!q1.equals(q2));
Assert.assertTrue(!q2.equals(q1));
// possible this test can fail on a hash collision... if that
// happens, please change test to use a different example.
Assert.assertTrue(q1.hashCode() != q2.hashCode());
}
/** deep check that explanations of a query 'score' correctly */
public static void checkExplanations (final Query q, final Searcher s) throws IOException {
CheckHits.checkExplanations(q, null, s, true);
}
/**
* Various query sanity checks on a searcher, some checks are only done for
* instanceof IndexSearcher.
*
* @see #check(Query)
* @see #checkFirstSkipTo
* @see #checkSkipTo
* @see #checkExplanations
* @see #checkSerialization
* @see #checkEqual
*/
public static void check(Query q1, Searcher s) {
check(q1, s, true);
}
private static void check(Query q1, Searcher s, boolean wrap) {
try {
check(q1);
if (s!=null) {
if (s instanceof IndexSearcher) {
IndexSearcher is = (IndexSearcher)s;
checkFirstSkipTo(q1,is);
checkSkipTo(q1,is);
if (wrap) {
check(q1, wrapUnderlyingReader(is, -1), false);
check(q1, wrapUnderlyingReader(is, 0), false);
check(q1, wrapUnderlyingReader(is, +1), false);
}
}
if (wrap) {
check(q1, wrapSearcher(s, -1), false);
check(q1, wrapSearcher(s, 0), false);
check(q1, wrapSearcher(s, +1), false);
}
checkExplanations(q1,s);
checkSerialization(q1,s);
Query q2 = (Query)q1.clone();
checkEqual(s.rewrite(q1),
s.rewrite(q2));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* Given an IndexSearcher, returns a new IndexSearcher whose IndexReader
* is a MultiReader containing the Reader of the original IndexSearcher,
* as well as several "empty" IndexReaders -- some of which will have
* deleted documents in them. This new IndexSearcher should
* behave exactly the same as the original IndexSearcher.
* @param s the searcher to wrap
* @param edge if negative, s will be the first sub; if 0, s will be in the middle, if positive s will be the last sub
*/
public static IndexSearcher wrapUnderlyingReader(final IndexSearcher s, final int edge)
throws IOException {
IndexReader r = s.getIndexReader();
// we can't put deleted docs before the nested reader, because
// it will throw off the docIds
IndexReader[] readers = new IndexReader[] {
edge < 0 ? r : IndexReader.open(makeEmptyIndex(0), true),
IndexReader.open(makeEmptyIndex(0), true),
new MultiReader(new IndexReader[] {
IndexReader.open(makeEmptyIndex(edge < 0 ? 4 : 0), true),
IndexReader.open(makeEmptyIndex(0), true),
0 == edge ? r : IndexReader.open(makeEmptyIndex(0), true)
}),
IndexReader.open(makeEmptyIndex(0 < edge ? 0 : 7), true),
IndexReader.open(makeEmptyIndex(0), true),
new MultiReader(new IndexReader[] {
IndexReader.open(makeEmptyIndex(0 < edge ? 0 : 5), true),
IndexReader.open(makeEmptyIndex(0), true),
0 < edge ? r : IndexReader.open(makeEmptyIndex(0), true)
})
};
IndexSearcher out = new IndexSearcher(new MultiReader(readers));
out.setSimilarity(s.getSimilarity());
return out;
}
/**
* Given a Searcher, returns a new MultiSearcher wrapping the
* the original Searcher,
* as well as several "empty" IndexSearchers -- some of which will have
* deleted documents in them. This new MultiSearcher
* should behave exactly the same as the original Searcher.
* @param s the Searcher to wrap
* @param edge if negative, s will be the first sub; if 0, s will be in hte middle, if positive s will be the last sub
*/
public static MultiSearcher wrapSearcher(final Searcher s, final int edge)
throws IOException {
// we can't put deleted docs before the nested reader, because
// it will through off the docIds
Searcher[] searchers = new Searcher[] {
edge < 0 ? s : new IndexSearcher(makeEmptyIndex(0), true),
new MultiSearcher(new Searcher[] {
new IndexSearcher(makeEmptyIndex(edge < 0 ? 65 : 0), true),
new IndexSearcher(makeEmptyIndex(0), true),
0 == edge ? s : new IndexSearcher(makeEmptyIndex(0), true)
}),
new IndexSearcher(makeEmptyIndex(0 < edge ? 0 : 3), true),
new IndexSearcher(makeEmptyIndex(0), true),
new MultiSearcher(new Searcher[] {
new IndexSearcher(makeEmptyIndex(0 < edge ? 0 : 5), true),
new IndexSearcher(makeEmptyIndex(0), true),
0 < edge ? s : new IndexSearcher(makeEmptyIndex(0), true)
})
};
MultiSearcher out = new MultiSearcher(searchers);
out.setSimilarity(s.getSimilarity());
return out;
}
private static RAMDirectory makeEmptyIndex(final int numDeletedDocs)
throws IOException {
RAMDirectory d = new RAMDirectory();
IndexWriter w = new IndexWriter(d, new IndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer()));
for (int i = 0; i < numDeletedDocs; i++) {
w.addDocument(new Document());
}
w.commit();
w.deleteDocuments( new MatchAllDocsQuery() );
w.commit();
if (0 < numDeletedDocs)
Assert.assertTrue("writer has no deletions", w.hasDeletions());
Assert.assertEquals("writer is missing some deleted docs",
numDeletedDocs, w.maxDoc());
Assert.assertEquals("writer has non-deleted docs",
0, w.numDocs());
w.close();
IndexReader r = IndexReader.open(d, true);
Assert.assertEquals("reader has wrong number of deleted docs",
numDeletedDocs, r.numDeletedDocs());
r.close();
return d;
}
/** check that the query weight is serializable.
* @throws IOException if serialization check fail.
*/
private static void checkSerialization(Query q, Searcher s) throws IOException {
Weight w = q.weight(s);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(w);
oos.close();
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
ois.readObject();
ois.close();
//skip equals() test for now - most weights don't override equals() and we won't add this just for the tests.
//TestCase.assertEquals("writeObject(w) != w. ("+w+")",w2,w);
} catch (Exception e) {
IOException e2 = new IOException("Serialization failed for "+w);
e2.initCause(e);
throw e2;
}
}
/** alternate scorer skipTo(),skipTo(),next(),next(),skipTo(),skipTo(), etc
* and ensure a hitcollector receives same docs and scores
*/
public static void checkSkipTo(final Query q, final IndexSearcher s) throws IOException {
//System.out.println("Checking "+q);
if (q.weight(s).scoresDocsOutOfOrder()) return; // in this case order of skipTo() might differ from that of next().
final int skip_op = 0;
final int next_op = 1;
final int orders [][] = {
{next_op},
{skip_op},
{skip_op, next_op},
{next_op, skip_op},
{skip_op, skip_op, next_op, next_op},
{next_op, next_op, skip_op, skip_op},
{skip_op, skip_op, skip_op, next_op, next_op},
};
for (int k = 0; k < orders.length; k++) {
final int order[] = orders[k];
// System.out.print("Order:");for (int i = 0; i < order.length; i++)
// System.out.print(order[i]==skip_op ? " skip()":" next()");
// System.out.println();
final int opidx[] = { 0 };
final int lastDoc[] = {-1};
// FUTURE: ensure scorer.doc()==-1
final float maxDiff = 1e-5f;
final IndexReader lastReader[] = {null};
s.search(q, new Collector() {
private Scorer sc;
private IndexReader reader;
private Scorer scorer;
@Override
public void setScorer(Scorer scorer) throws IOException {
this.sc = scorer;
}
@Override
public void collect(int doc) throws IOException {
float score = sc.score();
lastDoc[0] = doc;
try {
if (scorer == null) {
Weight w = q.weight(s);
scorer = w.scorer(reader, true, false);
}
int op = order[(opidx[0]++) % order.length];
// System.out.println(op==skip_op ?
// "skip("+(sdoc[0]+1)+")":"next()");
boolean more = op == skip_op ? scorer.advance(scorer.docID() + 1) != DocIdSetIterator.NO_MORE_DOCS
: scorer.nextDoc() != DocIdSetIterator.NO_MORE_DOCS;
int scorerDoc = scorer.docID();
float scorerScore = scorer.score();
float scorerScore2 = scorer.score();
float scoreDiff = Math.abs(score - scorerScore);
float scorerDiff = Math.abs(scorerScore2 - scorerScore);
if (!more || doc != scorerDoc || scoreDiff > maxDiff
|| scorerDiff > maxDiff) {
StringBuilder sbord = new StringBuilder();
for (int i = 0; i < order.length; i++)
sbord.append(order[i] == skip_op ? " skip()" : " next()");
throw new RuntimeException("ERROR matching docs:" + "\n\t"
+ (doc != scorerDoc ? "--> " : "") + "doc=" + doc + ", scorerDoc=" + scorerDoc
+ "\n\t" + (!more ? "--> " : "") + "tscorer.more=" + more
+ "\n\t" + (scoreDiff > maxDiff ? "--> " : "")
+ "scorerScore=" + scorerScore + " scoreDiff=" + scoreDiff
+ " maxDiff=" + maxDiff + "\n\t"
+ (scorerDiff > maxDiff ? "--> " : "") + "scorerScore2="
+ scorerScore2 + " scorerDiff=" + scorerDiff
+ "\n\thitCollector.doc=" + doc + " score=" + score
+ "\n\t Scorer=" + scorer + "\n\t Query=" + q + " "
+ q.getClass().getName() + "\n\t Searcher=" + s
+ "\n\t Order=" + sbord + "\n\t Op="
+ (op == skip_op ? " skip()" : " next()"));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
if (lastReader[0] != null) {
final IndexReader previousReader = lastReader[0];
Weight w = q.weight(new IndexSearcher(previousReader));
Scorer scorer = w.scorer(previousReader, true, false);
if (scorer != null) {
boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more);
}
}
- this.reader = reader;
+ this.reader = lastReader[0] = reader;
this.scorer = null;
lastDoc[0] = -1;
}
@Override
public boolean acceptsDocsOutOfOrder() {
return true;
}
});
if (lastReader[0] != null) {
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
final IndexReader previousReader = lastReader[0];
Weight w = q.weight(new IndexSearcher(previousReader));
Scorer scorer = w.scorer(previousReader, true, false);
if (scorer != null) {
boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more);
}
}
}
}
// check that first skip on just created scorers always goes to the right doc
private static void checkFirstSkipTo(final Query q, final IndexSearcher s) throws IOException {
//System.out.println("checkFirstSkipTo: "+q);
final float maxDiff = 1e-5f;
final int lastDoc[] = {-1};
final IndexReader lastReader[] = {null};
s.search(q,new Collector() {
private Scorer scorer;
private IndexReader reader;
@Override
public void setScorer(Scorer scorer) throws IOException {
this.scorer = scorer;
}
@Override
public void collect(int doc) throws IOException {
float score = scorer.score();
try {
for (int i=lastDoc[0]+1; i<=doc; i++) {
Weight w = q.weight(s);
Scorer scorer = w.scorer(reader, true, false);
Assert.assertTrue("query collected "+doc+" but skipTo("+i+") says no more docs!",scorer.advance(i) != DocIdSetIterator.NO_MORE_DOCS);
Assert.assertEquals("query collected "+doc+" but skipTo("+i+") got to "+scorer.docID(),doc,scorer.docID());
float skipToScore = scorer.score();
Assert.assertEquals("unstable skipTo("+i+") score!",skipToScore,scorer.score(),maxDiff);
Assert.assertEquals("query assigned doc "+doc+" a score of <"+score+"> but skipTo("+i+") has <"+skipToScore+">!",score,skipToScore,maxDiff);
}
lastDoc[0] = doc;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
if (lastReader[0] != null) {
final IndexReader previousReader = lastReader[0];
Weight w = q.weight(new IndexSearcher(previousReader));
Scorer scorer = w.scorer(previousReader, true, false);
if (scorer != null) {
boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more);
}
}
this.reader = lastReader[0] = reader;
lastDoc[0] = -1;
}
@Override
public boolean acceptsDocsOutOfOrder() {
return false;
}
});
if (lastReader[0] != null) {
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
final IndexReader previousReader = lastReader[0];
Weight w = q.weight(new IndexSearcher(previousReader));
Scorer scorer = w.scorer(previousReader, true, false);
if (scorer != null) {
boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more);
}
}
}
}
| true | true | public static void checkSkipTo(final Query q, final IndexSearcher s) throws IOException {
//System.out.println("Checking "+q);
if (q.weight(s).scoresDocsOutOfOrder()) return; // in this case order of skipTo() might differ from that of next().
final int skip_op = 0;
final int next_op = 1;
final int orders [][] = {
{next_op},
{skip_op},
{skip_op, next_op},
{next_op, skip_op},
{skip_op, skip_op, next_op, next_op},
{next_op, next_op, skip_op, skip_op},
{skip_op, skip_op, skip_op, next_op, next_op},
};
for (int k = 0; k < orders.length; k++) {
final int order[] = orders[k];
// System.out.print("Order:");for (int i = 0; i < order.length; i++)
// System.out.print(order[i]==skip_op ? " skip()":" next()");
// System.out.println();
final int opidx[] = { 0 };
final int lastDoc[] = {-1};
// FUTURE: ensure scorer.doc()==-1
final float maxDiff = 1e-5f;
final IndexReader lastReader[] = {null};
s.search(q, new Collector() {
private Scorer sc;
private IndexReader reader;
private Scorer scorer;
@Override
public void setScorer(Scorer scorer) throws IOException {
this.sc = scorer;
}
@Override
public void collect(int doc) throws IOException {
float score = sc.score();
lastDoc[0] = doc;
try {
if (scorer == null) {
Weight w = q.weight(s);
scorer = w.scorer(reader, true, false);
}
int op = order[(opidx[0]++) % order.length];
// System.out.println(op==skip_op ?
// "skip("+(sdoc[0]+1)+")":"next()");
boolean more = op == skip_op ? scorer.advance(scorer.docID() + 1) != DocIdSetIterator.NO_MORE_DOCS
: scorer.nextDoc() != DocIdSetIterator.NO_MORE_DOCS;
int scorerDoc = scorer.docID();
float scorerScore = scorer.score();
float scorerScore2 = scorer.score();
float scoreDiff = Math.abs(score - scorerScore);
float scorerDiff = Math.abs(scorerScore2 - scorerScore);
if (!more || doc != scorerDoc || scoreDiff > maxDiff
|| scorerDiff > maxDiff) {
StringBuilder sbord = new StringBuilder();
for (int i = 0; i < order.length; i++)
sbord.append(order[i] == skip_op ? " skip()" : " next()");
throw new RuntimeException("ERROR matching docs:" + "\n\t"
+ (doc != scorerDoc ? "--> " : "") + "doc=" + doc + ", scorerDoc=" + scorerDoc
+ "\n\t" + (!more ? "--> " : "") + "tscorer.more=" + more
+ "\n\t" + (scoreDiff > maxDiff ? "--> " : "")
+ "scorerScore=" + scorerScore + " scoreDiff=" + scoreDiff
+ " maxDiff=" + maxDiff + "\n\t"
+ (scorerDiff > maxDiff ? "--> " : "") + "scorerScore2="
+ scorerScore2 + " scorerDiff=" + scorerDiff
+ "\n\thitCollector.doc=" + doc + " score=" + score
+ "\n\t Scorer=" + scorer + "\n\t Query=" + q + " "
+ q.getClass().getName() + "\n\t Searcher=" + s
+ "\n\t Order=" + sbord + "\n\t Op="
+ (op == skip_op ? " skip()" : " next()"));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
if (lastReader[0] != null) {
final IndexReader previousReader = lastReader[0];
Weight w = q.weight(new IndexSearcher(previousReader));
Scorer scorer = w.scorer(previousReader, true, false);
if (scorer != null) {
boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more);
}
}
this.reader = reader;
this.scorer = null;
lastDoc[0] = -1;
}
@Override
public boolean acceptsDocsOutOfOrder() {
return true;
}
});
if (lastReader[0] != null) {
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
final IndexReader previousReader = lastReader[0];
Weight w = q.weight(new IndexSearcher(previousReader));
Scorer scorer = w.scorer(previousReader, true, false);
if (scorer != null) {
boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more);
}
}
}
}
| public static void checkSkipTo(final Query q, final IndexSearcher s) throws IOException {
//System.out.println("Checking "+q);
if (q.weight(s).scoresDocsOutOfOrder()) return; // in this case order of skipTo() might differ from that of next().
final int skip_op = 0;
final int next_op = 1;
final int orders [][] = {
{next_op},
{skip_op},
{skip_op, next_op},
{next_op, skip_op},
{skip_op, skip_op, next_op, next_op},
{next_op, next_op, skip_op, skip_op},
{skip_op, skip_op, skip_op, next_op, next_op},
};
for (int k = 0; k < orders.length; k++) {
final int order[] = orders[k];
// System.out.print("Order:");for (int i = 0; i < order.length; i++)
// System.out.print(order[i]==skip_op ? " skip()":" next()");
// System.out.println();
final int opidx[] = { 0 };
final int lastDoc[] = {-1};
// FUTURE: ensure scorer.doc()==-1
final float maxDiff = 1e-5f;
final IndexReader lastReader[] = {null};
s.search(q, new Collector() {
private Scorer sc;
private IndexReader reader;
private Scorer scorer;
@Override
public void setScorer(Scorer scorer) throws IOException {
this.sc = scorer;
}
@Override
public void collect(int doc) throws IOException {
float score = sc.score();
lastDoc[0] = doc;
try {
if (scorer == null) {
Weight w = q.weight(s);
scorer = w.scorer(reader, true, false);
}
int op = order[(opidx[0]++) % order.length];
// System.out.println(op==skip_op ?
// "skip("+(sdoc[0]+1)+")":"next()");
boolean more = op == skip_op ? scorer.advance(scorer.docID() + 1) != DocIdSetIterator.NO_MORE_DOCS
: scorer.nextDoc() != DocIdSetIterator.NO_MORE_DOCS;
int scorerDoc = scorer.docID();
float scorerScore = scorer.score();
float scorerScore2 = scorer.score();
float scoreDiff = Math.abs(score - scorerScore);
float scorerDiff = Math.abs(scorerScore2 - scorerScore);
if (!more || doc != scorerDoc || scoreDiff > maxDiff
|| scorerDiff > maxDiff) {
StringBuilder sbord = new StringBuilder();
for (int i = 0; i < order.length; i++)
sbord.append(order[i] == skip_op ? " skip()" : " next()");
throw new RuntimeException("ERROR matching docs:" + "\n\t"
+ (doc != scorerDoc ? "--> " : "") + "doc=" + doc + ", scorerDoc=" + scorerDoc
+ "\n\t" + (!more ? "--> " : "") + "tscorer.more=" + more
+ "\n\t" + (scoreDiff > maxDiff ? "--> " : "")
+ "scorerScore=" + scorerScore + " scoreDiff=" + scoreDiff
+ " maxDiff=" + maxDiff + "\n\t"
+ (scorerDiff > maxDiff ? "--> " : "") + "scorerScore2="
+ scorerScore2 + " scorerDiff=" + scorerDiff
+ "\n\thitCollector.doc=" + doc + " score=" + score
+ "\n\t Scorer=" + scorer + "\n\t Query=" + q + " "
+ q.getClass().getName() + "\n\t Searcher=" + s
+ "\n\t Order=" + sbord + "\n\t Op="
+ (op == skip_op ? " skip()" : " next()"));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void setNextReader(IndexReader reader, int docBase) throws IOException {
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
if (lastReader[0] != null) {
final IndexReader previousReader = lastReader[0];
Weight w = q.weight(new IndexSearcher(previousReader));
Scorer scorer = w.scorer(previousReader, true, false);
if (scorer != null) {
boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more);
}
}
this.reader = lastReader[0] = reader;
this.scorer = null;
lastDoc[0] = -1;
}
@Override
public boolean acceptsDocsOutOfOrder() {
return true;
}
});
if (lastReader[0] != null) {
// confirm that skipping beyond the last doc, on the
// previous reader, hits NO_MORE_DOCS
final IndexReader previousReader = lastReader[0];
Weight w = q.weight(new IndexSearcher(previousReader));
Scorer scorer = w.scorer(previousReader, true, false);
if (scorer != null) {
boolean more = scorer.advance(lastDoc[0] + 1) != DocIdSetIterator.NO_MORE_DOCS;
Assert.assertFalse("query's last doc was "+ lastDoc[0] +" but skipTo("+(lastDoc[0]+1)+") got to "+scorer.docID(),more);
}
}
}
}
|
diff --git a/sonar-application/src/test/java/org/sonar/application/StartServerTest.java b/sonar-application/src/test/java/org/sonar/application/StartServerTest.java
index 7cef36ab4d..f34676e1b0 100644
--- a/sonar-application/src/test/java/org/sonar/application/StartServerTest.java
+++ b/sonar-application/src/test/java/org/sonar/application/StartServerTest.java
@@ -1,150 +1,150 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube 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.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.application;
import com.github.kevinsawicki.http.HttpRequest;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
public class StartServerTest {
Env env = new Env(locateFakeConfFile());
StartServer starter = new StartServer(env);
@Before
@After
public void clean_generated_dirs() throws IOException {
FileUtils.deleteQuietly(env.file("temp"));
FileUtils.deleteQuietly(env.file("logs"));
}
@Test
public void start_server() throws Exception {
BackgroundThread background = new BackgroundThread(starter);
int port = 0;
try {
background.start();
boolean started = false;
- for (int i = 0; i < 100; i++) {
+ for (int i = 0; i < 400; i++) {
// Waiting for server to be started.
// A random and open port is used (see conf/sonar.properties)
- Thread.sleep(500L);
+ Thread.sleep(300L);
if (verifyUp() && verifyLogs()) {
port = starter.port();
started = true;
break;
}
}
assertThat(started).isTrue();
} finally {
starter.stop();
}
// Server is down
try {
assertThat(HttpRequest.get("http://localhost:" + port).ok()).isFalse();
} catch (HttpRequest.HttpRequestException e) {
// ok
}
}
private boolean verifyUp() {
if (starter.port() > 0) {
String url = "http://localhost:" + starter.port() + "/index.html";
HttpRequest request = HttpRequest.get(url);
if (request.ok() && "Hello World".equals(request.body(HttpRequest.CHARSET_UTF8))) {
return true;
}
}
return false;
}
private boolean verifyLogs() {
File logFile = env.file("logs/access.log");
return logFile.isFile() && logFile.exists() && logFile.length()>0;
}
@Test
public void fail_if_started_twice() throws Exception {
BackgroundThread background = new BackgroundThread(starter);
try {
background.start();
boolean started = false;
for (int i = 0; i < 100; i++) {
// Waiting for server to be started.
// A random and open port is used (see conf/sonar.properties)
Thread.sleep(500L);
if (starter.port() > 0) {
try {
starter.start();
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).isEqualTo("Tomcat is already started");
started = true;
break;
}
}
}
assertThat(started).isTrue();
} finally {
starter.stop();
}
}
@Test
public void ignore_stop_if_not_running() throws Exception {
starter.stop();
starter.stop();
}
private File locateFakeConfFile() {
File confFile = new File("src/test/fake-app/conf/sonar.properties");
if (!confFile.exists()) {
confFile = new File("sonar-application/src/test/fake-app/conf/sonar.properties");
}
return confFile;
}
static class BackgroundThread extends Thread {
private StartServer server;
BackgroundThread(StartServer server) {
this.server = server;
}
@Override
public void run() {
try {
server.start();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
}
| false | true | public void start_server() throws Exception {
BackgroundThread background = new BackgroundThread(starter);
int port = 0;
try {
background.start();
boolean started = false;
for (int i = 0; i < 100; i++) {
// Waiting for server to be started.
// A random and open port is used (see conf/sonar.properties)
Thread.sleep(500L);
if (verifyUp() && verifyLogs()) {
port = starter.port();
started = true;
break;
}
}
assertThat(started).isTrue();
} finally {
starter.stop();
}
// Server is down
try {
assertThat(HttpRequest.get("http://localhost:" + port).ok()).isFalse();
} catch (HttpRequest.HttpRequestException e) {
// ok
}
}
| public void start_server() throws Exception {
BackgroundThread background = new BackgroundThread(starter);
int port = 0;
try {
background.start();
boolean started = false;
for (int i = 0; i < 400; i++) {
// Waiting for server to be started.
// A random and open port is used (see conf/sonar.properties)
Thread.sleep(300L);
if (verifyUp() && verifyLogs()) {
port = starter.port();
started = true;
break;
}
}
assertThat(started).isTrue();
} finally {
starter.stop();
}
// Server is down
try {
assertThat(HttpRequest.get("http://localhost:" + port).ok()).isFalse();
} catch (HttpRequest.HttpRequestException e) {
// ok
}
}
|
diff --git a/carpentersblocks/util/flowerpot/FlowerPotHandler.java b/carpentersblocks/util/flowerpot/FlowerPotHandler.java
index daf3ef1..980eeac 100644
--- a/carpentersblocks/util/flowerpot/FlowerPotHandler.java
+++ b/carpentersblocks/util/flowerpot/FlowerPotHandler.java
@@ -1,201 +1,200 @@
package carpentersblocks.util.flowerpot;
import java.util.HashMap;
import java.util.Map;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Icon;
import net.minecraftforge.common.IShearable;
import carpentersblocks.tileentity.TEBase;
import carpentersblocks.tileentity.TECarpentersFlowerPot;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.GameRegistry.UniqueIdentifier;
public class FlowerPotHandler {
private final static Map<String, Profile> plantProfile = new HashMap<String, Profile>();
public enum Profile {
REDUCED_SCALE_YP,
REDUCED_SCALE_YN,
TRUE_SCALE,
THIN_YP,
THIN_YN,
CACTUS,
LEAVES
}
/**
* Initializes plant profiles.
*/
public static void initPlantProfiles()
{
/* Vanilla */
plantProfile.put("unknown:tile.tallgrass.grass", Profile.THIN_YP);
plantProfile.put("unknown:tile.tallgrass.fern", Profile.REDUCED_SCALE_YP);
plantProfile.put("unknown:tile.deadbush", Profile.REDUCED_SCALE_YP);
plantProfile.put("unknown:tile.cactus", Profile.CACTUS);
plantProfile.put("unknown:tile.mushroom", Profile.TRUE_SCALE);
plantProfile.put("unknown:tile.flower", Profile.TRUE_SCALE);
plantProfile.put("unknown:tile.rose", Profile.TRUE_SCALE);
plantProfile.put("unknown:tile.reeds", Profile.THIN_YP);
plantProfile.put("unknown:tile.carrots", Profile.THIN_YP);
plantProfile.put("unknown:tile.potatoes", Profile.THIN_YP);
plantProfile.put("unknown:tile.crops", Profile.THIN_YP);
/* Weee! Flowers */
plantProfile.put("unknown:orangeflower", Profile.TRUE_SCALE);
plantProfile.put("unknown:orangemoonflower", Profile.TRUE_SCALE);
plantProfile.put("unknown:purpleflower", Profile.THIN_YP);
plantProfile.put("unknown:yellowmoonflower", Profile.THIN_YP);
plantProfile.put("unknown:pinkmoonflower", Profile.THIN_YP);
plantProfile.put("unknown:darkgreymoonflower", Profile.THIN_YP);
plantProfile.put("unknown:lightgreymoonflower", Profile.THIN_YP);
plantProfile.put("unknown:purplemoonflower", Profile.THIN_YP);
plantProfile.put("unknown:brownmoonflower", Profile.THIN_YP);
plantProfile.put("unknown:redmoonflower", Profile.THIN_YP);
/* Harvestcraft */
plantProfile.put("unknown:tile.PamHarvestCraft:strawberrycrop_2", Profile.THIN_YP);
plantProfile.put("unknown:tile.PamHarvestCraft:cranberrycrop_2", Profile.THIN_YP);
plantProfile.put("unknown:tile.PamHarvestCraft:whitemushroomcrop_2", Profile.THIN_YP);
/* Biomes O' Plenty */
- plantProfile.put("tile.bop.plants.thorn", Profile.TRUE_SCALE);
- plantProfile.put("tile.bop.foliage.poisonivy", Profile.THIN_YP);
+ plantProfile.put("BiomesOPlenty:tile.bop.foliage.poisonivy", Profile.REDUCED_SCALE_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers.swampflower", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers.violet", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers.anemone", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers2.bluebells", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.coral.bluecoral", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.plants.thorn", Profile.REDUCED_SCALE_YP);
plantProfile.put("BiomesOPlenty:tile.bop.treeMoss", Profile.REDUCED_SCALE_YP);
plantProfile.put("BiomesOPlenty:tile.bop.mushrooms.portobello", Profile.TRUE_SCALE);
plantProfile.put("BiomesOPlenty:tile.bop.mushrooms.bluemilk", Profile.TRUE_SCALE);
plantProfile.put("BiomesOPlenty:tile.bop.mushrooms.flatmushroom", Profile.TRUE_SCALE);
plantProfile.put("BiomesOPlenty:tile.bop.stoneFormations.stalactite", Profile.THIN_YN);
/* Natura */
plantProfile.put("Natura:block.sapling.blood", Profile.REDUCED_SCALE_YN);
plantProfile.put("Natura:block.glowshroom.green", Profile.TRUE_SCALE);
plantProfile.put("Natura:block.glowshroom.blue", Profile.TRUE_SCALE);
plantProfile.put("Natura:block.glowshroom.purple", Profile.TRUE_SCALE);
/* ExtraBiomesXL */
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.cattail", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.2", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.5", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.6", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.7", Profile.THIN_YP);
}
/**
* Returns the plant profile to indicate which render method to use.
*/
public static Profile getPlantProfile(TEBase TE)
{
Block block = FlowerPotProperties.getPlantBlock(TE);
int metadata = FlowerPotProperties.getPlantMetadata((TECarpentersFlowerPot)TE);
String name = getFullUnlocalizedName(new ItemStack(block, 1, metadata));
if (plantProfile.containsKey(name)) {
return plantProfile.get(name);
} else if (block.blockMaterial.equals(Material.leaves) || block.blockMaterial.equals(Material.cactus)) {
return Profile.LEAVES;
} else if (block.blockMaterial == Material.vine) {
return Profile.THIN_YP;
} else {
return Profile.REDUCED_SCALE_YP;
}
}
public static Icon getPlantIcon(ItemStack itemStack)
{
int metadata = itemStack.getItemDamage();
// Override BoP's sunflower metadata so it uses the top of the flower.
if (getFullUnlocalizedName(itemStack).equals("BiomesOPlenty:tile.bop.flowers.sunflowerbottom")) {
metadata = 14;
}
return Block.blocksList[itemStack.itemID].getIcon(2, metadata);
}
/**
* Returns an unabridged, unlocalized name for item prefixed with
* a modId, if applicable.
*/
public static String getFullUnlocalizedName(ItemStack itemStack)
{
UniqueIdentifier uId = GameRegistry.findUniqueIdentifierFor(Item.itemsList[itemStack.itemID]);
StringBuilder string = new StringBuilder();
string.append(uId == null ? "unknown" : uId.modId);
string.append(":");
string.append(itemStack.getItem().getUnlocalizedNameInefficiently(itemStack));
return string.toString();
}
/**
* Returns equivalent block that represents item.
* If no equivalent exists, returns original ItemStack.
*/
public static ItemStack getEquivalentBlock(ItemStack itemStack)
{
if (itemStack != null)
{
Item item = itemStack.getItem();
if (item.equals(Item.reed)) {
return new ItemStack(Block.reed, 1, 0);
} else if (item.equals(Item.wheat)) {
return new ItemStack(Block.crops, 1, 7);
} else if (item.equals(Item.carrot)) {
return new ItemStack(Block.carrot, 1, 7);
} else if (item.equals(Item.potato)) {
return new ItemStack(Block.potato, 1, 7);
}
}
return itemStack;
}
/**
* Converts ItemStack block into appropriate Item where necessary.
*/
public static ItemStack getFilteredItem(ItemStack itemStack)
{
if (itemStack != null)
{
Block block = Block.blocksList[itemStack.itemID];
if (block instanceof IShearable) {
return itemStack;
} else {
int idDropped = Block.blocksList[itemStack.itemID].idDropped(itemStack.getItemDamage(), null, 0);
if (idDropped > 0) {
return new ItemStack(Item.itemsList[idDropped], 1, itemStack.getItemDamage());
}
}
}
return itemStack;
}
}
| true | true | public static void initPlantProfiles()
{
/* Vanilla */
plantProfile.put("unknown:tile.tallgrass.grass", Profile.THIN_YP);
plantProfile.put("unknown:tile.tallgrass.fern", Profile.REDUCED_SCALE_YP);
plantProfile.put("unknown:tile.deadbush", Profile.REDUCED_SCALE_YP);
plantProfile.put("unknown:tile.cactus", Profile.CACTUS);
plantProfile.put("unknown:tile.mushroom", Profile.TRUE_SCALE);
plantProfile.put("unknown:tile.flower", Profile.TRUE_SCALE);
plantProfile.put("unknown:tile.rose", Profile.TRUE_SCALE);
plantProfile.put("unknown:tile.reeds", Profile.THIN_YP);
plantProfile.put("unknown:tile.carrots", Profile.THIN_YP);
plantProfile.put("unknown:tile.potatoes", Profile.THIN_YP);
plantProfile.put("unknown:tile.crops", Profile.THIN_YP);
/* Weee! Flowers */
plantProfile.put("unknown:orangeflower", Profile.TRUE_SCALE);
plantProfile.put("unknown:orangemoonflower", Profile.TRUE_SCALE);
plantProfile.put("unknown:purpleflower", Profile.THIN_YP);
plantProfile.put("unknown:yellowmoonflower", Profile.THIN_YP);
plantProfile.put("unknown:pinkmoonflower", Profile.THIN_YP);
plantProfile.put("unknown:darkgreymoonflower", Profile.THIN_YP);
plantProfile.put("unknown:lightgreymoonflower", Profile.THIN_YP);
plantProfile.put("unknown:purplemoonflower", Profile.THIN_YP);
plantProfile.put("unknown:brownmoonflower", Profile.THIN_YP);
plantProfile.put("unknown:redmoonflower", Profile.THIN_YP);
/* Harvestcraft */
plantProfile.put("unknown:tile.PamHarvestCraft:strawberrycrop_2", Profile.THIN_YP);
plantProfile.put("unknown:tile.PamHarvestCraft:cranberrycrop_2", Profile.THIN_YP);
plantProfile.put("unknown:tile.PamHarvestCraft:whitemushroomcrop_2", Profile.THIN_YP);
/* Biomes O' Plenty */
plantProfile.put("tile.bop.plants.thorn", Profile.TRUE_SCALE);
plantProfile.put("tile.bop.foliage.poisonivy", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers.swampflower", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers.violet", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers.anemone", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers2.bluebells", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.coral.bluecoral", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.plants.thorn", Profile.REDUCED_SCALE_YP);
plantProfile.put("BiomesOPlenty:tile.bop.treeMoss", Profile.REDUCED_SCALE_YP);
plantProfile.put("BiomesOPlenty:tile.bop.mushrooms.portobello", Profile.TRUE_SCALE);
plantProfile.put("BiomesOPlenty:tile.bop.mushrooms.bluemilk", Profile.TRUE_SCALE);
plantProfile.put("BiomesOPlenty:tile.bop.mushrooms.flatmushroom", Profile.TRUE_SCALE);
plantProfile.put("BiomesOPlenty:tile.bop.stoneFormations.stalactite", Profile.THIN_YN);
/* Natura */
plantProfile.put("Natura:block.sapling.blood", Profile.REDUCED_SCALE_YN);
plantProfile.put("Natura:block.glowshroom.green", Profile.TRUE_SCALE);
plantProfile.put("Natura:block.glowshroom.blue", Profile.TRUE_SCALE);
plantProfile.put("Natura:block.glowshroom.purple", Profile.TRUE_SCALE);
/* ExtraBiomesXL */
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.cattail", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.2", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.5", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.6", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.7", Profile.THIN_YP);
}
| public static void initPlantProfiles()
{
/* Vanilla */
plantProfile.put("unknown:tile.tallgrass.grass", Profile.THIN_YP);
plantProfile.put("unknown:tile.tallgrass.fern", Profile.REDUCED_SCALE_YP);
plantProfile.put("unknown:tile.deadbush", Profile.REDUCED_SCALE_YP);
plantProfile.put("unknown:tile.cactus", Profile.CACTUS);
plantProfile.put("unknown:tile.mushroom", Profile.TRUE_SCALE);
plantProfile.put("unknown:tile.flower", Profile.TRUE_SCALE);
plantProfile.put("unknown:tile.rose", Profile.TRUE_SCALE);
plantProfile.put("unknown:tile.reeds", Profile.THIN_YP);
plantProfile.put("unknown:tile.carrots", Profile.THIN_YP);
plantProfile.put("unknown:tile.potatoes", Profile.THIN_YP);
plantProfile.put("unknown:tile.crops", Profile.THIN_YP);
/* Weee! Flowers */
plantProfile.put("unknown:orangeflower", Profile.TRUE_SCALE);
plantProfile.put("unknown:orangemoonflower", Profile.TRUE_SCALE);
plantProfile.put("unknown:purpleflower", Profile.THIN_YP);
plantProfile.put("unknown:yellowmoonflower", Profile.THIN_YP);
plantProfile.put("unknown:pinkmoonflower", Profile.THIN_YP);
plantProfile.put("unknown:darkgreymoonflower", Profile.THIN_YP);
plantProfile.put("unknown:lightgreymoonflower", Profile.THIN_YP);
plantProfile.put("unknown:purplemoonflower", Profile.THIN_YP);
plantProfile.put("unknown:brownmoonflower", Profile.THIN_YP);
plantProfile.put("unknown:redmoonflower", Profile.THIN_YP);
/* Harvestcraft */
plantProfile.put("unknown:tile.PamHarvestCraft:strawberrycrop_2", Profile.THIN_YP);
plantProfile.put("unknown:tile.PamHarvestCraft:cranberrycrop_2", Profile.THIN_YP);
plantProfile.put("unknown:tile.PamHarvestCraft:whitemushroomcrop_2", Profile.THIN_YP);
/* Biomes O' Plenty */
plantProfile.put("BiomesOPlenty:tile.bop.foliage.poisonivy", Profile.REDUCED_SCALE_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers.swampflower", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers.violet", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers.anemone", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.flowers2.bluebells", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.coral.bluecoral", Profile.THIN_YP);
plantProfile.put("BiomesOPlenty:tile.bop.plants.thorn", Profile.REDUCED_SCALE_YP);
plantProfile.put("BiomesOPlenty:tile.bop.treeMoss", Profile.REDUCED_SCALE_YP);
plantProfile.put("BiomesOPlenty:tile.bop.mushrooms.portobello", Profile.TRUE_SCALE);
plantProfile.put("BiomesOPlenty:tile.bop.mushrooms.bluemilk", Profile.TRUE_SCALE);
plantProfile.put("BiomesOPlenty:tile.bop.mushrooms.flatmushroom", Profile.TRUE_SCALE);
plantProfile.put("BiomesOPlenty:tile.bop.stoneFormations.stalactite", Profile.THIN_YN);
/* Natura */
plantProfile.put("Natura:block.sapling.blood", Profile.REDUCED_SCALE_YN);
plantProfile.put("Natura:block.glowshroom.green", Profile.TRUE_SCALE);
plantProfile.put("Natura:block.glowshroom.blue", Profile.TRUE_SCALE);
plantProfile.put("Natura:block.glowshroom.purple", Profile.TRUE_SCALE);
/* ExtraBiomesXL */
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.cattail", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.2", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.5", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.6", Profile.THIN_YP);
plantProfile.put("ExtrabiomesXL:tile.extrabiomes.flower.7", Profile.THIN_YP);
}
|
diff --git a/src/com/sonyericsson/chkbugreport/BugReport.java b/src/com/sonyericsson/chkbugreport/BugReport.java
index 6cef8cb..c8a44b7 100644
--- a/src/com/sonyericsson/chkbugreport/BugReport.java
+++ b/src/com/sonyericsson/chkbugreport/BugReport.java
@@ -1,621 +1,621 @@
/*
* Copyright (C) 2011 Sony Ericsson 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;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Vector;
import com.sonyericsson.chkbugreport.plugins.BatteryInfoPlugin;
import com.sonyericsson.chkbugreport.plugins.CpuFreqPlugin;
import com.sonyericsson.chkbugreport.plugins.EventLogPlugin;
import com.sonyericsson.chkbugreport.plugins.KernelLogPlugin;
import com.sonyericsson.chkbugreport.plugins.MainLogPlugin;
import com.sonyericsson.chkbugreport.plugins.MemPlugin;
import com.sonyericsson.chkbugreport.plugins.PackageInfoPlugin;
import com.sonyericsson.chkbugreport.plugins.ScreenShotPlugin;
import com.sonyericsson.chkbugreport.plugins.SummaryPlugin;
import com.sonyericsson.chkbugreport.plugins.SurfaceFlingerPlugin;
import com.sonyericsson.chkbugreport.plugins.SysPropsPlugin;
import com.sonyericsson.chkbugreport.plugins.SystemLogPlugin;
import com.sonyericsson.chkbugreport.plugins.WindowManagerPlugin;
import com.sonyericsson.chkbugreport.plugins.ftrace.FTracePlugin;
import com.sonyericsson.chkbugreport.plugins.stacktrace.StackTracePlugin;
public class BugReport extends Report {
public static final boolean USE_FRAMES = true;
public static final int SDK_DONUT = 4;
public static final int SDK_ECLAIR = 5;
public static final int SDK_ECLAIR_0_1 = 6;
public static final int SDK_ECLAIR_MR1 = 7;
public static final int SDK_FROYO = 8;
public static final int SDK_GB = 9;
public static final int SDK_GB_MR1 = 10;
public static final int SDK_HC = 11;
public static final int SDK_HC_MR1 = 12;
public static final int SDK_HC_MR2 = 13;
public static final int SDK_ICS = 14;
private static final String FN_TOC_HTML = "data/toc.html";
private static final String SECTION_DIVIDER = "-------------------------------------------------------------------------------";
private Vector<ProcessRecord> mProcessRecords = new Vector<ProcessRecord>();
private HashMap<Integer, ProcessRecord> mProcessRecordMap = new HashMap<Integer, ProcessRecord>();
private Chapter mChProcesses;
private HashMap<Integer, PSRecord> mPSRecords = new HashMap<Integer, PSRecord>();
private int mVerMaj;
private int mVerMin;
private int mVerRel;
private float mVer;
private int mVerSdk;
private Calendar mTimestamp;
{
addPlugin(new MemPlugin());
addPlugin(new StackTracePlugin());
addPlugin(new SystemLogPlugin());
addPlugin(new MainLogPlugin());
addPlugin(new EventLogPlugin());
addPlugin(new KernelLogPlugin());
addPlugin(new FTracePlugin());
addPlugin(new BatteryInfoPlugin());
addPlugin(new CpuFreqPlugin());
addPlugin(new SurfaceFlingerPlugin());
addPlugin(new WindowManagerPlugin());
addPlugin(new SysPropsPlugin());
addPlugin(new PackageInfoPlugin());
addPlugin(new SummaryPlugin());
addPlugin(new ScreenShotPlugin());
}
public BugReport(String fileName) {
super(fileName);
String chapterName = "Processes";
mChProcesses = new Chapter(this, chapterName);
}
public Calendar getTimestamp() {
return mTimestamp;
}
@Override
public void load(InputStream is) throws IOException {
load(is, false, null);
}
protected void load(InputStream is, boolean partial, String secName) throws IOException {
printOut(1, "Loading input...");
LineReader br = new LineReader(is);
String buff;
Section curSection = null;
mTimestamp = null;
int lineNr = 0;
int skipCount = 5;
boolean formatOk = partial;
while (null != (buff = br.readLine())) {
if (!formatOk) {
// Sill need file format validation
// Check if this is a dropbox file
if (0 == lineNr && buff.startsWith("Process: ")) {
loadFromDopBox(br, buff);
return;
}
if (0 == lineNr) {
// Not detected yet
if (buff.startsWith("==============")) {
// Ok, pass through and start processing
} else {
if (0 == --skipCount) {
// give up (simply pass through and let if fail later)
} else {
// Give another chance
continue;
}
}
}
// Verify file format (just a simple sanity check)
lineNr++;
if (1 == lineNr && !buff.startsWith("==============")) break;
if (2 == lineNr && !buff.startsWith("== dumpstate")) break;
if (3 == lineNr && !buff.startsWith("==============")) break;
if (4 == lineNr) {
formatOk = true;
}
// Extract timestamp of crash
Calendar ts = Util.parseTimestamp(this, buff);
if (ts != null) {
mTimestamp = ts;
}
}
// Parse sections and sub-sections
if (buff.startsWith("------ ")) {
// build up file name
int e = buff.indexOf(" ------");
if (e >= 0) {
String sectionName = buff.substring(7, e);
// Workaround for SMAP spamming
boolean newSection = true;
if (curSection != null && curSection.getName().equals("SMAPS OF ALL PROCESSES")) {
if (sectionName.startsWith("SHOW MAP ")) {
newSection = false;
}
}
if (newSection) {
Section section = new Section(this, sectionName);
addSection(section);
curSection = section;
continue;
}
}
}
// Workaround for buggy wallpaper service dump
int idx = buff.indexOf(SECTION_DIVIDER);
if (idx > 0) {
if (curSection != null) {
curSection.addLine(buff.substring(0, idx));
}
buff = buff.substring(idx);
}
- if (buff.startsWith(SECTION_DIVIDER)) {
+ if (buff.equals(SECTION_DIVIDER)) {
// Another kind of marker
// Need to read the next line
String sectionName = br.readLine();
if (sectionName != null) {
if ("DUMP OF SERVICE activity:".equals(sectionName)) {
// skip over this name, and use the next line as title, the provider thingy
sectionName = br.readLine();
}
}
if (sectionName != null) {
Section section = new Section(this, sectionName);
addSection(section);
curSection = section;
}
continue;
}
// Add the current line to the current section
if (curSection == null && partial) {
// We better not spam the header section, so let's create a fake section
curSection = new Section(this, secName);
addSection(curSection);
}
if (curSection != null) {
curSection.addLine(buff);
} else {
addHeaderLine(buff);
}
}
br.close();
if (!formatOk) {
throw new IOException("Does not look like a bugreport file!");
}
}
/**
* Load a partial bugreport, for example the output of dumpsys
* @param fileName The file name of the partial bugreport
* @param sectionName The name of the section where the header will be collected
*/
public boolean loadPartial(String fileName, String sectionName) {
try {
FileInputStream fis = new FileInputStream(fileName);
load(fis, true, sectionName);
fis.close();
addHeaderLine("Partial bugreport: " + fileName);
return true;
} catch (IOException e) {
System.err.println("Error reading file '" + fileName + "' (it will be ignored): " + e);
return false;
}
}
private void loadFromDopBox(LineReader br, String buff) {
printOut(2, "Detect dropbox file...");
int state = 0; // header
Section secLog = new Section(this, Section.SYSTEM_LOG);
Section secStack = new Section(this, Section.VM_TRACES_AT_LAST_ANR);
do {
switch (state) {
case 0: /* header state */
if (buff.length() == 0) {
state = 1; // log
} else {
addHeaderLine(buff);
}
break;
case 1: /* log state */
if (buff.length() == 0) {
state = 2; // stack trace
} else {
secLog.addLine(buff);
}
break;
case 2: /* stack trace */
secStack.addLine(buff);
break;
}
} while (null != (buff = br.readLine()));
addSection(secLog);
addSection(secStack);
br.close();
}
@Override
public void generate() throws IOException {
// This will create the empty index.html and open the file
super.generate();
// This will do build some extra chapters and save some non-html files
collectData();
if (useFrames()) {
// In the still opened index html we just create the frameset
printOut(1, "Writing frameset...");
writeHeaderLite();
writeFrames();
writeFooterLite();
closeFile();
// Write the table of contents
printOut(1, "Writing TOC...");
openFile(getOutDir() + FN_TOC_HTML);
writeHeader();
writeTOC();
writeFooter();
closeFile();
// Write all the chapters
printOut(1, "Writing Chapters...");
writeChapters();
} else {
// In the still opened index html we save everything
writeHeader();
// Write the table of contents
printOut(1, "Writing TOC...");
writeTOC();
// Write all the chapters
printOut(1, "Writing Chapters...");
writeChapters();
// Close the file
writeFooter();
closeFile();
}
printOut(1, "DONE!");
}
private void collectData() throws IOException {
// Save each section as raw file
printOut(1, "Saving raw sections");
saveSections();
// Collect the process names from the PS output
analyzePS();
// Run all the plugins
runPlugins();
// Collect detected bugs
printOut(1, "Collecting errors...");
collectBugs();
// Collect process records
printOut(1, "Collecting process records...");
collectProcessRecords();
// Create the header chapter
printOut(1, "Writing header...");
writeHeaderChapter();
// Copy over some builtin resources
printOut(1, "Copying extra resources...");
copyRes(Util.COMMON_RES);
}
/**
* Return the gathered information related to a process
* @param pid The pid of the process
* @param createIfNeeded if true then the process record will be created if it does not exists yet
* @param export marks the process record to be exported or not. If at least one call sets this to true
* for a given process, then the process will be exported.
* This is used so application can create process records early on, but mark them as not important,
* so if no other important info is added, the process record won't be saved.
* @return The process record or null if not found (and not created)
*/
public ProcessRecord getProcessRecord(int pid, boolean createIfNeeded, boolean export) {
ProcessRecord ret = mProcessRecordMap.get(pid);
if (ret == null && createIfNeeded) {
ret = new ProcessRecord(this, "", pid);
mProcessRecordMap.put(pid, ret);
mProcessRecords.add(ret);
}
if (ret != null && export) {
ret.setExport();
}
return ret;
}
public String createLinkToProcessRecord(int pid) {
String anchor = Util.getProcessRecordAnchor(pid);
String link = createLinkTo(mChProcesses, anchor);
return link;
}
protected void collectProcessRecords() {
// Sort
Collections.sort(mProcessRecords, new Comparator<ProcessRecord>(){
@Override
public int compare(ProcessRecord o1, ProcessRecord o2) {
return o1.getPid() - o2.getPid();
}
});
// Create chapter
for (ProcessRecord pr : mProcessRecords) {
if (pr.shouldExport()) {
mChProcesses.addChapter(pr);
}
}
addChapter(mChProcesses);
// Now sort by name
Collections.sort(mProcessRecords, new Comparator<ProcessRecord>(){
@Override
public int compare(ProcessRecord o1, ProcessRecord o2) {
return o1.getName().compareTo(o2.getName());
}
});
// And create the alphabetical list
mChProcesses.addLine("<ul>");
for (ProcessRecord pr : mProcessRecords) {
if (pr.shouldExport()) {
PSRecord ps = getPSRecord(pr.getPid());
boolean strike = (ps == null && mPSRecords.size() > 0);
StringBuffer line = new StringBuffer();
line.append("<li><a href=\"#");
line.append(Util.getProcessRecordAnchor(pr.getPid()));
line.append("\">");
if (strike) {
line.append("<strike>");
}
line.append(pr.getName());
if (strike) {
line.append("</strike>");
}
line.append("</a></li>");
mChProcesses.addLine(line.toString());
}
}
mChProcesses.addLine("</ul>");
}
private void writeFrames() {
String first = getChapters().getChild(0).getAnchor();
writeLine("<frameset cols=\"25%,75%\">");
writeLine(" <frame name=\"toc\" src=\"" + FN_TOC_HTML + "\"/>");
writeLine(" <frame name=\"content\" src=\"data/" + first + ".html\"/>");
writeLine("</frameset>");
}
private void analyzePS() {
// Locate the PS section
Section ps = findSection(Section.PROCESSES_AND_THREADS);
if (ps == null) {
printErr(3, "Cannot find section: " + Section.PROCESSES_AND_THREADS + " (ignoring it)");
}
if (ps == null) {
ps = findSection(Section.PROCESSES);
if (ps == null) {
printErr(3, "Cannot find section: " + Section.PROCESSES + " (ignoring it)");
}
}
if (ps != null) {
readPS(ps);
}
}
private void readPS(Section ps) {
// Process the PS section
// Read the header and use it to locate the PID, PPID and NAME fields
int tries = 10;
String buff = null;
int idxPid = -1, idxPPid = -1, idxName = -1, idxNice = -1, idxPCY = -1, lineIdx = 0;
while (tries > 0) {
buff = ps.getLine(lineIdx++);
idxPid = Util.indexOf(buff, " PID ", 2);
idxPPid = Util.indexOf(buff, " PPID ", 2);
idxNice = Util.indexOf(buff, " NICE ", 2);
idxPCY = Util.indexOf(buff, " PCY ", 1);
idxName = Util.indexOf(buff, " NAME", 0);
if (idxPid > 0 && idxName > 0) break;
tries--;
}
if (idxPid < 0 || idxName < 0) return;
// Now read and process every line
int pidZygote = -1;
int cnt = ps.getLineCount();
for (int i = lineIdx; i < cnt; i++) {
buff = ps.getLine(i);
if (buff.startsWith("[")) break;
// Extract pid
int pid = -1;
if (idxPid >= 0) {
String sPid = buff.substring(idxPid);
try {
pid = parseInt(sPid);
} catch (NumberFormatException nfe) {
printErr(4, "Error parsing pid from: " + sPid);
break;
}
}
// Extract ppid
int ppid = -1;
if (idxPPid >= 0) {
String sPid = buff.substring(idxPPid);
try {
ppid = parseInt(sPid);
} catch (NumberFormatException nfe) {
printErr(4, "Error parsing ppid from: " + sPid);
break;
}
}
// Extract nice
int nice = PSRecord.NICE_UNKNOWN;
if (idxNice >= 0) {
String sNice = buff.substring(idxNice);
try {
nice = parseInt(sNice);
} catch (NumberFormatException nfe) {
printErr(4, "Error parsing nice from: " + sNice);
break;
}
}
// Extract scheduler policy
int pcy = PSRecord.PCY_UNKNOWN;
if (idxPCY >= 0) {
String sPcy = buff.substring(idxPCY, idxPCY + 2);
if ("fg".equals(sPcy)) {
pcy = PSRecord.PCY_NORMAL;
} else if ("bg".equals(sPcy)) {
pcy = PSRecord.PCY_BATCH;
} else if ("un".equals(sPcy)) {
pcy = PSRecord.PCY_FIFO;
} else {
pcy = PSRecord.PCY_OTHER;
}
}
// Exctract name
String name = "";
if (idxName >= 0) {
name = buff.substring(idxName);
}
// Fix the name
mPSRecords.put(pid, new PSRecord(pid, ppid, nice, pcy, name));
// Check if we should create a ProcessRecord for this
if (pidZygote == -1 && name.equals("zygote")) {
pidZygote = pid;
}
ProcessRecord pr = getProcessRecord(pid, true, false);
pr.suggestName(name, 10);
}
}
public PSRecord getPSRecord(int pid) {
return mPSRecords.get(pid);
}
public Vector<PSRecord> findChildPSRecords(int pid) {
Vector<PSRecord> ret = new Vector<PSRecord>();
for (PSRecord psr : mPSRecords.values()) {
if (psr.getPid() == pid || psr.getParentPid() == pid) {
ret.add(psr);
}
}
return ret;
}
private int parseInt(String sPid) {
int e = 0, l = sPid.length();
while (e < l) {
char c = sPid.charAt(e);
if ((c < '0' || c > '9') && c != '-') break;
e++;
}
sPid = sPid.substring(0, e);
return Integer.parseInt(sPid);
}
public void setAndroidVersion(String string) {
String f[] = string.split(".");
if (f.length >= 1) {
mVerMaj = Integer.parseInt(f[0]);
mVer = mVerMaj;
}
if (f.length >= 2) {
mVerMin = Integer.parseInt(f[1]);
mVer = Float.parseFloat(f[0] + "." + f[1]);
}
if (f.length >= 3) {
mVerRel = Integer.parseInt(f[2]);
}
}
public float getAndroidVersion() {
return mVer;
}
public int getAndroidVersionMaj() {
return mVerMaj;
}
public int getAndroidVersionMin() {
return mVerMin;
}
public int getAndroidVersionRel() {
return mVerRel;
}
public void setAndroidSdkVersion(String string) {
mVerSdk = Integer.parseInt(string);
}
public int getAndroidVersionSdk() {
return mVerSdk;
}
}
| true | true | protected void load(InputStream is, boolean partial, String secName) throws IOException {
printOut(1, "Loading input...");
LineReader br = new LineReader(is);
String buff;
Section curSection = null;
mTimestamp = null;
int lineNr = 0;
int skipCount = 5;
boolean formatOk = partial;
while (null != (buff = br.readLine())) {
if (!formatOk) {
// Sill need file format validation
// Check if this is a dropbox file
if (0 == lineNr && buff.startsWith("Process: ")) {
loadFromDopBox(br, buff);
return;
}
if (0 == lineNr) {
// Not detected yet
if (buff.startsWith("==============")) {
// Ok, pass through and start processing
} else {
if (0 == --skipCount) {
// give up (simply pass through and let if fail later)
} else {
// Give another chance
continue;
}
}
}
// Verify file format (just a simple sanity check)
lineNr++;
if (1 == lineNr && !buff.startsWith("==============")) break;
if (2 == lineNr && !buff.startsWith("== dumpstate")) break;
if (3 == lineNr && !buff.startsWith("==============")) break;
if (4 == lineNr) {
formatOk = true;
}
// Extract timestamp of crash
Calendar ts = Util.parseTimestamp(this, buff);
if (ts != null) {
mTimestamp = ts;
}
}
// Parse sections and sub-sections
if (buff.startsWith("------ ")) {
// build up file name
int e = buff.indexOf(" ------");
if (e >= 0) {
String sectionName = buff.substring(7, e);
// Workaround for SMAP spamming
boolean newSection = true;
if (curSection != null && curSection.getName().equals("SMAPS OF ALL PROCESSES")) {
if (sectionName.startsWith("SHOW MAP ")) {
newSection = false;
}
}
if (newSection) {
Section section = new Section(this, sectionName);
addSection(section);
curSection = section;
continue;
}
}
}
// Workaround for buggy wallpaper service dump
int idx = buff.indexOf(SECTION_DIVIDER);
if (idx > 0) {
if (curSection != null) {
curSection.addLine(buff.substring(0, idx));
}
buff = buff.substring(idx);
}
if (buff.startsWith(SECTION_DIVIDER)) {
// Another kind of marker
// Need to read the next line
String sectionName = br.readLine();
if (sectionName != null) {
if ("DUMP OF SERVICE activity:".equals(sectionName)) {
// skip over this name, and use the next line as title, the provider thingy
sectionName = br.readLine();
}
}
if (sectionName != null) {
Section section = new Section(this, sectionName);
addSection(section);
curSection = section;
}
continue;
}
// Add the current line to the current section
if (curSection == null && partial) {
// We better not spam the header section, so let's create a fake section
curSection = new Section(this, secName);
addSection(curSection);
}
if (curSection != null) {
curSection.addLine(buff);
} else {
addHeaderLine(buff);
}
}
br.close();
if (!formatOk) {
throw new IOException("Does not look like a bugreport file!");
}
}
| protected void load(InputStream is, boolean partial, String secName) throws IOException {
printOut(1, "Loading input...");
LineReader br = new LineReader(is);
String buff;
Section curSection = null;
mTimestamp = null;
int lineNr = 0;
int skipCount = 5;
boolean formatOk = partial;
while (null != (buff = br.readLine())) {
if (!formatOk) {
// Sill need file format validation
// Check if this is a dropbox file
if (0 == lineNr && buff.startsWith("Process: ")) {
loadFromDopBox(br, buff);
return;
}
if (0 == lineNr) {
// Not detected yet
if (buff.startsWith("==============")) {
// Ok, pass through and start processing
} else {
if (0 == --skipCount) {
// give up (simply pass through and let if fail later)
} else {
// Give another chance
continue;
}
}
}
// Verify file format (just a simple sanity check)
lineNr++;
if (1 == lineNr && !buff.startsWith("==============")) break;
if (2 == lineNr && !buff.startsWith("== dumpstate")) break;
if (3 == lineNr && !buff.startsWith("==============")) break;
if (4 == lineNr) {
formatOk = true;
}
// Extract timestamp of crash
Calendar ts = Util.parseTimestamp(this, buff);
if (ts != null) {
mTimestamp = ts;
}
}
// Parse sections and sub-sections
if (buff.startsWith("------ ")) {
// build up file name
int e = buff.indexOf(" ------");
if (e >= 0) {
String sectionName = buff.substring(7, e);
// Workaround for SMAP spamming
boolean newSection = true;
if (curSection != null && curSection.getName().equals("SMAPS OF ALL PROCESSES")) {
if (sectionName.startsWith("SHOW MAP ")) {
newSection = false;
}
}
if (newSection) {
Section section = new Section(this, sectionName);
addSection(section);
curSection = section;
continue;
}
}
}
// Workaround for buggy wallpaper service dump
int idx = buff.indexOf(SECTION_DIVIDER);
if (idx > 0) {
if (curSection != null) {
curSection.addLine(buff.substring(0, idx));
}
buff = buff.substring(idx);
}
if (buff.equals(SECTION_DIVIDER)) {
// Another kind of marker
// Need to read the next line
String sectionName = br.readLine();
if (sectionName != null) {
if ("DUMP OF SERVICE activity:".equals(sectionName)) {
// skip over this name, and use the next line as title, the provider thingy
sectionName = br.readLine();
}
}
if (sectionName != null) {
Section section = new Section(this, sectionName);
addSection(section);
curSection = section;
}
continue;
}
// Add the current line to the current section
if (curSection == null && partial) {
// We better not spam the header section, so let's create a fake section
curSection = new Section(this, secName);
addSection(curSection);
}
if (curSection != null) {
curSection.addLine(buff);
} else {
addHeaderLine(buff);
}
}
br.close();
if (!formatOk) {
throw new IOException("Does not look like a bugreport file!");
}
}
|
diff --git a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/OLAPExpressionCompiler.java b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/OLAPExpressionCompiler.java
index 1cc8f478a..6288176ec 100644
--- a/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/OLAPExpressionCompiler.java
+++ b/plugins/org.eclipse.birt.data/src/org/eclipse/birt/data/engine/olap/script/OLAPExpressionCompiler.java
@@ -1,84 +1,84 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.data.engine.olap.script;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.script.ScriptContext;
import org.eclipse.birt.data.engine.api.IBaseExpression;
import org.eclipse.birt.data.engine.api.IConditionalExpression;
import org.eclipse.birt.data.engine.api.IExpressionCollection;
import org.eclipse.birt.data.engine.api.IScriptExpression;
import org.eclipse.birt.data.engine.core.DataException;
/**
*
*/
public class OLAPExpressionCompiler
{
/**
*
* @param cx
* @throws DataException
*/
public static void compile( ScriptContext cx, IBaseExpression expr ) throws DataException
{
if ( expr instanceof IConditionalExpression )
{
prepareScriptExpression( cx,
( (IConditionalExpression) expr ).getExpression( ) );
prepareScriptExpression( cx,
( (IConditionalExpression) expr ).getOperand1( ) );
prepareScriptExpression( cx,
( (IConditionalExpression) expr ).getOperand2( ) );
}
else if ( expr instanceof IScriptExpression )
{
prepareScriptExpression( cx, (IScriptExpression) expr );
}
}
/**
*
* @param cx
* @param expr1
* @throws DataException
*/
private static void prepareScriptExpression( ScriptContext cx,
IBaseExpression expr1 ) throws DataException
{
try {
if ( expr1 == null )
return;
if ( expr1 instanceof IScriptExpression )
{
String exprText = ( (IScriptExpression) expr1 ).getText( );
- if( expr1.getHandle( ) != null )
+ if( expr1.getHandle( ) == null )
expr1.setHandle( new OLAPExpressionHandler( cx.compile( expr1.getScriptId(), null, 0, exprText ) ) );
}
else if ( expr1 instanceof IExpressionCollection )
{
Object[] exprs = ( (IExpressionCollection) expr1 ).getExpressions( ).toArray( );
for ( int i = 0; i <exprs.length; i++ )
{
prepareScriptExpression( cx,
(IBaseExpression)exprs[i] );
}
}
}
catch (BirtException e)
{
throw DataException.wrap( e );
}
}
}
| true | true | private static void prepareScriptExpression( ScriptContext cx,
IBaseExpression expr1 ) throws DataException
{
try {
if ( expr1 == null )
return;
if ( expr1 instanceof IScriptExpression )
{
String exprText = ( (IScriptExpression) expr1 ).getText( );
if( expr1.getHandle( ) != null )
expr1.setHandle( new OLAPExpressionHandler( cx.compile( expr1.getScriptId(), null, 0, exprText ) ) );
}
else if ( expr1 instanceof IExpressionCollection )
{
Object[] exprs = ( (IExpressionCollection) expr1 ).getExpressions( ).toArray( );
for ( int i = 0; i <exprs.length; i++ )
{
prepareScriptExpression( cx,
(IBaseExpression)exprs[i] );
}
}
}
catch (BirtException e)
{
throw DataException.wrap( e );
}
}
| private static void prepareScriptExpression( ScriptContext cx,
IBaseExpression expr1 ) throws DataException
{
try {
if ( expr1 == null )
return;
if ( expr1 instanceof IScriptExpression )
{
String exprText = ( (IScriptExpression) expr1 ).getText( );
if( expr1.getHandle( ) == null )
expr1.setHandle( new OLAPExpressionHandler( cx.compile( expr1.getScriptId(), null, 0, exprText ) ) );
}
else if ( expr1 instanceof IExpressionCollection )
{
Object[] exprs = ( (IExpressionCollection) expr1 ).getExpressions( ).toArray( );
for ( int i = 0; i <exprs.length; i++ )
{
prepareScriptExpression( cx,
(IBaseExpression)exprs[i] );
}
}
}
catch (BirtException e)
{
throw DataException.wrap( e );
}
}
|
diff --git a/Utilities/java/convertFastqToFasta.java b/Utilities/java/convertFastqToFasta.java
index 4485385..594e83e 100644
--- a/Utilities/java/convertFastqToFasta.java
+++ b/Utilities/java/convertFastqToFasta.java
@@ -1,58 +1,55 @@
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.regex.Pattern;
import java.io.PrintStream;
import java.io.File;
public class convertFastqToFasta {
private static final NumberFormat nf = new DecimalFormat("############.#");
private static char OFFSET_CHAR = '!';
public static final Pattern splitBySpaces = Pattern.compile("\\s+");
public static final String[] FILE_SUFFIX = {"seq", "fastq", "fq"};
public convertFastqToFasta() {
}
public void processFasta(String inputFile, String outputFasta, String outputQual) throws Exception {
- BufferedReader bf = null;
- for (int i = 0; i < FILE_SUFFIX.length; i++) {
- bf = Utils.getFile(inputFile, FILE_SUFFIX[i]);
- if (bf != null ) { break; }
- }
+ BufferedReader bf = Utils.getFile(inputFile, FILE_SUFFIX);
+ if (bf == null) { return; }
PrintStream fastaOut = new PrintStream(new File(outputFasta));
PrintStream qualOut = new PrintStream(new File(outputQual));
String line = null;
String header = "";
while ((line = bf.readLine()) != null) {
fastaOut.println(">"+line.substring(1, line.length()));
line = bf.readLine();
fastaOut.println(Utils.convertToFasta(line));
line = bf.readLine();
qualOut.println(">"+line.substring(1, line.length()));
line = bf.readLine();
qualOut.println(Utils.convertToFasta(Utils.decodeQualRecord(line, line.length(), OFFSET_CHAR)));
}
bf.close();
}
public static void printUsage() {
System.err.println("This program sizes a fasta or fastq file. Multiple fasta files can be supplied by using a comma-separated list.");
System.err.println("Example usage: convertFastqToFasta in.fq out.fasta out.qual encoding");
}
public static void main(String[] args) throws Exception {
if (args.length < 3) { printUsage(); System.exit(1);}
if (args.length > 3) { convertFastqToFasta.OFFSET_CHAR = args[3].charAt(0); }
convertFastqToFasta f = new convertFastqToFasta();
f.processFasta(args[0], args[1], args[2]);
}
}
| true | true | public void processFasta(String inputFile, String outputFasta, String outputQual) throws Exception {
BufferedReader bf = null;
for (int i = 0; i < FILE_SUFFIX.length; i++) {
bf = Utils.getFile(inputFile, FILE_SUFFIX[i]);
if (bf != null ) { break; }
}
PrintStream fastaOut = new PrintStream(new File(outputFasta));
PrintStream qualOut = new PrintStream(new File(outputQual));
String line = null;
String header = "";
while ((line = bf.readLine()) != null) {
fastaOut.println(">"+line.substring(1, line.length()));
line = bf.readLine();
fastaOut.println(Utils.convertToFasta(line));
line = bf.readLine();
qualOut.println(">"+line.substring(1, line.length()));
line = bf.readLine();
qualOut.println(Utils.convertToFasta(Utils.decodeQualRecord(line, line.length(), OFFSET_CHAR)));
}
bf.close();
}
| public void processFasta(String inputFile, String outputFasta, String outputQual) throws Exception {
BufferedReader bf = Utils.getFile(inputFile, FILE_SUFFIX);
if (bf == null) { return; }
PrintStream fastaOut = new PrintStream(new File(outputFasta));
PrintStream qualOut = new PrintStream(new File(outputQual));
String line = null;
String header = "";
while ((line = bf.readLine()) != null) {
fastaOut.println(">"+line.substring(1, line.length()));
line = bf.readLine();
fastaOut.println(Utils.convertToFasta(line));
line = bf.readLine();
qualOut.println(">"+line.substring(1, line.length()));
line = bf.readLine();
qualOut.println(Utils.convertToFasta(Utils.decodeQualRecord(line, line.length(), OFFSET_CHAR)));
}
bf.close();
}
|
diff --git a/src/etc/jtlv/GROne/GROneGame.java b/src/etc/jtlv/GROne/GROneGame.java
index 7e768d3..33dac78 100644
--- a/src/etc/jtlv/GROne/GROneGame.java
+++ b/src/etc/jtlv/GROne/GROneGame.java
@@ -1,1221 +1,1222 @@
import java.util.Iterator;
import java.util.Stack;
import java.util.Vector;
import net.sf.javabdd.BDD;
import net.sf.javabdd.BDDVarSet;
import net.sf.javabdd.BDD.BDDIterator;
import edu.wis.jtlv.env.Env;
import edu.wis.jtlv.env.module.ModuleWithWeakFairness;
import edu.wis.jtlv.env.module.Module;
import edu.wis.jtlv.lib.FixPoint;
import edu.wis.jtlv.old_lib.games.GameException;
/**
* <p>
* Nir Piterman, Amir Pnueli, and Yaniv Sa’ar. Synthesis of Reactive(1) Designs.
* In VMCAI, pages 364–380, Charleston, SC, Jenuary 2006.
* </p>
* <p>
* To execute, create an object with two Modules, one for the system and the
* other for the environment, and then just extract the strategy through
* {@link edu.wis.jtlv.old_lib.games.GR1Game#printWinningStrategy()}.
* </p>
*
* @version {@value edu.wis.jtlv.env.Env#version}
* @author yaniv sa'ar. (parts modified by Cameron Finucane)
*
*/
public class GROneGame {
private ModuleWithWeakFairness env;
private ModuleWithWeakFairness sys;
int sysJustNum, envJustNum;
private BDD player1_winning;
private BDD player2_winning;
private boolean autBDDTrue;
// p2_winning in GRGAmes are !p1_winning
public GROneGame(ModuleWithWeakFairness env, ModuleWithWeakFairness sys, int sysJustNum, int envJustNum)
throws GameException {
if ((env == null) || (sys == null)) {
throw new GameException(
"cannot instanciate a GR[1] Game with an empty player.");
}
this.env = env;
this.sys = sys;
this.sysJustNum = sysJustNum;
this.envJustNum = envJustNum;
// for now I'm giving max_y 50, at the end I'll cut it (and during, I'll
// extend if needed. (using vectors only makes things more complicate
// since we cannot instantiate vectors with new vectors)
x_mem = new BDD[sysJustNum][envJustNum][50];
y_mem = new BDD[sysJustNum][50];
z_mem = new BDD[sysJustNum];
x2_mem = new BDD[sysJustNum][envJustNum][50][50];
y2_mem = new BDD[sysJustNum][50];
z2_mem = new BDD[50];
this.player2_winning = this.calculate_win();
this.player1_winning = this.calculate_loss();
//this.player1_winning = this.player2_winning.not();
}
public GROneGame(ModuleWithWeakFairness env, ModuleWithWeakFairness sys)
throws GameException {
this(env, sys, sys.justiceNum(), env.justiceNum());
}
public BDD[][][] x_mem;
public BDD[][][][] x2_mem;
public BDD[][] y_mem, y2_mem;
public BDD[] z_mem, z2_mem;
/**
* <p>
* Calculating winning states.
* </p>
*
* @return The winning states for this game.
*/
private BDD calculate_win() {
BDD x, y, z;
FixPoint<BDD> iterZ, iterY, iterX;
int cy = 0;
z = Env.TRUE();
for (iterZ = new FixPoint<BDD>(); iterZ.advance(z);) {
//for (int j = 0; j < sys.justiceNum(); j++) {
for (int j = 0; j < sysJustNum; j++) {
cy = 0;
y = Env.FALSE();
for (iterY = new FixPoint<BDD>(); iterY.advance(y);) {
BDD start = sys.justiceAt(j).and(env.yieldStates(sys, z))
.or(env.yieldStates(sys, y));
y = Env.FALSE();
for (int i = 0; i < envJustNum; i++) {
BDD negp = env.justiceAt(i).not();
x = z.id();
for (iterX = new FixPoint<BDD>(); iterX.advance(x);) {
x = negp.and(env.yieldStates(sys, x)).or(start);
}
x_mem[j][i][cy] = x.id();
y = y.id().or(x);
}
y_mem[j][cy] = y.id();
cy++;
if (cy % 50 == 0) {
x_mem = extend_size(x_mem, cy);
y_mem = extend_size(y_mem, cy);
}
}
z = y.id();
z_mem[j] = z.id();
}
}
x_mem = extend_size(x_mem, 0);
y_mem = extend_size(y_mem, 0);
return z.id();
}
private BDD calculate_loss() {
BDD x, y, z;
FixPoint<BDD> iterZ, iterY, iterX;
int c = 0;
int a = 0;
z = Env.FALSE();
x = Env.FALSE();
for (iterZ = new FixPoint<BDD>(); iterZ.advance(z);) {
//for (int j = 0; j < sys.justiceNum(); j++) {
for (int j = 0; j < sysJustNum; j++) {
y = Env.TRUE();
for (iterY = new FixPoint<BDD>(); iterY.advance(y);) {
BDD start = ((sys.justiceAt(j).not()).or((env.yieldStates(sys, z.not())).not()))
//BDD start = ((sys.justiceAt(j).not()).or(sys.yieldStates(sys, z)))
.and((env.yieldStates(sys, y.not())).not());
for (int i = 0; i < envJustNum; i++) {
x = Env.FALSE();
c=0;
for (iterX = new FixPoint<BDD>(); iterX.advance(x);) {
x = x.id().or((env.justiceAt(i).or(((env.yieldStates(sys, x.not())).not()))).and(start));
//x = x.id().or((env.justiceAt(i).or(env.yieldStates(sys, x))).and(start));
x2_mem[j][i][a][c] = x.id();
//System.out.println("X ["+ j + ", " + i + ", " + a + ", " + c + "] = " + x2_mem[j][i][a][c]);
c++;
}
y = y.id().and(x);
}
if (c % 50 == 0) {
x2_mem = extend_size(x2_mem, c);
}
}
y2_mem[j][a] = y.id();
//System.out.println("Y ["+ j + ", " + a + "] = " + y2_mem[j][a]);
z = x.id().or(y);
}
z2_mem[a] = z.id();
//System.out.println("Z ["+ a + "] = " + z2_mem[a]);
a++;
if (a % 50 == 0) {
z2_mem = extend_size(z2_mem, a);
y2_mem = extend_size(y2_mem, a);
}
}
x2_mem = extend_size(x2_mem, 0);
y2_mem = extend_size(y2_mem, 0);
z2_mem = extend_size(z2_mem, 0);
//System.out.println(z.id().equals(player2_winning.not()));
return z.id();
}
private BDD[][][][] extend_size(BDD[][][][] in, int extended_size) {
BDD[][][][] res;
if (extended_size > 0) {
res = new BDD[in.length][in[0].length][in[0][0].length + extended_size][in[0][0][0].length
+ extended_size];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
for (int k = 0; k < in[i][j].length; k++) {
for (int m = 0; m < in[i][j][k].length; m++) {
res[i][j][k][m] = in[i][j][k][m];
}
}
}
}
} else {
res = new BDD[in.length][in[0].length][in[0][0].length][];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
for (int k = 0; k < in[i][j].length; k++) {
int real_size = 0;
for (int m = 0; m < in[i][j][k].length; m++) {
if (in[i][j][k][m] != null)
real_size++;
}
res[i][j][k] = new BDD[real_size];
int new_add = 0;
for (int m = 0; m < in[i][j][k].length; m++) {
if (in[i][j][k][m] != null) {
res[i][j][k][new_add] = in[i][j][k][m];
new_add++;
}
}
}
}
}
}
return res;
}
// extended_size<=0 will tight the arrays to be the exact sizes.
private BDD[][][] extend_size(BDD[][][] in, int extended_size) {
BDD[][][] res;
if (extended_size > 0) {
res = new BDD[in.length][in[0].length][in[0][0].length
+ extended_size];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
for (int k = 0; k < in[i][j].length; k++) {
res[i][j][k] = in[i][j][k];
}
}
}
} else {
res = new BDD[in.length][in[0].length][];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
int real_size = 0;
for (int k = 0; k < in[i][j].length; k++) {
if (in[i][j][k] != null)
real_size++;
}
res[i][j] = new BDD[real_size];
int new_add = 0;
for (int k = 0; k < in[i][j].length; k++) {
if (in[i][j][k] != null) {
res[i][j][new_add] = in[i][j][k];
new_add++;
}
}
}
}
}
return res;
}
// extended_size<=0 will tight the arrays to be the exact sizes.
private BDD[][] extend_size(BDD[][] in, int extended_size) {
BDD[][] res;
if (extended_size > 0) {
res = new BDD[in.length][in[0].length + extended_size];
for (int i = 0; i < in.length; i++) {
for (int j = 0; j < in[i].length; j++) {
res[i][j] = in[i][j];
}
}
} else {
res = new BDD[in.length][];
for (int i = 0; i < in.length; i++) {
int real_size = 0;
for (int j = 0; j < in[i].length; j++) {
if (in[i][j] != null)
real_size++;
}
res[i] = new BDD[real_size];
int new_add = 0;
for (int j = 0; j < in[i].length; j++) {
if (in[i][j] != null) {
res[i][new_add] = in[i][j];
new_add++;
}
}
}
}
return res;
}
private BDD[] extend_size(BDD[] in, int extended_size) {
BDD[] res;
if (extended_size > 0) {
res = new BDD[in.length + extended_size];
for (int i = 0; i < in.length; i++) {
res[i] = in[i];
}
} else {
int real_size = 0;
for (int j = 0; j < in.length; j++) {
if (in[j] != null)
real_size++;
}
res = new BDD[real_size];
for (int j = 0; j < real_size; j++) {
res[j] = in[j];
}
}
return res;
}
/**
* <p>
* Extracting an arbitrary implementation from the set of possible
* strategies.
* </p>
*/
public void printWinningStrategy(BDD ini) {
calculate_strategy(3, ini);
// return calculate_strategy(3);
// return calculate_strategy(7);
// return calculate_strategy(11);
// return calculate_strategy(15);
// return calculate_strategy(19);
// return calculate_strategy(23);
}
public void printLosingStrategy(BDD ini) {
calculate_counterstrategy(ini);
// return calculate_strategy(3);
// return calculate_strategy(7);
// return calculate_strategy(11);
// return calculate_strategy(15);
// return calculate_strategy(19);
}
//public void printLosingTrace(BDD ini) {
// calculate_countertrace(ini);
// return calculate_strategy(3);
// return calculate_strategy(7);
// return calculate_strategy(11);
// return calculate_strategy(15);
// return calculate_strategy(19);
// /}
/**
* <p>
* Extracting an implementation from the set of possible strategies with the
* given priority to the next step.
* </p>
* <p>
* Possible priorities are:<br>
* 3 - Z Y X.<br>
* 7 - Z X Y.<br>
* 11 - Y Z X.<br>
* 15 - Y X Z.<br>
* 19 - X Z Y.<br>
* 23 - X Y Z.<br>
* </p>
*
* @param kind
* The priority kind.
*/
public void calculate_strategy(int kind, BDD ini) {
calculate_strategy(kind, ini, true);
}
public boolean calculate_strategy(int kind, BDD ini, boolean det) {
int strategy_kind = kind;
BDD autBDD = sys.trans().and(env.trans());
Stack<BDD> st_stack = new Stack<BDD>();
Stack<Integer> j_stack = new Stack<Integer>();
Stack<RawState> aut = new Stack<RawState>();
boolean result = true;
// FDSModule res = new FDSModule("strategy");
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
BDD this_ini = (BDD) ini_iterator.next();
RawState test_st = new RawState(aut.size(), this_ini, 0);
int idx = -1;
for (RawState cmp_st : aut) {
if (cmp_st.equals(test_st, false)) { // search ignoring rank
idx = aut.indexOf(cmp_st);
break;
}
}
if (idx != -1) {
// This initial state is already in the automaton
continue;
}
// Otherwise, we need to attach this initial state to the automaton
st_stack.push(this_ini);
j_stack.push(new Integer(0)); // TODO: is there a better default j?
this_ini.printSet();
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
int p_j = j_stack.pop().intValue();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawState new_state = new RawState(aut.size(), p_st, p_j);
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
/* Find Y index of current state */
// find minimal cy and an i
int p_cy = -1;
for (int i = 0; i < y_mem[p_j].length; i++) {
if (!p_st.and(y_mem[p_j][i]).isZero()) {
p_cy = i;
break;
}
}
assert p_cy >= 0 : "Couldn't find p_cy";
/* Find X index of current state */
int p_i = -1;
for (int i = 0; i < envJustNum; i++) {
if (!p_st.and(x_mem[p_j][i][p_cy]).isZero()) {
p_i = i;
break;
}
}
assert p_i >= 0 : "Couldn't find p_i";
// computing the set of env possible successors.
Vector<BDD> succs = new Vector<BDD>();
BDD all_succs = env.succ(p_st);
if (all_succs.isZero()) return true;
for (BDDIterator all_states = all_succs.iterator(env
.moduleUnprimeVars()); all_states.hasNext();) {
BDD sin = (BDD) all_states.next();
succs.add(sin);
}
BDD candidate = Env.FALSE();
// For each env successor, find a strategy successor
for (Iterator<BDD> iter_succ = succs.iterator(); iter_succ
.hasNext();) {
BDD primed_cur_succ = Env.prime(iter_succ.next());
BDD next_op = Env
.unprime(sys.trans().and(p_st).and(primed_cur_succ)
.exist(
env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())));
candidate = Env.FALSE();
int jcand = p_j;
int local_kind = strategy_kind;
while (candidate.isZero() & (local_kind >= 0)) {
// a - first successor option in the strategy.
// (rho_1 in Piterman; satisfy current goal and move to next goal)
if ((local_kind == 3) | (local_kind == 7)
| (local_kind == 10) | (local_kind == 13)
| (local_kind == 18) | (local_kind == 21)) {
if (!p_st.and(sys.justiceAt(p_j)).isZero()) {
int next_p_j = (p_j + 1) % sysJustNum;
- //Look for the next goal and see if you can satisfy it by staying in place. If so, swell. If not, poo.
- while (!p_st.and(primed_cur_succ.and(Env.prime(p_st.and(sys.justiceAt(next_p_j))))).isZero() && next_p_j!=p_j)
+ //Look for the next goal and see if you can satisfy it by staying in place. If so, swell.
+ while (!next_op.and(sys.justiceAt(next_p_j)).isZero() && next_p_j!=p_j)
{
next_p_j = (next_p_j + 1) % sysJustNum;
}
if (next_p_j!=p_j)
{
int look_r = 0;
while ((next_op.and(y_mem[next_p_j][look_r]).isZero())) {
look_r++;
}
BDD opt = next_op.and(y_mem[next_p_j][look_r]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("1");
jcand = next_p_j;
}
} else {
//There are no unsatisfied goals, so just stay in place, yay.
- candidate = p_st;
- jcand = p_j;
+ candidate = next_op;
+ jcand = p_j;
+ //System.out.println("All goals satisfied");
}
}
}
// b - second successor option in the strategy.
// (rho_2 in Piterman; move closer to current goal)
if ((local_kind == 2) | (local_kind == 5)
| (local_kind == 11) | (local_kind == 15)
| (local_kind == 17) | (local_kind == 22)) {
if (p_cy > 0) {
int look_r = 0;
// look for the farest r.
while ((next_op.and(y_mem[p_j][look_r]).isZero())
& (look_r < p_cy)) {
look_r++;
}
BDD opt = next_op.and(y_mem[p_j][look_r]);
if ((look_r != p_cy) && (!opt.isZero())) {
candidate = opt;
//System.out.println("2");
}
}
}
// c - third successor option in the strategy.
// (rho_3 in Piterman; falsify environment :()
if ((local_kind == 1) | (local_kind == 6)
| (local_kind == 9) | (local_kind == 14)
| (local_kind == 19) | (local_kind == 23)) {
if (!p_st.and(env.justiceAt(p_i).not()).isZero()) {
BDD opt = next_op.and(x_mem[p_j][p_i][p_cy]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("3");
}
}
}
// no successor was found yet.
//assert ((local_kind != 0) & (local_kind != 4)
if (!((local_kind != 0) & (local_kind != 4)
& (local_kind != 8) & (local_kind != 12)
& (local_kind != 16) & (local_kind != 20))) {
System.out.println("No successor was found");
result = false;
}
local_kind--;
}
// picking one candidate. In JDD satOne is not take
// env.unprimeVars().union(sys.unprimeVars()) into its
// considerations.
// BDD one_cand = candidate.satOne();
/* BDD one_cand = candidate.satOne(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars()), false);
*/
for (BDDIterator candIter = candidate.iterator(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())); candIter.hasNext();) {
BDD one_cand = (BDD) candIter.next();
RawState gsucc = new RawState(aut.size(), one_cand, jcand);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(one_cand);
j_stack.push(jcand);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
if (det) break; //if we only need one successor, stop here
}
autBDD = autBDD.and((p_st.imp(Env.prime(candidate))));
result = result & (candidate.equals(next_op));
//result = result & (candidate.equals(env.trans().and(sys.trans())));
}
}
}
/* Remove stuttering */
// TODO: Make this more efficient (and less ugly) if possible
/*
int num_removed = 0;
for (RawState state1 : aut) {
int j1 = state1.get_rank();
for (RawState state2 : state1.get_succ()) {
int j2 = state2.get_rank();
if ((j2 == (j1 + 1) % sys.justiceNum()) &&
state1.equals(state2, false)) {
// Find any states pointing to state1
for (RawState state3 : aut) {
if (state3.get_succ().indexOf(state1) != -1) {
// Redirect transitions to state2
state3.del_succ(state1);
state3.add_succ(state2);
// Mark the extra state for deletion
state1.set_rank(-1);
}
}
}
}
if (state1.get_rank() == -1) {
num_removed++;
}
}
System.out.println("Removed " + num_removed + " stutter states.");
*/
/* Print output */
if (det) {
String res = "";
for (RawState state : aut) {
if (state.get_rank() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
// return null; // res;
System.out.print("\n\n");
}
if (strategy_kind == 3) return result; else return false;
}
public void generate_safety_aut(BDD ini) {
Stack<BDD> st_stack = new Stack<BDD>();
Stack<RawState> aut = new Stack<RawState>();
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
BDD this_ini = (BDD) ini_iterator.next();
RawState test_st = new RawState(aut.size(), this_ini, 0);
int idx = -1;
for (RawState cmp_st : aut) {
if (cmp_st.equals(test_st, false)) { // search ignoring rank
idx = aut.indexOf(cmp_st);
break;
}
}
if (idx != -1) {
// This initial state is already in the automaton
continue;
}
// Otherwise, we need to attach this initial state to the automaton
st_stack.push(this_ini);
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawState new_state = new RawState(aut.size(), p_st, 0);
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
BDD next_op = Env.unprime(sys.trans().and(p_st).exist(env.moduleUnprimeVars().union(sys.moduleUnprimeVars())));
BDDIterator next_iterator = next_op.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (next_iterator.hasNext()) {
BDD this_next = (BDD) next_iterator.next();
//this_next.printSet();
RawState gsucc = new RawState(aut.size(), this_next, 0);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(this_next);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
}
//System.out.print("------------\n");
}
}
/* Print output */
String res = "";
for (RawState state : aut) {
if (state.get_rank() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
// return null; // res;
}
public void calculate_counterstrategy(BDD ini) {
calculate_counterstrategy(ini, true, true);
}
public boolean calculate_counterstrategy(BDD ini, boolean enable_234, boolean det) {
Stack<BDD> st_stack = new Stack<BDD>();
Stack<Integer> i_stack = new Stack<Integer>();
Stack<Integer> j_stack = new Stack<Integer>();
Stack<RawCState> aut = new Stack<RawCState>();
BDD autBDD = sys.trans().and(env.trans());
boolean result = true;
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
int a = 0;
BDD this_ini = (BDD) ini_iterator.next();
int idx = -1;
st_stack.push(this_ini);
i_stack.push(new Integer(0)); // TODO: is there a better default j?
j_stack.push(new Integer(-1)); // TODO: is there a better default j?
this_ini.printSet();
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
int rank_i = i_stack.pop().intValue();
int rank_j = j_stack.pop().intValue();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawCState new_state = new RawCState(aut.size(), p_st, rank_j, rank_i, Env.FALSE());
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
BDD primed_cur_succ = Env.prime(env.succ(p_st));
BDD input = Env.FALSE();
int new_i = -1, new_j = -1;
while(input.isZero()) {
input = p_st.and(z2_mem[0]).and(primed_cur_succ.and(sys.yieldStates(env,Env.FALSE())));
if (!input.isZero()) {
new_i = rank_i;
new_j = -1;
continue;
}
//\rho_1 transitions in K\"onighofer et al
for (int az = 1; az < z2_mem.length; az++) {
input = p_st.and(z2_mem[az])
.and((primed_cur_succ.and(sys.yieldStates(env,(Env.unprime(primed_cur_succ).and(z2_mem[az-1]))))));
if (!input.isZero()) {
new_i = rank_i;
new_j = -1;
break;
}
}
//if we are only looking for unsatisfiability, we only allow transitions
//into a lower iterate of Z, i.e. \rho_1
if (!enable_234) {
if (input.isZero()) System.out.println("No successor was found");
result = false;
continue;
}
if (!input.isZero()) continue;
//\rho_2 transitions
for (int az = 0; az < z2_mem.length; az++) {
for (int j = 0; j < sysJustNum; j++) {
if (az == 0)
input = p_st.and(z2_mem[az])
.and(primed_cur_succ.and(sys.yieldStates(env,(y2_mem[j][az]))))
.and(sys.yieldStates(env,(z2_mem[az])).not());
else
input = p_st.and(z2_mem[az]).and(z2_mem[az-1].not())
.and(primed_cur_succ.and(sys.yieldStates(env,(y2_mem[j][az]))))
.and((sys.yieldStates(env,(z2_mem[az-1]))).not());
if (!input.isZero()) {
new_i = rank_i;
new_j = j;
break;
}
}
if (rank_j != -1) break;
}
if (!input.isZero()) continue;
//\rho_3 transitions
if (rank_j != -1 && p_st.and(env.justiceAt(rank_i)).isZero()) {
new_i = (rank_i + 1) % env.justiceNum();
new_j = rank_j;
for (int az = 0; az < z2_mem.length; az++) {
if (az == 0)
input = (p_st.and(z2_mem[az])
.and(primed_cur_succ.and(sys.yieldStates(env,y2_mem[rank_j][az])))
.and((sys.yieldStates(env,(z2_mem[az]))).not()));
else
input = (p_st.and(z2_mem[az]).and(z2_mem[az-1].not())
.and(primed_cur_succ.and((sys.yieldStates(env,y2_mem[rank_j][az]))))
.and((sys.yieldStates(env,z2_mem[az-1])).not()));
if (!input.isZero()) break;
}
}
if (!input.isZero()) continue;
//\rho_4 transitions
for (int az = 0; az < z2_mem.length; az++) {
if (rank_i != -1 && rank_j != -1) {
for (int c = 1; c < x2_mem[rank_j][rank_i][az].length; c++) {
if (az == 0)
input = ((p_st.and(z2_mem[az])
.and(x2_mem[rank_j][rank_i][az][c])
.and(x2_mem[rank_j][rank_i][az][c-1].not())
.and(primed_cur_succ.and((sys.yieldStates(env,x2_mem[rank_j][rank_i][az][c-1])))
.and(sys.yieldStates(env,z2_mem[az]).not()))));
else
input = ((p_st.and(z2_mem[az])
.and(x2_mem[rank_j][rank_i][az][c])
.and(x2_mem[rank_j][rank_i][az][c-1].not())
.and(primed_cur_succ.and((sys.yieldStates(env,x2_mem[rank_j][rank_i][az][c-1])))
.and((sys.yieldStates(env,z2_mem[az-1])).not()))));
if (!input.isZero()) {
new_i = rank_i;
new_j = rank_j;
break;
}
}
}
}
assert (!input.isZero()) : "No successor was found";
}
addState(new_state, input, new_i, new_j, aut, st_stack, i_stack, j_stack, det);
autBDD = autBDD.and(p_st.imp(input));
//result is true if for every state, all environment actions take us into a lower iterate of Z
//this means the environment can do anything to prevent the system from achieving some goal.
result = result & (input.equals(p_st));
}
}
if (det) {
String res = "";
for (RawCState state : aut) {
if (state.get_rank_i() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
}
return result;
}
public void addState(RawCState new_state, BDD input, int new_i, int new_j, Stack<RawCState> aut, Stack<BDD> st_stack, Stack<Integer> i_stack, Stack<Integer> j_stack, boolean det) {
//method for adding stated to the aut and state stack, based on whether we want a deterministic or nondet automaton
for (BDDIterator inputIter = input.iterator(env
.modulePrimeVars()); inputIter.hasNext();) {
BDD inputOne = (BDD) inputIter.next();
// computing the set of system possible successors.
Vector<BDD> sys_succs = new Vector<BDD>();
BDD all_sys_succs = sys.succ(new_state.get_state().and(inputOne));
int idx = -1;
if (all_sys_succs.equals(Env.FALSE())) {
RawCState gsucc = new RawCState(aut.size(), Env.unprime(inputOne), new_j, new_i, inputOne);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
continue;
}
for (BDDIterator all_sys_states = all_sys_succs.iterator(sys
.moduleUnprimeVars()); all_sys_states.hasNext();) {
BDD sin = (BDD) all_sys_states.next();
sys_succs.add(sin);
}
// For each system successor, find a strategy successor
for (Iterator<BDD> iter_succ = sys_succs.iterator(); iter_succ
.hasNext();) {
BDD sys_succ = iter_succ.next().and(Env.unprime(inputOne));
RawCState gsucc = new RawCState(aut.size(), sys_succ, new_j, new_i, inputOne);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(sys_succ);
i_stack.push(new_i);
j_stack.push(new_j);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
}
if (det) break;
}
}
@SuppressWarnings("unused")
private class RawState {
private int id;
private int rank;
private BDD state;
private Vector<RawState> succ;
public RawState(int id, BDD state, int rank) {
this.id = id;
this.state = state;
this.rank = rank;
succ = new Vector<RawState>(10);
}
public void add_succ(RawState to_add) {
succ.add(to_add);
}
public void del_succ(RawState to_del) {
succ.remove(to_del);
}
public BDD get_state() {
return this.state;
}
public int get_rank() {
return this.rank;
}
public void set_rank(int rank) {
this.rank = rank;
}
public Vector<RawState> get_succ() {
//RawState[] res = new RawState[this.succ.size()];
//this.succ.toArray(res);
return this.succ;
}
public boolean equals(Object other) {
return this.equals(other, true);
}
public boolean equals(Object other, boolean use_rank) {
if (!(other instanceof RawState))
return false;
RawState other_raw = (RawState) other;
if (other_raw == null)
return false;
if (use_rank) {
return ((this.rank == other_raw.rank) & (this.state
.equals(other_raw.state)));
} else {
return (this.state.equals(other_raw.state));
}
}
public String toString() {
String res = "State " + id + " with rank " + rank + " -> "
+ state.toStringWithDomains(Env.stringer) + "\n";
if (succ.isEmpty()) {
res += "\tWith no successors.";
} else {
RawState[] all_succ = new RawState[succ.size()];
succ.toArray(all_succ);
res += "\tWith successors : " + all_succ[0].id;
for (int i = 1; i < all_succ.length; i++) {
res += ", " + all_succ[i].id;
}
}
return res;
}
}
private class RawCState {
private int id;
private int rank_i;//_old, rank_j_old;
private int rank_j;//i_new, rank_j_new;
private BDD input;
private BDD state;
private Vector<RawCState> succ;
/*public RawCState(int id, BDD state, int rank_i_old, int rank_i_new, int rank_j_old, int rank_j_new, BDD input) {
this.id = id;
this.state = state;
this.rank_i_old = rank_i_old;
this.rank_j_old = rank_j_old;
this.rank_i_new = rank_i_new;
this.rank_j_new = rank_j_new;
this.input = input;
}*/
public RawCState(int id, BDD state, int rank_j, int rank_i, BDD input) {
this.id = id;
this.state = state;
this.rank_i = rank_i;
this.rank_j = rank_j;
this.input = input;
succ = new Vector<RawCState>(10);
}
public void add_succ(RawCState to_add) {
succ.add(to_add);
}
public void del_succ(RawCState to_del) {
succ.remove(to_del);
}
public BDD get_input() {
return this.input;
}
public void set_input(BDD input) {
this.input = input;
}
public BDD get_state() {
return this.state;
}
public int get_rank_i() {
return this.rank_i;
}
public void set_rank_i(int rank) {
this.rank_i = rank;
}
public int get_rank_j() {
return this.rank_j;
}
public void set_rank_j(int rank) {
this.rank_j = rank;
}
/*public int get_rank_i_new() {
return this.rank_i_new;
}
public void set_rank_i_new(int rank) {
this.rank_i_new = rank;
}
public int get_rank_j_new() {
return this.rank_j_new;
}
public void set_rank_j_new(int rank) {
this.rank_j_new = rank;
}*/
public boolean equals(Object other) {
return this.equals(other, true);
}
public boolean equals(Object other, boolean use_rank) {
if (!(other instanceof RawCState))
return false;
RawCState other_raw = (RawCState) other;
if (other_raw == null)
return false;
if (use_rank) {
//return ((this.rank_i_old == other_raw.rank_i_old) & (this.rank_j_old == other_raw.rank_j_old) & (this.rank_i_new == other_raw.rank_i_new) & (this.rank_j_new == other_raw.rank_j_new) &
return ((this.rank_i == other_raw.rank_i) & (this.rank_j == other_raw.rank_j) &
(this.state.equals(other_raw.state)));
} else {
return ((this.state.equals(other_raw.state)));
}
}
/*public String toString() {
String res = "State " + id + " with rank_i " + rank_i + " with rank_j " + rank_j + " -> "
+ state.toStringWithDomains(Env.stringer) + "\n";
if (succ.isEmpty()) {
res += "\tWith no successors.";
} else {
RawCState[] all_succ = new RawCState[succ.size()];
succ.toArray(all_succ);
res += "\tWith successors : " + all_succ[0].id;
for (int i = 1; i < all_succ.length; i++) {
res += ", " + all_succ[i].id;
}
}
res += "\tWith input : " + input.toStringWithDomains(Env.stringer) + "\n";
return res;
}*/
public String toString() {
String res = "State " + id + " with rank (" + rank_i + "," + rank_j + ") -> "
+ state.toStringWithDomains(Env.stringer) + "\n";
if (succ.isEmpty()) {
res += "\tWith no successors.";
} else {
RawCState[] all_succ = new RawCState[succ.size()];
succ.toArray(all_succ);
res += "\tWith successors : " + all_succ[0].id;
for (int i = 1; i < all_succ.length; i++) {
res += ", " + all_succ[i].id;
}
}
return res;
}
}
/**
* <p>
* Getter for the environment player.
* </p>
*
* @return The environment player.
*/
public ModuleWithWeakFairness getEnvPlayer() {
return env;
}
/**
* <p>
* Getter for the system player.
* </p>
*
* @return The system player.
*/
public ModuleWithWeakFairness getSysPlayer() {
return sys;
}
/**
* <p>
* Getter for the environment's winning states.
* </p>
*
* @return The environment's winning states.
*/
public BDD sysWinningStates() {
return player2_winning;
}
/**
* <p>
* Getter for the system's winning states.
* </p>
*
* @return The system's winning states.
*/
public BDD envWinningStates() {
return player2_winning.not();
}
public BDD gameInitials() {
return getSysPlayer().initial().and(getEnvPlayer().initial());
}
public BDD[] playersWinningStates() {
return new BDD[] { envWinningStates(), sysWinningStates() };
}
public BDD firstPlayersWinningStates() {
return envWinningStates();
}
public BDD secondPlayersWinningStates() {
return sysWinningStates();
}
}
| false | true | public boolean calculate_strategy(int kind, BDD ini, boolean det) {
int strategy_kind = kind;
BDD autBDD = sys.trans().and(env.trans());
Stack<BDD> st_stack = new Stack<BDD>();
Stack<Integer> j_stack = new Stack<Integer>();
Stack<RawState> aut = new Stack<RawState>();
boolean result = true;
// FDSModule res = new FDSModule("strategy");
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
BDD this_ini = (BDD) ini_iterator.next();
RawState test_st = new RawState(aut.size(), this_ini, 0);
int idx = -1;
for (RawState cmp_st : aut) {
if (cmp_st.equals(test_st, false)) { // search ignoring rank
idx = aut.indexOf(cmp_st);
break;
}
}
if (idx != -1) {
// This initial state is already in the automaton
continue;
}
// Otherwise, we need to attach this initial state to the automaton
st_stack.push(this_ini);
j_stack.push(new Integer(0)); // TODO: is there a better default j?
this_ini.printSet();
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
int p_j = j_stack.pop().intValue();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawState new_state = new RawState(aut.size(), p_st, p_j);
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
/* Find Y index of current state */
// find minimal cy and an i
int p_cy = -1;
for (int i = 0; i < y_mem[p_j].length; i++) {
if (!p_st.and(y_mem[p_j][i]).isZero()) {
p_cy = i;
break;
}
}
assert p_cy >= 0 : "Couldn't find p_cy";
/* Find X index of current state */
int p_i = -1;
for (int i = 0; i < envJustNum; i++) {
if (!p_st.and(x_mem[p_j][i][p_cy]).isZero()) {
p_i = i;
break;
}
}
assert p_i >= 0 : "Couldn't find p_i";
// computing the set of env possible successors.
Vector<BDD> succs = new Vector<BDD>();
BDD all_succs = env.succ(p_st);
if (all_succs.isZero()) return true;
for (BDDIterator all_states = all_succs.iterator(env
.moduleUnprimeVars()); all_states.hasNext();) {
BDD sin = (BDD) all_states.next();
succs.add(sin);
}
BDD candidate = Env.FALSE();
// For each env successor, find a strategy successor
for (Iterator<BDD> iter_succ = succs.iterator(); iter_succ
.hasNext();) {
BDD primed_cur_succ = Env.prime(iter_succ.next());
BDD next_op = Env
.unprime(sys.trans().and(p_st).and(primed_cur_succ)
.exist(
env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())));
candidate = Env.FALSE();
int jcand = p_j;
int local_kind = strategy_kind;
while (candidate.isZero() & (local_kind >= 0)) {
// a - first successor option in the strategy.
// (rho_1 in Piterman; satisfy current goal and move to next goal)
if ((local_kind == 3) | (local_kind == 7)
| (local_kind == 10) | (local_kind == 13)
| (local_kind == 18) | (local_kind == 21)) {
if (!p_st.and(sys.justiceAt(p_j)).isZero()) {
int next_p_j = (p_j + 1) % sysJustNum;
//Look for the next goal and see if you can satisfy it by staying in place. If so, swell. If not, poo.
while (!p_st.and(primed_cur_succ.and(Env.prime(p_st.and(sys.justiceAt(next_p_j))))).isZero() && next_p_j!=p_j)
{
next_p_j = (next_p_j + 1) % sysJustNum;
}
if (next_p_j!=p_j)
{
int look_r = 0;
while ((next_op.and(y_mem[next_p_j][look_r]).isZero())) {
look_r++;
}
BDD opt = next_op.and(y_mem[next_p_j][look_r]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("1");
jcand = next_p_j;
}
} else {
//There are no unsatisfied goals, so just stay in place, yay.
candidate = p_st;
jcand = p_j;
}
}
}
// b - second successor option in the strategy.
// (rho_2 in Piterman; move closer to current goal)
if ((local_kind == 2) | (local_kind == 5)
| (local_kind == 11) | (local_kind == 15)
| (local_kind == 17) | (local_kind == 22)) {
if (p_cy > 0) {
int look_r = 0;
// look for the farest r.
while ((next_op.and(y_mem[p_j][look_r]).isZero())
& (look_r < p_cy)) {
look_r++;
}
BDD opt = next_op.and(y_mem[p_j][look_r]);
if ((look_r != p_cy) && (!opt.isZero())) {
candidate = opt;
//System.out.println("2");
}
}
}
// c - third successor option in the strategy.
// (rho_3 in Piterman; falsify environment :()
if ((local_kind == 1) | (local_kind == 6)
| (local_kind == 9) | (local_kind == 14)
| (local_kind == 19) | (local_kind == 23)) {
if (!p_st.and(env.justiceAt(p_i).not()).isZero()) {
BDD opt = next_op.and(x_mem[p_j][p_i][p_cy]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("3");
}
}
}
// no successor was found yet.
//assert ((local_kind != 0) & (local_kind != 4)
if (!((local_kind != 0) & (local_kind != 4)
& (local_kind != 8) & (local_kind != 12)
& (local_kind != 16) & (local_kind != 20))) {
System.out.println("No successor was found");
result = false;
}
local_kind--;
}
// picking one candidate. In JDD satOne is not take
// env.unprimeVars().union(sys.unprimeVars()) into its
// considerations.
// BDD one_cand = candidate.satOne();
/* BDD one_cand = candidate.satOne(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars()), false);
*/
for (BDDIterator candIter = candidate.iterator(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())); candIter.hasNext();) {
BDD one_cand = (BDD) candIter.next();
RawState gsucc = new RawState(aut.size(), one_cand, jcand);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(one_cand);
j_stack.push(jcand);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
if (det) break; //if we only need one successor, stop here
}
autBDD = autBDD.and((p_st.imp(Env.prime(candidate))));
result = result & (candidate.equals(next_op));
//result = result & (candidate.equals(env.trans().and(sys.trans())));
}
}
}
/* Remove stuttering */
// TODO: Make this more efficient (and less ugly) if possible
/*
int num_removed = 0;
for (RawState state1 : aut) {
int j1 = state1.get_rank();
for (RawState state2 : state1.get_succ()) {
int j2 = state2.get_rank();
if ((j2 == (j1 + 1) % sys.justiceNum()) &&
state1.equals(state2, false)) {
// Find any states pointing to state1
for (RawState state3 : aut) {
if (state3.get_succ().indexOf(state1) != -1) {
// Redirect transitions to state2
state3.del_succ(state1);
state3.add_succ(state2);
// Mark the extra state for deletion
state1.set_rank(-1);
}
}
}
}
if (state1.get_rank() == -1) {
num_removed++;
}
}
System.out.println("Removed " + num_removed + " stutter states.");
*/
/* Print output */
if (det) {
String res = "";
for (RawState state : aut) {
if (state.get_rank() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
// return null; // res;
System.out.print("\n\n");
}
if (strategy_kind == 3) return result; else return false;
}
| public boolean calculate_strategy(int kind, BDD ini, boolean det) {
int strategy_kind = kind;
BDD autBDD = sys.trans().and(env.trans());
Stack<BDD> st_stack = new Stack<BDD>();
Stack<Integer> j_stack = new Stack<Integer>();
Stack<RawState> aut = new Stack<RawState>();
boolean result = true;
// FDSModule res = new FDSModule("strategy");
BDDIterator ini_iterator = ini.iterator(env.moduleUnprimeVars().union(sys.moduleUnprimeVars()));
while (ini_iterator.hasNext()) {
BDD this_ini = (BDD) ini_iterator.next();
RawState test_st = new RawState(aut.size(), this_ini, 0);
int idx = -1;
for (RawState cmp_st : aut) {
if (cmp_st.equals(test_st, false)) { // search ignoring rank
idx = aut.indexOf(cmp_st);
break;
}
}
if (idx != -1) {
// This initial state is already in the automaton
continue;
}
// Otherwise, we need to attach this initial state to the automaton
st_stack.push(this_ini);
j_stack.push(new Integer(0)); // TODO: is there a better default j?
this_ini.printSet();
// iterating over the stacks.
while (!st_stack.isEmpty()) {
// making a new entry.
BDD p_st = st_stack.pop();
int p_j = j_stack.pop().intValue();
/* Create a new automaton state for our current state
(or use a matching one if it already exists) */
RawState new_state = new RawState(aut.size(), p_st, p_j);
int nidx = aut.indexOf(new_state);
if (nidx == -1) {
aut.push(new_state);
} else {
new_state = aut.elementAt(nidx);
}
/* Find Y index of current state */
// find minimal cy and an i
int p_cy = -1;
for (int i = 0; i < y_mem[p_j].length; i++) {
if (!p_st.and(y_mem[p_j][i]).isZero()) {
p_cy = i;
break;
}
}
assert p_cy >= 0 : "Couldn't find p_cy";
/* Find X index of current state */
int p_i = -1;
for (int i = 0; i < envJustNum; i++) {
if (!p_st.and(x_mem[p_j][i][p_cy]).isZero()) {
p_i = i;
break;
}
}
assert p_i >= 0 : "Couldn't find p_i";
// computing the set of env possible successors.
Vector<BDD> succs = new Vector<BDD>();
BDD all_succs = env.succ(p_st);
if (all_succs.isZero()) return true;
for (BDDIterator all_states = all_succs.iterator(env
.moduleUnprimeVars()); all_states.hasNext();) {
BDD sin = (BDD) all_states.next();
succs.add(sin);
}
BDD candidate = Env.FALSE();
// For each env successor, find a strategy successor
for (Iterator<BDD> iter_succ = succs.iterator(); iter_succ
.hasNext();) {
BDD primed_cur_succ = Env.prime(iter_succ.next());
BDD next_op = Env
.unprime(sys.trans().and(p_st).and(primed_cur_succ)
.exist(
env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())));
candidate = Env.FALSE();
int jcand = p_j;
int local_kind = strategy_kind;
while (candidate.isZero() & (local_kind >= 0)) {
// a - first successor option in the strategy.
// (rho_1 in Piterman; satisfy current goal and move to next goal)
if ((local_kind == 3) | (local_kind == 7)
| (local_kind == 10) | (local_kind == 13)
| (local_kind == 18) | (local_kind == 21)) {
if (!p_st.and(sys.justiceAt(p_j)).isZero()) {
int next_p_j = (p_j + 1) % sysJustNum;
//Look for the next goal and see if you can satisfy it by staying in place. If so, swell.
while (!next_op.and(sys.justiceAt(next_p_j)).isZero() && next_p_j!=p_j)
{
next_p_j = (next_p_j + 1) % sysJustNum;
}
if (next_p_j!=p_j)
{
int look_r = 0;
while ((next_op.and(y_mem[next_p_j][look_r]).isZero())) {
look_r++;
}
BDD opt = next_op.and(y_mem[next_p_j][look_r]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("1");
jcand = next_p_j;
}
} else {
//There are no unsatisfied goals, so just stay in place, yay.
candidate = next_op;
jcand = p_j;
//System.out.println("All goals satisfied");
}
}
}
// b - second successor option in the strategy.
// (rho_2 in Piterman; move closer to current goal)
if ((local_kind == 2) | (local_kind == 5)
| (local_kind == 11) | (local_kind == 15)
| (local_kind == 17) | (local_kind == 22)) {
if (p_cy > 0) {
int look_r = 0;
// look for the farest r.
while ((next_op.and(y_mem[p_j][look_r]).isZero())
& (look_r < p_cy)) {
look_r++;
}
BDD opt = next_op.and(y_mem[p_j][look_r]);
if ((look_r != p_cy) && (!opt.isZero())) {
candidate = opt;
//System.out.println("2");
}
}
}
// c - third successor option in the strategy.
// (rho_3 in Piterman; falsify environment :()
if ((local_kind == 1) | (local_kind == 6)
| (local_kind == 9) | (local_kind == 14)
| (local_kind == 19) | (local_kind == 23)) {
if (!p_st.and(env.justiceAt(p_i).not()).isZero()) {
BDD opt = next_op.and(x_mem[p_j][p_i][p_cy]);
if (!opt.isZero()) {
candidate = opt;
//System.out.println("3");
}
}
}
// no successor was found yet.
//assert ((local_kind != 0) & (local_kind != 4)
if (!((local_kind != 0) & (local_kind != 4)
& (local_kind != 8) & (local_kind != 12)
& (local_kind != 16) & (local_kind != 20))) {
System.out.println("No successor was found");
result = false;
}
local_kind--;
}
// picking one candidate. In JDD satOne is not take
// env.unprimeVars().union(sys.unprimeVars()) into its
// considerations.
// BDD one_cand = candidate.satOne();
/* BDD one_cand = candidate.satOne(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars()), false);
*/
for (BDDIterator candIter = candidate.iterator(env.moduleUnprimeVars().union(
sys.moduleUnprimeVars())); candIter.hasNext();) {
BDD one_cand = (BDD) candIter.next();
RawState gsucc = new RawState(aut.size(), one_cand, jcand);
idx = aut.indexOf(gsucc); // the equals doesn't consider
// the id number.
if (idx == -1) {
st_stack.push(one_cand);
j_stack.push(jcand);
aut.add(gsucc);
idx = aut.indexOf(gsucc);
}
new_state.add_succ(aut.elementAt(idx));
if (det) break; //if we only need one successor, stop here
}
autBDD = autBDD.and((p_st.imp(Env.prime(candidate))));
result = result & (candidate.equals(next_op));
//result = result & (candidate.equals(env.trans().and(sys.trans())));
}
}
}
/* Remove stuttering */
// TODO: Make this more efficient (and less ugly) if possible
/*
int num_removed = 0;
for (RawState state1 : aut) {
int j1 = state1.get_rank();
for (RawState state2 : state1.get_succ()) {
int j2 = state2.get_rank();
if ((j2 == (j1 + 1) % sys.justiceNum()) &&
state1.equals(state2, false)) {
// Find any states pointing to state1
for (RawState state3 : aut) {
if (state3.get_succ().indexOf(state1) != -1) {
// Redirect transitions to state2
state3.del_succ(state1);
state3.add_succ(state2);
// Mark the extra state for deletion
state1.set_rank(-1);
}
}
}
}
if (state1.get_rank() == -1) {
num_removed++;
}
}
System.out.println("Removed " + num_removed + " stutter states.");
*/
/* Print output */
if (det) {
String res = "";
for (RawState state : aut) {
if (state.get_rank() != -1) {
res += state + "\n";
}
}
System.out.print("\n\n");
System.out.print(res);
// return null; // res;
System.out.print("\n\n");
}
if (strategy_kind == 3) return result; else return false;
}
|
diff --git a/src/com/android/phone/sip/SipSettings.java b/src/com/android/phone/sip/SipSettings.java
index d6ad69a4..d7586f1c 100644
--- a/src/com/android/phone/sip/SipSettings.java
+++ b/src/com/android/phone/sip/SipSettings.java
@@ -1,527 +1,527 @@
/*
* 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.phone.sip;
import com.android.phone.R;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.sip.SipException;
import android.net.sip.SipErrorCode;
import android.net.sip.SipProfile;
import android.net.sip.SipManager;
import android.net.sip.SipRegistrationListener;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.Process;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* The PreferenceActivity class for managing sip profile preferences.
*/
public class SipSettings extends PreferenceActivity {
public static final String SIP_SHARED_PREFERENCES = "SIP_PREFERENCES";
public static final String PROFILES_DIR = "/profiles/";
static final String KEY_SIP_PROFILE = "sip_profile";
static final String PROFILE_OBJ_FILE = ".pobj";
private static final String BUTTON_SIP_RECEIVE_CALLS =
"sip_receive_calls_key";
private static final String PREF_SIP_LIST = "sip_account_list";
private static final String TAG = "SipSettings";
private static final int REQUEST_ADD_OR_EDIT_SIP_PROFILE = 1;
private PackageManager mPackageManager;
private SipManager mSipManager;
private String mProfilesDirectory;
private SipProfile mProfile;
private CheckBoxPreference mButtonSipReceiveCalls;
private PreferenceCategory mSipListContainer;
private Map<String, SipPreference> mSipPreferenceMap;
private List<SipProfile> mSipProfileList;
private SipSharedPreferences mSipSharedPreferences;
private int mUid = Process.myUid();
private class SipPreference extends Preference {
SipProfile mProfile;
SipPreference(Context c, SipProfile p) {
super(c);
setProfile(p);
}
SipProfile getProfile() {
return mProfile;
}
void setProfile(SipProfile p) {
mProfile = p;
setTitle(p.getProfileName());
updateSummary(mSipSharedPreferences.isReceivingCallsEnabled()
? getString(R.string.registration_status_checking_status)
: getString(R.string.registration_status_not_receiving));
}
void updateSummary(String registrationStatus) {
int profileUid = mProfile.getCallingUid();
boolean isPrimary = mProfile.getUriString().equals(
mSipSharedPreferences.getPrimaryAccount());
Log.v(TAG, "profile uid is " + profileUid + " isPrimary:"
+ isPrimary + " registration:" + registrationStatus
+ " Primary:" + mSipSharedPreferences.getPrimaryAccount()
+ " status:" + registrationStatus);
String summary = "";
if ((profileUid > 0) && (profileUid != mUid)) {
// from third party apps
summary = getString(R.string.third_party_account_summary,
getPackageNameFromUid(profileUid));
} else if (isPrimary) {
summary = getString(R.string.primary_account_summary_with,
registrationStatus);
} else {
summary = registrationStatus;
}
setSummary(summary);
}
}
private String getPackageNameFromUid(int uid) {
try {
String[] pkgs = mPackageManager.getPackagesForUid(uid);
ApplicationInfo ai =
mPackageManager.getApplicationInfo(pkgs[0], 0);
return ai.loadLabel(mPackageManager).toString();
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "cannot find name of uid " + uid, e);
}
return "uid:" + uid;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mSipManager = SipManager.newInstance(SipSettings.this);
mSipSharedPreferences = new SipSharedPreferences(this);
mPackageManager = getPackageManager();
setContentView(R.layout.sip_settings_ui);
addPreferencesFromResource(R.xml.sip_setting);
mProfilesDirectory = getFilesDir().getAbsolutePath() + PROFILES_DIR;
mSipListContainer = (PreferenceCategory) findPreference(PREF_SIP_LIST);
registerForAddSipListener();
registerForReceiveCallsCheckBox();
updateProfilesStatus();
}
@Override
public void onResume() {
super.onResume();
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterForContextMenu(getListView());
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode,
final Intent intent) {
if (resultCode != RESULT_OK && resultCode != RESULT_FIRST_USER) return;
new Thread() {
public void run() {
try {
SipProfile profile = intent.getParcelableExtra(KEY_SIP_PROFILE);
if (resultCode == RESULT_OK) {
Log.v(TAG, "New Profile Name:" + profile.getProfileName());
saveProfileToStorage(profile);
if (profile.getAutoRegistration()
|| mSipSharedPreferences.isPrimaryAccount(
profile.getUriString())) {
registerProfile(profile);
}
} else {
Log.v(TAG, "Removed Profile Name:" + profile.getProfileName());
deleteProfile(profile, true);
}
updateProfilesStatus();
} catch (IOException e) {
Log.v(TAG, "Can not handle the profile : " + e.getMessage());
}
}}.start();
}
private void registerForAddSipListener() {
((Button) findViewById(R.id.add_remove_account_button))
.setOnClickListener(new android.view.View.OnClickListener() {
public void onClick(View v) {
startSipEditor(null);
}
});
}
private void registerForReceiveCallsCheckBox() {
mButtonSipReceiveCalls = (CheckBoxPreference) findPreference
(BUTTON_SIP_RECEIVE_CALLS);
mButtonSipReceiveCalls.setChecked(
mSipSharedPreferences.isReceivingCallsEnabled());
mButtonSipReceiveCalls.setOnPreferenceClickListener(
new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
final boolean enabled =
((CheckBoxPreference) preference).isChecked();
new Thread(new Runnable() {
public void run() {
handleSipReceiveCallsOption(enabled);
}
}).start();
return true;
}
});
}
private synchronized void handleSipReceiveCallsOption(boolean enabled) {
mSipSharedPreferences.setReceivingCallsEnabled(enabled);
List<SipProfile> sipProfileList =
retrieveSipListFromDirectory(mProfilesDirectory);
for (SipProfile p : sipProfileList) {
String sipUri = p.getUriString();
boolean openFlag = enabled;
// open the profile if it is primary or the receive calls option
// is enabled.
if (!enabled && mSipSharedPreferences.isPrimaryAccount(sipUri)) {
openFlag = true;
}
p = updateAutoRegistrationFlag(p, enabled);
try {
mSipManager.close(sipUri);
if (openFlag) {
mSipManager.open(p);
}
} catch (Exception e) {
Log.e(TAG, "register failed", e);
}
}
updateProfilesStatus();
}
private SipProfile updateAutoRegistrationFlag(
SipProfile p, boolean enabled) {
SipProfile newProfile = new SipProfile.Builder(p)
.setAutoRegistration(enabled)
.build();
try {
deleteProfile(mProfilesDirectory + p.getProfileName());
saveProfile(mProfilesDirectory, newProfile);
} catch (Exception e) {
Log.e(TAG, "updateAutoRegistrationFlag error", e);
}
return newProfile;
}
private void updateProfilesStatus() {
new Thread(new Runnable() {
public void run() {
try {
retrieveSipLists();
} catch (Exception e) {
Log.e(TAG, "isRegistered", e);
}
}
}).start();
}
public static List<SipProfile> retrieveSipListFromDirectory(
String directory) {
List<SipProfile> sipProfileList = Collections.synchronizedList(
new ArrayList<SipProfile>());
File root = new File(directory);
String[] dirs = root.list();
if (dirs == null) return sipProfileList;
for (String dir : dirs) {
File f = new File(
new File(root, dir), SipSettings.PROFILE_OBJ_FILE);
if (!f.exists()) continue;
try {
SipProfile p = SipSettings.deserialize(f);
if (p == null) continue;
if (!dir.equals(p.getProfileName())) continue;
sipProfileList.add(p);
} catch (IOException e) {
Log.e(TAG, "retrieveProfileListFromStorage()", e);
}
}
return sipProfileList;
}
private void retrieveSipLists() {
mSipPreferenceMap = new LinkedHashMap<String, SipPreference>();
mSipProfileList = retrieveSipListFromDirectory(mProfilesDirectory);
processActiveProfilesFromSipService();
Collections.sort(mSipProfileList, new Comparator<SipProfile>() {
public int compare(SipProfile p1, SipProfile p2) {
return p1.getProfileName().compareTo(p2.getProfileName());
}
public boolean equals(SipProfile p) {
// not used
return false;
}
});
mSipListContainer.removeAll();
for (SipProfile p : mSipProfileList) {
addPreferenceFor(p);
}
if (!mSipSharedPreferences.isReceivingCallsEnabled()) return;
for (SipProfile p : mSipProfileList) {
if (mUid == p.getCallingUid()) {
try {
mSipManager.setRegistrationListener(
p.getUriString(), createRegistrationListener());
} catch (SipException e) {
Log.e(TAG, "cannot set registration listener", e);
}
}
}
}
private void processActiveProfilesFromSipService() {
SipProfile[] activeList = mSipManager.getListOfProfiles();
for (SipProfile activeProfile : activeList) {
SipProfile profile = getProfileFromList(activeProfile);
if (profile == null) {
mSipProfileList.add(activeProfile);
} else {
profile.setCallingUid(activeProfile.getCallingUid());
}
}
}
private SipProfile getProfileFromList(SipProfile activeProfile) {
for (SipProfile p : mSipProfileList) {
if (p.getUriString().equals(activeProfile.getUriString())) {
return p;
}
}
return null;
}
private void addPreferenceFor(SipProfile p) {
String status;
Log.v(TAG, "addPreferenceFor profile uri" + p.getUri());
SipPreference pref = new SipPreference(this, p);
mSipPreferenceMap.put(p.getUriString(), pref);
mSipListContainer.addPreference(pref);
pref.setOnPreferenceClickListener(
new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference pref) {
handleProfileClick(((SipPreference) pref).mProfile);
return true;
}
});
}
private void handleProfileClick(final SipProfile profile) {
int uid = profile.getCallingUid();
if (uid == mUid || uid == 0) {
startSipEditor(profile);
return;
}
new AlertDialog.Builder(this)
.setTitle(R.string.alert_dialog_close)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.close_profile,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int w) {
deleteProfile(profile, false);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
}
private void registerProfile(SipProfile profile) {
if (profile != null) {
try {
mSipManager.open(profile, SipManager.ACTION_SIP_INCOMING_CALL,
createRegistrationListener());
} catch (Exception e) {
Log.e(TAG, "register failed", e);
}
}
}
private void unRegisterProfile(SipProfile profile) {
if (profile != null) {
try {
mSipManager.close(profile.getUriString());
} catch (Exception e) {
Log.e(TAG, "unregister failed:" + profile.getUriString(), e);
}
}
}
// TODO: Use the Util class in settings.vpn instead
public static void deleteProfile(String name) {
deleteProfile(new File(name));
}
private static void deleteProfile(File file) {
if (file.isDirectory()) {
for (File child : file.listFiles()) deleteProfile(child);
}
file.delete();
}
void deleteProfile(SipProfile p, boolean removeProfile) {
mSipProfileList.remove(p);
SipPreference pref = mSipPreferenceMap.remove(p.getUriString());
mSipListContainer.removePreference(pref);
if (removeProfile) {
deleteProfile(mProfilesDirectory + p.getProfileName());
}
unRegisterProfile(p);
}
public static void saveProfile(String profilesDir, SipProfile p)
throws IOException {
File f = new File(profilesDir + p.getProfileName());
if (!f.exists()) f.mkdirs();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
new File(f, PROFILE_OBJ_FILE)));
oos.writeObject(p);
oos.close();
}
private void saveProfileToStorage(SipProfile p) throws IOException {
if (mProfile != null) deleteProfile(mProfile, true);
saveProfile(mProfilesDirectory, p);
mSipProfileList.add(p);
addPreferenceFor(p);
}
static SipProfile deserialize(File profileObjectFile) throws IOException {
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
profileObjectFile));
SipProfile p = (SipProfile) ois.readObject();
ois.close();
return p;
} catch (ClassNotFoundException e) {
Log.d(TAG, "deserialize a profile", e);
return null;
}
}
private void startSipEditor(final SipProfile profile) {
mProfile = profile;
Intent intent = new Intent(this, SipEditor.class);
intent.putExtra(KEY_SIP_PROFILE, (Parcelable) profile);
startActivityForResult(intent, REQUEST_ADD_OR_EDIT_SIP_PROFILE);
}
private void showRegistrationMessage(final String profileUri,
final String message) {
runOnUiThread(new Runnable() {
public void run() {
SipPreference pref = mSipPreferenceMap.get(profileUri);
if (pref != null) {
pref.updateSummary(message);
}
}
});
}
private SipRegistrationListener createRegistrationListener() {
return new SipRegistrationListener() {
public void onRegistrationDone(String profileUri, long expiryTime) {
showRegistrationMessage(profileUri, getString(
R.string.registration_status_done));
}
public void onRegistering(String profileUri) {
showRegistrationMessage(profileUri, getString(
R.string.registration_status_registering));
}
public void onRegistrationFailed(String profileUri, int errorCode,
String message) {
switch (errorCode) {
case SipErrorCode.IN_PROGRESS:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_still_trying));
break;
case SipErrorCode.INVALID_CREDENTIALS:
showRegistrationMessage(profileUri, getString(
- R.string.registration_status_failed, message));
+ R.string.registration_status_invalid_credentials));
break;
case SipErrorCode.DATA_CONNECTION_LOST:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_no_data));
break;
case SipErrorCode.CLIENT_ERROR:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_not_running));
break;
default:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_failed_try_later,
message));
}
}
};
}
}
| true | true | private SipRegistrationListener createRegistrationListener() {
return new SipRegistrationListener() {
public void onRegistrationDone(String profileUri, long expiryTime) {
showRegistrationMessage(profileUri, getString(
R.string.registration_status_done));
}
public void onRegistering(String profileUri) {
showRegistrationMessage(profileUri, getString(
R.string.registration_status_registering));
}
public void onRegistrationFailed(String profileUri, int errorCode,
String message) {
switch (errorCode) {
case SipErrorCode.IN_PROGRESS:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_still_trying));
break;
case SipErrorCode.INVALID_CREDENTIALS:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_failed, message));
break;
case SipErrorCode.DATA_CONNECTION_LOST:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_no_data));
break;
case SipErrorCode.CLIENT_ERROR:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_not_running));
break;
default:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_failed_try_later,
message));
}
}
};
}
| private SipRegistrationListener createRegistrationListener() {
return new SipRegistrationListener() {
public void onRegistrationDone(String profileUri, long expiryTime) {
showRegistrationMessage(profileUri, getString(
R.string.registration_status_done));
}
public void onRegistering(String profileUri) {
showRegistrationMessage(profileUri, getString(
R.string.registration_status_registering));
}
public void onRegistrationFailed(String profileUri, int errorCode,
String message) {
switch (errorCode) {
case SipErrorCode.IN_PROGRESS:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_still_trying));
break;
case SipErrorCode.INVALID_CREDENTIALS:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_invalid_credentials));
break;
case SipErrorCode.DATA_CONNECTION_LOST:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_no_data));
break;
case SipErrorCode.CLIENT_ERROR:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_not_running));
break;
default:
showRegistrationMessage(profileUri, getString(
R.string.registration_status_failed_try_later,
message));
}
}
};
}
|
diff --git a/content-tool/tool/src/java/org/sakaiproject/content/tool/FilePickerAction.java b/content-tool/tool/src/java/org/sakaiproject/content/tool/FilePickerAction.java
index 4489ce8c..9b89b9d8 100755
--- a/content-tool/tool/src/java/org/sakaiproject/content/tool/FilePickerAction.java
+++ b/content-tool/tool/src/java/org/sakaiproject/content/tool/FilePickerAction.java
@@ -1,2644 +1,2650 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2005, 2006 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.sakaiproject.content.tool;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.cheftool.Context;
import org.sakaiproject.cheftool.JetspeedRunData;
import org.sakaiproject.cheftool.RunData;
import org.sakaiproject.cheftool.VelocityPortlet;
import org.sakaiproject.cheftool.VelocityPortletPaneledAction;
import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentCollectionEdit;
import org.sakaiproject.content.api.ContentEntity;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.content.api.ContentResourceFilter;
import org.sakaiproject.content.api.FilePickerHelper;
import org.sakaiproject.content.api.InteractionAction;
import org.sakaiproject.content.api.ResourceToolAction;
import org.sakaiproject.content.api.ResourceToolActionPipe;
import org.sakaiproject.content.api.ResourceType;
import org.sakaiproject.content.api.ResourceTypeRegistry;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentTypeImageService;
import org.sakaiproject.content.api.ServiceLevelAction;
import org.sakaiproject.content.api.GroupAwareEntity.AccessMode;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.entity.cover.EntityManager;
import org.sakaiproject.event.api.SessionState;
import org.sakaiproject.event.cover.NotificationService;
import org.sakaiproject.exception.IdInvalidException;
import org.sakaiproject.exception.IdLengthException;
import org.sakaiproject.exception.IdUniquenessException;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InconsistentException;
import org.sakaiproject.exception.OverQuotaException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.exception.ServerOverloadException;
import org.sakaiproject.exception.TypeException;
import org.sakaiproject.site.api.Site;
import org.sakaiproject.site.cover.SiteService;
import org.sakaiproject.time.api.Time;
import org.sakaiproject.time.cover.TimeService;
import org.sakaiproject.tool.api.Tool;
import org.sakaiproject.tool.api.ToolException;
import org.sakaiproject.tool.api.ToolSession;
import org.sakaiproject.tool.cover.SessionManager;
import org.sakaiproject.tool.cover.ToolManager;
import org.sakaiproject.user.api.User;
import org.sakaiproject.util.FileItem;
import org.sakaiproject.util.ParameterParser;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.StringUtil;
import org.sakaiproject.util.Validator;
/**
* The FilePickerAction drives the FilePicker helper.<br />
* This works with the ResourcesTool to show a file picker / attachment editor that can be used by any Sakai tools as a helper.<br />
* If the user ends without a cancel, the original collection of attachments is replaced with the edited list - otherwise it is left unchanged.
*/
public class FilePickerAction extends VelocityPortletPaneledAction
{
/** Resource bundle using current language locale */
private static ResourceLoader rb = new ResourceLoader("helper");
/** Resource bundle using current language locale */
private static ResourceLoader trb = new ResourceLoader("types");
private static final Log logger = LogFactory.getLog(FilePickerAction.class);
protected static final String PREFIX = "filepicker.";
protected static final String MODE_ADD_METADATA = "mode_add_metadata";
protected static final String MODE_ATTACHMENT_CREATE = "mode_attachment_create";
protected static final String MODE_ATTACHMENT_CREATE_INIT = "mode_attachment_create_init";
protected static final String MODE_ATTACHMENT_DONE = "mode_attachment_done";
protected static final String MODE_ATTACHMENT_EDIT_ITEM = "mode_attachment_edit_item";
protected static final String MODE_ATTACHMENT_EDIT_ITEM_INIT = "mode_attachment_edit_item_init";
protected static final String MODE_ATTACHMENT_NEW_ITEM = "mode_attachment_new_item";
protected static final String MODE_ATTACHMENT_NEW_ITEM_INIT = "mode_attachment_new_item_init";
protected static final String MODE_ATTACHMENT_SELECT = "mode_attachment_select";
protected static final String MODE_ATTACHMENT_SELECT_INIT = "mode_attachment_select_init";
protected static final String MODE_HELPER = "mode_helper";
/** The null/empty string */
private static final String NULL_STRING = "";
protected static final String STATE_ADDED_ITEMS = PREFIX + "added_items";
/** The name of the state attribute containing the name of the tool that invoked Resources as attachment helper */
public static final String STATE_ATTACH_TOOL_NAME = PREFIX + "attach_tool_name";
/**
* The name of the state attribute for the maximum number of items to attach. The attribute value will be an Integer,
* usually FilePickerHelper.CARDINALITY_SINGLE or FilePickerHelper.CARDINALITY_MULTIPLE.
*/
protected static final String STATE_ATTACH_CARDINALITY = PREFIX + "attach_cardinality";
protected static final String STATE_ATTACH_INSTRUCTION = PREFIX + "attach_instruction";
protected static final String STATE_ATTACH_LINKS = PREFIX + "attach_links";
protected static final String STATE_ATTACH_TITLE = PREFIX + "attach_title";
protected static final String STATE_ATTACHMENT_FILTER = PREFIX + "attachment_filter";
protected static final String STATE_ATTACHMENT_LIST = PREFIX + "attachment_list";
protected static final String STATE_CONTENT_SERVICE = PREFIX + "content_service";
/** The content type image lookup service in the State. */
protected static final String STATE_CONTENT_TYPE_IMAGE_SERVICE = PREFIX + "content_type_image_service";
protected static final String STATE_DEFAULT_COLLECTION_ID = PREFIX + "default_collection_id";
protected static final String STATE_DEFAULT_COPYRIGHT = PREFIX + "default_copyright";
protected static final String STATE_DEFAULT_RETRACT_TIME = PREFIX + "default_retract_time";
protected static final String STATE_EXPAND_ALL = PREFIX + "expand_all";
protected static final String STATE_EXPAND_ALL_FLAG = PREFIX + "expand_all_flag";
protected static final String STATE_EXPANDED_COLLECTIONS = PREFIX + "expanded_collections";
protected static final String STATE_FILE_UPLOAD_MAX_SIZE = PREFIX + "file_upload_max_size";
protected static final String STATE_FILEPICKER_MODE = PREFIX + "mode";
protected static final String STATE_HELPER_CANCELED_BY_USER = PREFIX + "helper_canceled_by_user";
protected static final String STATE_HELPER_CHANGED = PREFIX + "made_changes";
protected static final String STATE_HOME_COLLECTION_ID = PREFIX + "home_collection_id";
protected static final String STATE_LIST_SELECTIONS = PREFIX + "list_selections";
protected static final String STATE_LIST_VIEW_SORT = PREFIX + "list_view_sort";
protected static final String STATE_NAVIGATION_ROOT = PREFIX + "navigation_root";
protected static final String STATE_NEED_TO_EXPAND_ALL = PREFIX + "need_to_expand_all";
protected static final String STATE_NEW_ATTACHMENT = PREFIX + "new_attachment";
protected static final String STATE_PREVENT_PUBLIC_DISPLAY = PREFIX + "prevent_public_display";
protected static final String STATE_REMOVED_ITEMS = PREFIX + "removed_items";
protected static final String STATE_RESOURCES_TYPE_REGISTRY = PREFIX + "resource_type_registry";
protected static final String STATE_SHOW_ALL_SITES = PREFIX + "show_all_sites";
protected static final String STATE_SHOW_OTHER_SITES = PREFIX + "show_other_sites";
/** The sort by */
private static final String STATE_SORT_BY = PREFIX + "sort_by";
/** The sort ascending or decending */
private static final String STATE_SORT_ASC = PREFIX + "sort_asc";
private static final String TEMPLATE_ATTACH = "content/sakai_filepicker_attach";
private static final String TEMPLATE_SELECT = "content/sakai_filepicker_select";
private static final int MAXIMUM_ATTEMPTS_FOR_UNIQUENESS = ResourcesAction.MAXIMUM_ATTEMPTS_FOR_UNIQUENESS;
/**
* @param portlet
* @param context
* @param data
* @param state
* @return
*/
protected String buildCreateContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
// TODO Auto-generated method stub
return null;
}
/**
* @param portlet
* @param context
* @param data
* @param state
* @return
*/
protected String buildItemTypeContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
// TODO Auto-generated method stub
return null;
}
/**
* @param portlet
* @param context
* @param data
* @param state
* @return
*/
public String buildMainPanelContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
// if we are in edit attachments...
String mode = (String) state.getAttribute(ResourcesAction.STATE_MODE);
ToolSession toolSession = SessionManager.getCurrentToolSession();
String helper_mode = (String) state.getAttribute(STATE_FILEPICKER_MODE);
if (mode == null || helper_mode == null || toolSession.getAttribute(FilePickerHelper.START_HELPER) != null)
{
toolSession.removeAttribute(FilePickerHelper.START_HELPER);
mode = initHelperAction(state, toolSession);
helper_mode = (String) state.getAttribute(STATE_FILEPICKER_MODE);
}
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
if(pipe != null)
{
if(pipe.isActionCanceled())
{
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
}
else if(pipe.isErrorEncountered())
{
String msg = pipe.getErrorMessage();
if(msg != null && ! msg.trim().equals(""))
{
addAlert(state, msg);
}
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
}
else if(pipe.isActionCompleted())
{
finishAction(state, toolSession, pipe);
}
toolSession.removeAttribute(ResourceToolAction.DONE);
}
helper_mode = (String) state.getAttribute(STATE_FILEPICKER_MODE);
if(MODE_ATTACHMENT_SELECT.equals(helper_mode))
{
helper_mode = MODE_ATTACHMENT_SELECT_INIT;
}
else if(MODE_ATTACHMENT_CREATE.equals(helper_mode))
{
helper_mode = MODE_ATTACHMENT_CREATE_INIT;
}
else if(MODE_ATTACHMENT_NEW_ITEM.equals(helper_mode))
{
helper_mode = MODE_ATTACHMENT_NEW_ITEM_INIT;
}
else if(MODE_ATTACHMENT_EDIT_ITEM.equals(helper_mode))
{
helper_mode = MODE_ATTACHMENT_EDIT_ITEM_INIT;
}
String template = null;
if(MODE_ATTACHMENT_SELECT_INIT.equals(helper_mode))
{
template = buildSelectAttachmentContext(portlet, context, data, state);
}
else if(MODE_ADD_METADATA.equals(helper_mode))
{
template = buildAddMetadataContext(portlet, context, data, state);
}
// else if(MODE_ATTACHMENT_CREATE_INIT.equals(helper_mode))
// {
// template = buildCreateContext(portlet, context, data, state);
// }
// else if(MODE_ATTACHMENT_NEW_ITEM_INIT.equals(helper_mode))
// {
// template = buildItemTypeContext(portlet, context, data, state);
// }
// else if(MODE_ATTACHMENT_EDIT_ITEM_INIT.equals(helper_mode))
// {
// template = buildCreateContext(portlet, context, data, state);
// }
return template;
}
/**
* @param portlet
* @param context
* @param data
* @param state
* @return
*/
private String buildAddMetadataContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("tlang",trb);
String template = "content/sakai_resources_cwiz_finish";
ToolSession toolSession = SessionManager.getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
if(pipe.isActionCanceled())
{
// go back to list view
}
else if(pipe.isErrorEncountered())
{
// report the error?
}
else
{
// complete the create wizard
String defaultCopyrightStatus = (String) state.getAttribute(STATE_DEFAULT_COPYRIGHT);
if(defaultCopyrightStatus == null || defaultCopyrightStatus.trim().equals(""))
{
defaultCopyrightStatus = ServerConfigurationService.getString("default.copyright");
state.setAttribute(STATE_DEFAULT_COPYRIGHT, defaultCopyrightStatus);
}
String encoding = data.getRequest().getCharacterEncoding();
Time defaultRetractDate = (Time) state.getAttribute(STATE_DEFAULT_RETRACT_TIME);
if(defaultRetractDate == null)
{
defaultRetractDate = TimeService.newTime();
state.setAttribute(STATE_DEFAULT_RETRACT_TIME, defaultRetractDate);
}
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
ContentEntity collection = pipe.getContentEntity();
String typeId = pipe.getAction().getTypeId();
//List items = newEditItems(collection.getId(), typeId, encoding, defaultCopyrightStatus, preventPublicDisplay.booleanValue(), defaultRetractDate, new Integer(1));
ResourcesItem item = new ResourcesItem("", collection.getId(), typeId, pipe);
item.setContent(pipe.getContent());
item.setContentType(pipe.getMimeType());
context.put("item", item);
state.setAttribute(STATE_NEW_ATTACHMENT, item);
ResourceTypeRegistry registry = (ResourceTypeRegistry) state.getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
if(registry == null)
{
registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
state.setAttribute(STATE_RESOURCES_TYPE_REGISTRY, registry);
}
ResourceType typeDef = registry.getType(typeId);
context.put("type", typeDef);
context.put("title", (new ResourceTypeLabeler()).getLabel(pipe.getAction()));
context.put("instruction", trb.getFormattedMessage("instr.create", new String[]{typeDef.getLabel()}));
context.put("required", trb.getFormattedMessage("instr.require", new String[]{"<span class=\"reqStarInline\">*</span>"}));
// find the ContentHosting service
ContentHostingService contentService = (ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
if(contentService.isAvailabilityEnabled())
{
context.put("availability_is_enabled", Boolean.TRUE);
}
ResourcesAction.copyrightChoicesIntoContext(state, context);
context.put("SITE_ACCESS", AccessMode.SITE.toString());
context.put("GROUP_ACCESS", AccessMode.GROUPED.toString());
context.put("INHERITED_ACCESS", AccessMode.INHERITED.toString());
context.put("PUBLIC_ACCESS", ResourcesAction.PUBLIC_ACCESS);
}
return template;
}
/**
* @param state
* @param toolSession
* @param pipe
*/
protected void finishAction(SessionState state, ToolSession toolSession, ResourceToolActionPipe pipe)
{
ResourceToolAction action = pipe.getAction();
// use ActionType for this
switch(action.getActionType())
{
case CREATE:
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ADD_METADATA);
break;
case NEW_UPLOAD:
List<ContentResource> resources = ResourcesAction.createResources(pipe);
if(resources != null && ! resources.isEmpty())
{
// expand folder
SortedSet<String> expandedCollections = (SortedSet<String>) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
expandedCollections.add(resources.get(0).getContainingCollection().getId());
List<AttachItem> new_items = (List<AttachItem>) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector<AttachItem>();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
for(ContentResource resource : resources)
{
new_items.add(new AttachItem(resource));
}
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
}
toolSession.removeAttribute(ResourceToolAction.ACTION_PIPE);
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
break;
case NEW_FOLDER:
List<ContentCollection> folders = ResourcesAction.createFolders(state, pipe);
toolSession.removeAttribute(ResourceToolAction.ACTION_PIPE);
break;
case REVISE_CONTENT:
ResourcesAction.reviseContent(pipe);
toolSession.removeAttribute(ResourceToolAction.ACTION_PIPE);
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
break;
default:
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
}
}
/**
* @param portlet
* @param context
* @param data
* @param state
* @return
*/
protected String buildSelectAttachmentContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("tlang",rb);
// find the ContentHosting service
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("labeler", new ResourceTypeLabeler());
context.put("ACTION_DELIMITER", ResourceToolAction.ACTION_DELIMITER);
List new_items = (List) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
context.put("attached", new_items);
context.put("last", new Integer(new_items.size() - 1));
Integer max_cardinality = (Integer) state.getAttribute(STATE_ATTACH_CARDINALITY);
if(max_cardinality == null)
{
max_cardinality = FilePickerHelper.CARDINALITY_MULTIPLE;
state.setAttribute(STATE_ATTACH_CARDINALITY, max_cardinality);
}
context.put("max_cardinality", max_cardinality);
if(new_items.size() < max_cardinality.intValue())
{
context.put("can_attach_more", Boolean.TRUE);
}
if(new_items.size() >= max_cardinality.intValue())
{
context.put("disable_attach_links", Boolean.TRUE.toString());
}
if(state.getAttribute(STATE_HELPER_CHANGED) != null)
{
context.put("list_has_changed", Boolean.TRUE.toString());
}
boolean inMyWorkspace = SiteService.isUserSite(ToolManager.getCurrentPlacement().getContext());
// context.put("inMyWorkspace", Boolean.toString(inMyWorkspace));
boolean atHome = false;
// %%STATE_MODE_RESOURCES%%
//boolean dropboxMode = RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES));
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
// make sure the collectionId is set
String collectionId = (String) state.getAttribute(STATE_DEFAULT_COLLECTION_ID);
if(collectionId == null)
{
collectionId = homeCollectionId;
}
context.put ("collectionId", collectionId);
String navRoot = (String) state.getAttribute(STATE_NAVIGATION_ROOT);
// String siteTitle = (String) state.getAttribute (STATE_SITE_TITLE);
if (collectionId.equals(homeCollectionId))
{
atHome = true;
//context.put ("collectionDisplayName", state.getAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME));
}
Comparator userSelectedSort = (Comparator) state.getAttribute(STATE_LIST_VIEW_SORT);
// set the sort values
String sortedBy = (String) state.getAttribute (STATE_SORT_BY);
String sortedAsc = (String) state.getAttribute (STATE_SORT_ASC);
context.put ("currentSortedBy", sortedBy);
context.put ("currentSortAsc", sortedAsc);
context.put("TRUE", Boolean.TRUE.toString());
try
{
try
{
contentService.checkCollection (collectionId);
context.put ("collectionFlag", Boolean.TRUE.toString());
}
catch(IdUnusedException ex)
{
if(logger.isDebugEnabled())
{
logger.debug("ResourcesAction.buildSelectAttachment (static) : IdUnusedException: " + collectionId);
}
try
{
ContentCollectionEdit coll = contentService.addCollection(collectionId);
contentService.commitCollection(coll);
}
catch(IdUsedException inner)
{
// how can this happen??
logger.warn("ResourcesAction.buildSelectAttachment (static) : IdUsedException: " + collectionId);
throw ex;
}
catch(IdInvalidException inner)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : IdInvalidException: " + collectionId);
// what now?
throw ex;
}
catch(InconsistentException inner)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : InconsistentException: " + collectionId);
// what now?
throw ex;
}
}
catch(TypeException ex)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : TypeException.");
throw ex;
}
catch(PermissionException ex)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : PermissionException.");
throw ex;
}
SortedSet<String> expandedCollections = (SortedSet<String>) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(expandedCollections == null)
{
expandedCollections = new TreeSet<String>();
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
expandedCollections.add(collectionId);
ResourceTypeRegistry registry = (ResourceTypeRegistry) state.getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
if(registry == null)
{
registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
state.setAttribute(STATE_RESOURCES_TYPE_REGISTRY, registry);
}
boolean expandAll = Boolean.TRUE.toString().equals(state.getAttribute(STATE_NEED_TO_EXPAND_ALL));
//state.removeAttribute(STATE_PASTE_ALLOWED_FLAG);
List<ListItem> this_site = new Vector<ListItem>();
if(contentService.isInDropbox(collectionId))
{
User[] submitters = (User[]) state.getAttribute(FilePickerHelper.FILE_PICKER_SHOW_DROPBOXES);
if(submitters != null)
{
String dropboxId = contentService.getDropboxCollection();
if(dropboxId == null)
{
contentService.createDropboxCollection();
dropboxId = contentService.getDropboxCollection();
}
if(dropboxId == null)
{
// do nothing
}
else if(contentService.isDropboxMaintainer())
{
for(int i = 0; i < submitters.length; i++)
{
User submitter = submitters[i];
String dbId = dropboxId + StringUtil.trimToZero(submitter.getId()) + "/";
try
{
ContentCollection db = contentService.getCollection(dbId);
expandedCollections.add(dbId);
ListItem item = ListItem.getListItem(db, (ListItem) null, registry, expandAll, expandedCollections, (List<String>) null, (List<String>) null, 0, userSelectedSort);
List<ListItem> items = item.convert2list();
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACHMENT_FILTER);
if(filter != null)
{
items = filterList(items, filter);
}
- this_site.addAll(item.convert2list());
+ this_site.addAll(items);
// List dbox = getListView(dbId, highlightedItems, (ResourcesBrowseItem) null, false, state);
// getBrowseItems(dbId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, false, state);
// if(dbox != null && dbox.size() > 0)
// {
// ResourcesBrowseItem root = (ResourcesBrowseItem) dbox.remove(0);
// // context.put("site", root);
// root.setName(submitter.getDisplayName() + " " + rb.getString("gen.drop"));
// root.addMembers(dbox);
// this_site.add(root);
// }
}
catch(IdUnusedException e)
{
// ignore a user's dropbox if it's not defined
}
}
}
else
{
try
{
ContentCollection db = contentService.getCollection(dropboxId);
expandedCollections.add(dropboxId);
ListItem item = ListItem.getListItem(db, null, registry, expandAll, expandedCollections, null, null, 0, null);
this_site.addAll(item.convert2list());
// List dbox = getListView(dropboxId, highlightedItems, (ResourcesBrowseItem) null, false, state);
// // List dbox = getBrowseItems(dropboxId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, false, state);
// if(dbox != null && dbox.size() > 0)
// {
// ResourcesBrowseItem root = (ResourcesBrowseItem) dbox.remove(0);
// // context.put("site", root);
// root.setName(ContentHostingService.getDropboxDisplayName());
// root.addMembers(dbox);
// this_site.add(root);
// }
}
catch(IdUnusedException e)
{
// if an id is unused, ignore it
}
}
}
}
else
{
ContentCollection collection = contentService.getCollection(collectionId);
ListItem item = ListItem.getListItem(collection, null, registry, expandAll, expandedCollections, null, null, 0, null);
- this_site.addAll(item.convert2list());
+ List<ListItem> items = item.convert2list();
+ ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACHMENT_FILTER);
+ if(filter != null)
+ {
+ items = filterList(items, filter);
+ }
+ this_site.addAll(items);
}
// List members = getListView(collectionId, highlightedItems, (ResourcesBrowseItem) null, navRoot.equals(homeCollectionId), state);
// // List members = getBrowseItems(collectionId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, navRoot.equals(homeCollectionId), state);
// if(members != null && members.size() > 0)
// {
// ResourcesBrowseItem root = (ResourcesBrowseItem) members.remove(0);
// if(atHome && dropboxMode)
// {
// root.setName(siteTitle + " " + rb.getString("gen.drop"));
// }
// else if(atHome)
// {
// root.setName(siteTitle + " " + rb.getString("gen.reso"));
// }
// context.put("site", root);
// root.addMembers(members);
// this_site.add(root);
// }
context.put ("this_site", this_site);
List other_sites = new Vector();
boolean show_all_sites = false;
String allowed_to_see_other_sites = (String) state.getAttribute(STATE_SHOW_ALL_SITES);
String show_other_sites = (String) state.getAttribute(STATE_SHOW_OTHER_SITES);
context.put("show_other_sites", show_other_sites);
if(Boolean.TRUE.toString().equals(allowed_to_see_other_sites))
{
context.put("allowed_to_see_other_sites", Boolean.TRUE.toString());
show_all_sites = Boolean.TRUE.toString().equals(show_other_sites);
}
if(show_all_sites)
{
// List messages = prepPage(state);
// context.put("other_sites", messages);
//
// if (state.getAttribute(STATE_NUM_MESSAGES) != null)
// {
// context.put("allMsgNumber", state.getAttribute(STATE_NUM_MESSAGES).toString());
// context.put("allMsgNumberInt", state.getAttribute(STATE_NUM_MESSAGES));
// }
//
// context.put("pagesize", ((Integer) state.getAttribute(STATE_PAGESIZE)).toString());
//
// // find the position of the message that is the top first on the page
// if ((state.getAttribute(STATE_TOP_MESSAGE_INDEX) != null) && (state.getAttribute(STATE_PAGESIZE) != null))
// {
// int topMsgPos = ((Integer)state.getAttribute(STATE_TOP_MESSAGE_INDEX)).intValue() + 1;
// context.put("topMsgPos", Integer.toString(topMsgPos));
// int btmMsgPos = topMsgPos + ((Integer)state.getAttribute(STATE_PAGESIZE)).intValue() - 1;
// if (state.getAttribute(STATE_NUM_MESSAGES) != null)
// {
// int allMsgNumber = ((Integer)state.getAttribute(STATE_NUM_MESSAGES)).intValue();
// if (btmMsgPos > allMsgNumber)
// btmMsgPos = allMsgNumber;
// }
// context.put("btmMsgPos", Integer.toString(btmMsgPos));
// }
//
// boolean goPPButton = state.getAttribute(STATE_PREV_PAGE_EXISTS) != null;
// context.put("goPPButton", Boolean.toString(goPPButton));
// boolean goNPButton = state.getAttribute(STATE_NEXT_PAGE_EXISTS) != null;
// context.put("goNPButton", Boolean.toString(goNPButton));
//
// /*
// boolean goFPButton = state.getAttribute(STATE_FIRST_PAGE_EXISTS) != null;
// context.put("goFPButton", Boolean.toString(goFPButton));
// boolean goLPButton = state.getAttribute(STATE_LAST_PAGE_EXISTS) != null;
// context.put("goLPButton", Boolean.toString(goLPButton));
// */
//
// context.put("pagesize", state.getAttribute(STATE_PAGESIZE));
// // context.put("pagesizes", PAGESIZES);
}
// context.put ("root", root);
context.put("expandedCollections", expandedCollections);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfind"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(TypeException e)
{
// logger.warn(this + "TypeException.");
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(PermissionException e)
{
addAlert(state, rb.getString("notpermis1"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
context.put("homeCollection", (String) state.getAttribute (STATE_HOME_COLLECTION_ID));
// context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE));
context.put ("resourceProperties", contentService.newResourceProperties ());
try
{
// TODO: why 'site' here?
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
context.put("siteTitle", site.getTitle());
}
catch (IdUnusedException e)
{
// logger.warn(this + e.toString());
}
context.put("expandallflag", state.getAttribute(STATE_EXPAND_ALL_FLAG));
state.removeAttribute(STATE_NEED_TO_EXPAND_ALL);
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
// justDelivered(state);
// pick the template based on whether client wants links or copies
String template = TEMPLATE_SELECT;
if(state.getAttribute(STATE_ATTACH_LINKS) == null)
{
// user wants copies in hidden attachments area
template = TEMPLATE_ATTACH;
}
return template;
//return TEMPLATE_SELECT;
}
/**
* @param filter
* @param name
* @return
*/
private List<ListItem> filterList(List<ListItem> items, ContentResourceFilter filter)
{
List<ListItem> rv = new Vector<ListItem>();
for(ListItem item : items)
{
ContentEntity entity = item.getEntity();
if(entity.isCollection() || filter.allowSelect((ContentResource) entity))
{
rv.add(item);
}
}
return rv;
}
/**
* @param state
*/
protected void cleanup(SessionState state)
{
Iterator<String> attributeNameIt = state.getAttributeNames().iterator();
while(attributeNameIt.hasNext())
{
String attributeName = attributeNameIt.next();
if(attributeName.startsWith(PREFIX))
{
state.removeAttribute(attributeName);
}
}
ToolSession toolSession = SessionManager.getCurrentToolSession();
if (toolSession != null)
{
toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_MAX_ATTACHMENTS);
toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_RESOURCE_FILTER);
toolSession.removeAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID);
}
} // cleanup
/**
* @param state
* @param toolSession
* @return
*/
protected String initHelperAction(SessionState state, ToolSession toolSession)
{
toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
ContentHostingService contentService = (ContentHostingService) ComponentManager.get("org.sakaiproject.content.api.ContentHostingService");
state.setAttribute (STATE_CONTENT_SERVICE, contentService);
state.setAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE, ComponentManager.get("org.sakaiproject.content.api.ContentTypeImageService"));
state.setAttribute(STATE_RESOURCES_TYPE_REGISTRY, ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry"));
// start with a copy of the original attachment list
List attachments = (List) toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
if (attachments != null)
{
attachments = EntityManager.newReferenceList(attachments);
}
else
{
attachments = EntityManager.newReferenceList();
}
state.setAttribute(STATE_ATTACHMENT_LIST, attachments);
Object attach_links = state.getAttribute(FilePickerHelper.FILE_PICKER_ATTACH_LINKS);
if(attach_links == null)
{
state.removeAttribute(STATE_ATTACH_LINKS);
}
else
{
state.setAttribute(STATE_ATTACH_LINKS, Boolean.TRUE.toString());
}
List<AttachItem> new_items = new Vector<AttachItem>();
Iterator attachmentIt = attachments.iterator();
while(attachmentIt.hasNext())
{
Reference ref = (Reference) attachmentIt.next();
try
{
ContentResource res = (ContentResource) ref.getEntity();
ResourceProperties props = null;
String accessUrl = null;
if(res == null)
{
props = contentService.getProperties(ref.getId());
accessUrl = contentService.getUrl(ref.getId());
}
else
{
props = res.getProperties();
accessUrl = res.getUrl();
}
String displayName = props.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
String containerId = contentService.getContainingCollectionId (res.getId());
AttachItem item = new AttachItem(ref.getId(), displayName, containerId, accessUrl);
item.setContentType(res.getContentType());
item.setResourceType(res.getResourceType());
new_items.add(item);
}
catch (PermissionException e)
{
logger.info("PermissionException -- User has permission to revise item but lacks permission to view attachment: " + ref.getId());
}
catch (IdUnusedException e)
{
logger.info("IdUnusedException -- An attachment has been deleted: " + ref.getId());
}
}
state.setAttribute(STATE_ADDED_ITEMS, new_items);
initMessage(toolSession, state);
state.setAttribute(STATE_ATTACHMENT_FILTER, toolSession.getAttribute(FilePickerHelper.FILE_PICKER_RESOURCE_FILTER));
String defaultCollectionId = (String) toolSession.getAttribute(FilePickerHelper.DEFAULT_COLLECTION_ID);
if(defaultCollectionId == null)
{
defaultCollectionId = contentService.getSiteCollection(ToolManager.getCurrentPlacement().getContext());
}
state.setAttribute(STATE_DEFAULT_COLLECTION_ID, defaultCollectionId);
state.setAttribute(STATE_MODE, MODE_HELPER);
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT);
// TODO: Should check sakai.properties
state.setAttribute(STATE_SHOW_ALL_SITES, Boolean.TRUE.toString());
// state attribute ResourcesAction.STATE_ATTACH_TOOL_NAME should be set with a string to indicate name of tool
String toolName = ToolManager.getCurrentPlacement().getTitle();
state.setAttribute(STATE_ATTACH_TOOL_NAME, toolName);
Object max_cardinality = toolSession.getAttribute(FilePickerHelper.FILE_PICKER_MAX_ATTACHMENTS);
if (max_cardinality != null)
{
state.setAttribute(STATE_ATTACH_CARDINALITY, max_cardinality);
}
if (state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE) == null)
{
state.setAttribute(STATE_FILE_UPLOAD_MAX_SIZE, ServerConfigurationService.getString("content.upload.max", "1"));
}
return MODE_HELPER;
}
/**
* @param toolSession
* @param state
*/
protected void initMessage(ToolSession toolSession, SessionState state)
{
String message = (String) toolSession.getAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT);
toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_TITLE_TEXT);
if (message == null)
{
message = rb.getString(FilePickerHelper.FILE_PICKER_TITLE_TEXT);
}
state.setAttribute(STATE_ATTACH_TITLE, message);
message = (String) toolSession.getAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT);
toolSession.removeAttribute(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT);
if (message == null)
{
message = rb.getString(FilePickerHelper.FILE_PICKER_INSTRUCTION_TEXT);
}
state.setAttribute(STATE_ATTACH_INSTRUCTION, message);
}
/**
* @param data
*/
public void doAttachitem(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
//state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
String itemId = params.getString("itemId");
Object attach_links = state.getAttribute(FilePickerHelper.FILE_PICKER_ATTACH_LINKS);
if(attach_links == null)
{
attachItem(itemId, state);
}
else
{
attachLink(itemId, state);
}
List<AttachItem> removed = (List<AttachItem>) state.getAttribute(STATE_REMOVED_ITEMS);
if(removed == null)
{
removed = new Vector<AttachItem>();
state.setAttribute(STATE_REMOVED_ITEMS, removed);
}
Iterator<AttachItem> removeIt = removed.iterator();
while(removeIt.hasNext())
{
AttachItem item = removeIt.next();
if(item.getId().equals(itemId))
{
removeIt.remove();
break;
}
}
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
} // doAttachitem
/**
* @param data
*/
public void doAttachupload(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String max_file_size_mb = (String) state.getAttribute(STATE_FILE_UPLOAD_MAX_SIZE);
int max_bytes = 1024 * 1024;
try
{
max_bytes = Integer.parseInt(max_file_size_mb) * 1024 * 1024;
}
catch(Exception e)
{
// if unable to parse an integer from the value
// in the properties file, use 1 MB as a default
max_file_size_mb = "1";
max_bytes = 1024 * 1024;
}
FileItem fileitem = null;
try
{
fileitem = params.getFileItem("upload");
}
catch(Exception e)
{
}
if(fileitem == null)
{
// "The user submitted a file to upload but it was too big!"
addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else if (fileitem.getFileName() == null || fileitem.getFileName().length() == 0)
{
addAlert(state, rb.getString("choosefile7"));
}
else if (fileitem.getFileName().length() > 0)
{
String filename = Validator.getFileName(fileitem.getFileName());
byte[] bytes = fileitem.get();
String contentType = fileitem.getContentType();
if(bytes.length >= max_bytes)
{
addAlert(state, rb.getString("size") + " " + max_file_size_mb + "MB " + rb.getString("exceeded2"));
}
else if(bytes.length > 0)
{
// we just want the file name part - strip off any drive and path stuff
String name = Validator.getFileName(filename);
String resourceId = Validator.escapeResourceName(name);
ContentHostingService contentService = (ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// make a set of properties to add for the new resource
ResourcePropertiesEdit props = contentService.newResourceProperties();
props.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);
props.addProperty(ResourceProperties.PROP_DESCRIPTION, filename);
// make an attachment resource for this URL
try
{
String siteId = ToolManager.getCurrentPlacement().getContext();
String toolName = (String) state.getAttribute(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = ToolManager.getCurrentPlacement().getTitle();
state.setAttribute(STATE_ATTACH_TOOL_NAME, toolName);
}
ContentResource attachment = contentService.addAttachmentResource(resourceId, siteId, toolName, contentType, bytes, props);
List<AttachItem> new_items = (List<AttachItem>) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector<AttachItem>();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
String containerId = contentService.getContainingCollectionId (attachment.getId());
String accessUrl = attachment.getUrl();
AttachItem item = new AttachItem(attachment.getId(), filename, containerId, accessUrl);
item.setResourceType(ResourceType.TYPE_UPLOAD);
item.setContentType(contentType);
new_items.add(item);
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch(IdInvalidException ignore)
{
// other exceptions should be caught earlier
}
catch(InconsistentException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUsedException ignore)
{
// other exceptions should be caught earlier
}
catch(RuntimeException e)
{
logger.debug("ResourcesAction.doAttachupload ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
}
else
{
addAlert(state, rb.getString("choosefile7"));
}
}
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
} // doAttachupload
/**
* @param data
*/
public void doAttachurl(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
String url = params.getCleanString("url");
ContentHostingService contentService = (ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
ResourcePropertiesEdit resourceProperties = contentService.newResourceProperties ();
resourceProperties.addProperty (ResourceProperties.PROP_DISPLAY_NAME, url);
resourceProperties.addProperty (ResourceProperties.PROP_DESCRIPTION, url);
resourceProperties.addProperty(ResourceProperties.PROP_IS_COLLECTION, Boolean.FALSE.toString());
try
{
url = validateURL(url);
byte[] newUrl = url.getBytes();
String newResourceId = Validator.escapeResourceName(url);
String siteId = ToolManager.getCurrentPlacement().getContext();
String toolName = (String) (String) state.getAttribute(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = ToolManager.getCurrentPlacement().getTitle();
state.setAttribute(STATE_ATTACH_TOOL_NAME, toolName);
}
ContentResource attachment = contentService.addAttachmentResource(newResourceId, siteId, toolName, ResourceProperties.TYPE_URL, newUrl, resourceProperties);
List<AttachItem> new_items = (List<AttachItem>) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
String containerId = contentService.getContainingCollectionId (attachment.getId());
String accessUrl = attachment.getUrl();
AttachItem item = new AttachItem(attachment.getId(), url, containerId, accessUrl);
item.setResourceType(ResourceType.TYPE_URL);
item.setContentType(ResourceProperties.TYPE_URL);
new_items.add(item);
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
}
catch(MalformedURLException e)
{
// invalid url
addAlert(state, rb.getString("validurl") + " \"" + url + "\" " + rb.getString("invalid"));
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch(IdInvalidException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUsedException ignore)
{
// other exceptions should be caught earlier
}
catch(InconsistentException ignore)
{
// other exceptions should be caught earlier
}
catch(RuntimeException e)
{
logger.debug("ResourcesAction.doAttachurl ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
} // doAttachurl
/**
* doCancel to return to the previous state
*/
public void doCancel ( RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//cleanup(state);
state.setAttribute(STATE_HELPER_CANCELED_BY_USER, Boolean.TRUE.toString());
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_DONE);
} // doCancel
public void doRemoveitem(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
//state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
String itemId = params.getString("itemId");
List<AttachItem> new_items = (List<AttachItem>) state.getAttribute(STATE_ADDED_ITEMS);
AttachItem item = null;
boolean found = false;
Iterator<AttachItem> it = new_items.iterator();
while(!found && it.hasNext())
{
item = it.next();
if(item.getId().equals(itemId))
{
found = true;
}
}
if(found && item != null)
{
new_items.remove(item);
List<AttachItem> removed = (List<AttachItem>) state.getAttribute(STATE_REMOVED_ITEMS);
if(removed == null)
{
removed = new Vector<AttachItem>();
state.setAttribute(STATE_REMOVED_ITEMS, removed);
}
removed.add(item);
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
}
} // doRemoveitem
public void doAddattachments(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
ParameterParser params = data.getParameters ();
ContentHostingService contentService = (ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// // cancel copy if there is one in progress
// if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_COPY_FLAG)))
// {
// initCopyContext(state);
// }
//
// // cancel move if there is one in progress
// if(! Boolean.FALSE.toString().equals(state.getAttribute (STATE_MOVE_FLAG)))
// {
// initMoveContext(state);
// }
// state.setAttribute(STATE_LIST_SELECTIONS, new TreeSet());
List<AttachItem> new_items = (List<AttachItem>) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector<AttachItem>();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
List<AttachItem> removed = (List<AttachItem>) state.getAttribute(STATE_REMOVED_ITEMS);
if(removed == null)
{
removed = new Vector<AttachItem>();
state.setAttribute(STATE_REMOVED_ITEMS, removed);
}
Iterator<AttachItem> removeIt = removed.iterator();
while(removeIt.hasNext())
{
AttachItem item = removeIt.next();
try
{
if(contentService.isAttachmentResource(item.getId()))
{
ContentResourceEdit edit = contentService.editResource(item.getId());
contentService.removeResource(edit);
ContentCollectionEdit coll = contentService.editCollection(item.getCollectionId());
contentService.removeCollection(coll);
}
}
catch(Exception ignore)
{
// log failure
}
}
state.removeAttribute(STATE_REMOVED_ITEMS);
// add to the attachments vector
List<Reference> attachments = (List<Reference>) state.getAttribute(STATE_ATTACHMENT_LIST);
if(attachments == null)
{
attachments = EntityManager.newReferenceList();
state.setAttribute(STATE_ATTACHMENT_LIST, attachments);
}
attachments.clear();
Iterator<AttachItem> it = new_items.iterator();
while(it.hasNext())
{
AttachItem item = it.next();
try
{
Reference ref = EntityManager.newReference(contentService.getReference(item.getId()));
attachments.add(ref);
}
catch(Exception e)
{
logger.warn("doAddattachments " + e);
}
}
// cleanupState(state);
// end up in main mode
// resetCurrentMode(state);
String field = null;
// if there is at least one attachment
if (attachments.size() > 0)
{
//check -- jim
state.setAttribute(AttachmentAction.STATE_HAS_ATTACHMENT_BEFORE, Boolean.TRUE);
}
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_DONE);
// if(field != null)
// {
// int index = 0;
// String fieldname = field;
// Matcher matcher = INDEXED_FORM_FIELD_PATTERN.matcher(field.trim());
// if(matcher.matches())
// {
// fieldname = matcher.group(0);
// index = Integer.parseInt(matcher.group(1));
// }
//
// // we are trying to attach a link to a form field and there is at least one attachment
// if(new_items == null)
// {
// new_items = (List) current_stack_frame.get(ResourcesAction.STATE_HELPER_NEW_ITEMS);
// if(new_items == null)
// {
// new_items = (List) state.getAttribute(ResourcesAction.STATE_HELPER_NEW_ITEMS);
// }
// }
// ResourcesEditItem edit_item = null;
// List edit_items = (List) current_stack_frame.get(ResourcesAction.STATE_STACK_CREATE_ITEMS);
// if(edit_items == null)
// {
// edit_item = (ResourcesEditItem) current_stack_frame.get(ResourcesAction.STATE_STACK_EDIT_ITEM);
// }
// else
// {
// edit_item = (ResourcesEditItem) edit_items.get(0);
// }
// if(edit_item != null)
// {
// Reference ref = (Reference) attachments.get(0);
// edit_item.setPropertyValue(fieldname, index, ref);
// }
// }
}
/**
* @param itemId
* @param state
*/
public void attachItem(String itemId, SessionState state)
{
ContentHostingService contentService = (ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
List<AttachItem> new_items = (List<AttachItem>) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector<AttachItem>();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
boolean found = false;
Iterator<AttachItem> it = new_items.iterator();
while(!found && it.hasNext())
{
AttachItem item = it.next();
if(item.getId().equals(itemId))
{
found = true;
}
}
if(!found)
{
try
{
ContentResource res = contentService.getResource(itemId);
ResourceProperties props = res.getProperties();
ResourcePropertiesEdit newprops = contentService.newResourceProperties();
newprops.set(props);
byte[] bytes = res.getContent();
String contentType = res.getContentType();
String filename = Validator.getFileName(itemId);
String resourceId = Validator.escapeResourceName(filename);
String siteId = ToolManager.getCurrentPlacement().getContext();
String toolName = (String) state.getAttribute(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = ToolManager.getCurrentPlacement().getTitle();
}
ContentResource attachment = contentService.addAttachmentResource(resourceId, siteId, toolName, contentType, bytes, props);
String displayName = newprops.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
String containerId = contentService.getContainingCollectionId (attachment.getId());
String accessUrl = attachment.getUrl();
AttachItem item = new AttachItem(attachment.getId(), displayName, containerId, accessUrl);
item.setContentType(contentType);
item.setResourceType(res.getResourceType());
new_items.add(item);
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(OverQuotaException e)
{
addAlert(state, rb.getString("overquota"));
}
catch(ServerOverloadException e)
{
addAlert(state, rb.getString("failed"));
}
catch(IdInvalidException ignore)
{
// other exceptions should be caught earlier
}
catch(TypeException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUnusedException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUsedException ignore)
{
// other exceptions should be caught earlier
}
catch(InconsistentException ignore)
{
// other exceptions should be caught earlier
}
catch(RuntimeException e)
{
logger.debug("ResourcesAction.attachItem ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
}
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
/**
* @param itemId
* @param state
*/
public void attachLink(String itemId, SessionState state)
{
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
List<AttachItem> new_items = (List<AttachItem>) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector<AttachItem>();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
Integer max_cardinality = (Integer) state.getAttribute(STATE_ATTACH_CARDINALITY);
if(max_cardinality == null)
{
max_cardinality = FilePickerHelper.CARDINALITY_MULTIPLE;
state.setAttribute(STATE_ATTACH_CARDINALITY, max_cardinality);
}
boolean found = false;
Iterator<AttachItem> it = new_items.iterator();
while(!found && it.hasNext())
{
AttachItem item = it.next();
if(item.getId().equals(itemId))
{
found = true;
}
}
if(!found)
{
try
{
String toolName = (String) state.getAttribute(STATE_ATTACH_TOOL_NAME);
if(toolName == null)
{
toolName = ToolManager.getCurrentPlacement().getTitle();
state.setAttribute(STATE_ATTACH_TOOL_NAME, toolName);
}
ContentResource res = contentService.getResource(itemId);
ResourceProperties props = res.getProperties();
String displayName = props.getPropertyFormatted(ResourceProperties.PROP_DISPLAY_NAME);
String containerId = contentService.getContainingCollectionId (itemId);
String accessUrl = res.getUrl();
AttachItem item = new AttachItem(itemId, displayName, containerId, accessUrl);
item.setContentType(res.getContentType());
item.setResourceType(res.getResourceType());
new_items.add(item);
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
}
catch (PermissionException e)
{
addAlert(state, rb.getString("notpermis4"));
}
catch(TypeException ignore)
{
// other exceptions should be caught earlier
}
catch(IdUnusedException ignore)
{
// other exceptions should be caught earlier
}
catch(RuntimeException e)
{
logger.debug("ResourcesAction.attachItem ***** Unknown Exception ***** " + e.getMessage());
addAlert(state, rb.getString("failed"));
}
}
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
/**
* Allow extension classes to control which build method gets called for this pannel
* @param panel
* @return
*/
protected String panelMethodName(String panel)
{
// we are always calling buildMainPanelContext
return "buildMainPanelContext";
}
/* (non-Javadoc)
* @see org.sakaiproject.cheftool.VelocityPortletPaneledAction#toolModeDispatch(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void toolModeDispatch(String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
throws ToolException
{
SessionState state = getState(req);
if (MODE_ATTACHMENT_DONE.equals(state.getAttribute(STATE_FILEPICKER_MODE)))
{
ToolSession toolSession = SessionManager.getCurrentToolSession();
if (state.getAttribute(STATE_HELPER_CANCELED_BY_USER) == null)
{
// not canceled, so populate the original list with the results
List attachments = (List) state.getAttribute(STATE_ATTACHMENT_LIST);
if (attachments != null)
{
// get the original list
Collection original = (Collection) toolSession.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
if(original == null)
{
original = EntityManager.newReferenceList();
toolSession.setAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS, original);
}
// replace its contents with the edited attachments
original.clear();
original.addAll(attachments);
}
// otherwise the original list remains unchanged
else if (state.getAttribute(ResourcesAction.STATE_EDIT_ID) == null)
{
toolSession.setAttribute(FilePickerHelper.FILE_PICKER_CANCEL, Boolean.TRUE.toString());
}
}
else
{
toolSession.setAttribute(FilePickerHelper.FILE_PICKER_CANCEL, Boolean.TRUE.toString());
}
cleanup(state);
Tool tool = ToolManager.getCurrentTool();
String url = (String) SessionManager.getCurrentToolSession().getAttribute(tool.getId() + Tool.HELPER_DONE_URL);
SessionManager.getCurrentToolSession().removeAttribute(tool.getId() + Tool.HELPER_DONE_URL);
try
{
res.sendRedirect(url);
}
catch (IOException e)
{
logger.warn("IOException: ", e);
}
return;
}
else if(sendToHelper(req, res, req.getPathInfo()))
{
return;
}
else
{
super.toolModeDispatch(methodBase, methodExt, req, res);
}
}
/**
* @param data
*/
public void doCompleteCreateWizard(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// find the ContentHosting service
ContentHostingService contentService = (ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
ResourcesItem item = (ResourcesItem) state.getAttribute(STATE_NEW_ATTACHMENT);
// get the parameter-parser
ParameterParser params = data.getParameters();
String user_action = params.getString("user_action");
String displayName = null;
ToolSession toolSession = SessionManager.getCurrentToolSession();
ResourceToolActionPipe pipe = (ResourceToolActionPipe) toolSession.getAttribute(ResourceToolAction.ACTION_PIPE);
if(user_action == null)
{
}
else if(user_action.equals("save"))
{
String collectionId = pipe.getContentEntity().getId();
try
{
// title
displayName = params.getString("name");
String basename = displayName.trim();
String extension = "";
if(displayName.contains("."))
{
String[] parts = displayName.split("\\.");
basename = parts[0];
if(parts.length > 1)
{
extension = parts[parts.length - 1];
}
for(int i = 1; i < parts.length - 1; i++)
{
basename += "." + parts[i];
}
}
// create resource
ContentResourceEdit resource = contentService.addResource(collectionId, basename, extension, MAXIMUM_ATTEMPTS_FOR_UNIQUENESS);
String resourceType = null;
if(pipe != null)
{
ResourceToolAction action = pipe.getAction();
if(action == null)
{
}
else
{
if(action instanceof InteractionAction)
{
InteractionAction iAction = (InteractionAction) action;
iAction.finalizeAction(EntityManager.newReference(resource.getReference()), pipe.getInitializationId());
}
resourceType = action.getTypeId();
}
}
resource.setResourceType(resourceType);
byte[] content = pipe.getRevisedContent();
if(content == null)
{
InputStream stream = pipe.getRevisedContentStream();
if(stream == null)
{
logger.warn("pipe with null content and null stream: " + pipe.getFileName());
}
else
{
resource.setContent(stream);
}
}
else
{
resource.setContent(content);
}
resource.setContentType(pipe.getRevisedMimeType());
ResourcePropertiesEdit resourceProperties = resource.getPropertiesEdit();
resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, displayName);
Map values = pipe.getRevisedResourceProperties();
Iterator valueIt = values.keySet().iterator();
while(valueIt.hasNext())
{
String pname = (String) valueIt.next();
String pvalue = (String) values.get(pname);
resourceProperties.addProperty(pname, pvalue);
}
// description
String description = params.getString("description");
resourceProperties.addProperty(ResourceProperties.PROP_DESCRIPTION, description);
// rights
String copyright = params.getString("copyright");
String newcopyright = params.getString("newcopyright");
boolean copyrightAlert = params.getBoolean("copyrightAlert");
if(copyright == null || copyright.trim().length() == 0)
{
resourceProperties.removeProperty(ResourceProperties.PROP_COPYRIGHT_CHOICE);
}
else
{
resourceProperties.addProperty (ResourceProperties.PROP_COPYRIGHT_CHOICE, copyright);
}
if(newcopyright == null || newcopyright.trim().length() == 0)
{
resourceProperties.removeProperty(ResourceProperties.PROP_COPYRIGHT);
}
else
{
resourceProperties.addProperty (ResourceProperties.PROP_COPYRIGHT, newcopyright);
}
if (copyrightAlert)
{
resourceProperties.addProperty (ResourceProperties.PROP_COPYRIGHT_ALERT, Boolean.TRUE.toString());
}
else
{
resourceProperties.removeProperty (ResourceProperties.PROP_COPYRIGHT_ALERT);
}
// availability
boolean hidden = params.getBoolean("hidden");
boolean use_start_date = params.getBoolean("use_start_date");
boolean use_end_date = params.getBoolean("use_end_date");
Time releaseDate = null;
Time retractDate = null;
if(use_start_date)
{
int begin_year = params.getInt("release_year");
int begin_month = params.getInt("release_month");
int begin_day = params.getInt("release_day");
int begin_hour = params.getInt("release_hour");
int begin_min = params.getInt("release_min");
String release_ampm = params.getString("release_ampm");
if("pm".equals(release_ampm))
{
begin_hour += 12;
}
else if(begin_hour == 12)
{
begin_hour = 0;
}
releaseDate = TimeService.newTimeLocal(begin_year, begin_month, begin_day, begin_hour, begin_min, 0, 0);
}
if(use_end_date)
{
int end_year = params.getInt("retract_year");
int end_month = params.getInt("retract_month");
int end_day = params.getInt("retract_day");
int end_hour = params.getInt("retract_hour");
int end_min = params.getInt("retract_min");
String retract_ampm = params.getString("retract_ampm");
if("pm".equals(retract_ampm))
{
end_hour += 12;
}
else if(end_hour == 12)
{
end_hour = 0;
}
retractDate = TimeService.newTimeLocal(end_year, end_month, end_day, end_hour, end_min, 0, 0);
}
resource.setAvailability(hidden, releaseDate, retractDate);
// access
Boolean preventPublicDisplay = (Boolean) state.getAttribute(STATE_PREVENT_PUBLIC_DISPLAY);
if(preventPublicDisplay == null)
{
preventPublicDisplay = Boolean.FALSE;
state.setAttribute(STATE_PREVENT_PUBLIC_DISPLAY, preventPublicDisplay);
}
String access_mode = params.getString("access_mode");
SortedSet groups = new TreeSet();
if(access_mode == null || AccessMode.GROUPED.toString().equals(access_mode))
{
// we inherit more than one group and must check whether group access changes at this item
String[] access_groups = params.getStrings("access_groups");
// SortedSet new_groups = new TreeSet();
// if(access_groups != null)
// {
// new_groups.addAll(Arrays.asList(access_groups));
// }
// new_groups = item.convertToRefs(new_groups);
//
// Collection inh_grps = item.getInheritedGroupRefs();
// boolean groups_are_inherited = (new_groups.size() == inh_grps.size()) && inh_grps.containsAll(new_groups);
//
// if(groups_are_inherited)
// {
// new_groups.clear();
// item.setEntityGroupRefs(new_groups);
// item.setAccess(AccessMode.INHERITED.toString());
// }
// else
// {
// item.setEntityGroupRefs(new_groups);
// item.setAccess(AccessMode.GROUPED.toString());
// }
//
// item.setPubview(false);
}
else if(ResourcesAction.PUBLIC_ACCESS.equals(access_mode))
{
// if(! preventPublicDisplay.booleanValue() && ! item.isPubviewInherited())
// {
// item.setPubview(true);
// item.setAccess(AccessMode.INHERITED.toString());
// }
}
else if(AccessMode.INHERITED.toString().equals(access_mode))
{
}
// update resource with access info
// notification
int noti = NotificationService.NOTI_NONE;
// read the notification options
String notification = params.getString("notify");
if ("r".equals(notification))
{
noti = NotificationService.NOTI_REQUIRED;
}
else if ("o".equals(notification))
{
noti = NotificationService.NOTI_OPTIONAL;
}
contentService.commitResource(resource, noti);
toolSession.removeAttribute(ResourceToolAction.ACTION_PIPE);
// set to public access if allowed and requested
if(!preventPublicDisplay.booleanValue() && ResourcesAction.PUBLIC_ACCESS.equals(access_mode))
{
contentService.setPubView(resource.getId(), true);
}
// show folder if in hierarchy view
SortedSet expandedCollections = (SortedSet) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
expandedCollections.add(collectionId);
if(checkSelctItemFilter(resource, state))
{
AttachItem new_item = new AttachItem(resource.getId(), displayName, collectionId, resource.getUrl());
new_item.setContentType(resource.getContentType());
new_item.setResourceType(resourceType);
List new_items = (List) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
new_items.add(new_item);
}
else
{
addAlert(state, (String) rb.getFormattedMessage("filter", new Object[]{displayName}));
}
state.setAttribute(STATE_HELPER_CHANGED, Boolean.TRUE.toString());
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
}
catch (IdUnusedException e)
{
logger.warn("IdUnusedException", e);
}
catch (PermissionException e)
{
logger.warn("PermissionException", e);
}
catch (IdInvalidException e)
{
logger.warn("IdInvalidException", e);
}
catch (ServerOverloadException e)
{
logger.warn("ServerOverloadException", e);
}
catch (OverQuotaException e)
{
// TODO Auto-generated catch block
logger.warn("OverQuotaException ", e);
}
catch (IdUniquenessException e)
{
// TODO Auto-generated catch block
logger.warn("IdUniquenessException ", e);
}
catch (IdLengthException e)
{
// TODO Auto-generated catch block
logger.warn("IdLengthException ", e);
}
}
else if(user_action.equals("cancel"))
{
if(pipe != null)
{
ResourceToolAction action = pipe.getAction();
if(action == null)
{
}
else
{
if(action instanceof InteractionAction)
{
InteractionAction iAction = (InteractionAction) action;
iAction.cancelAction(null, pipe.getInitializationId());
}
}
}
state.setAttribute(STATE_FILEPICKER_MODE, MODE_ATTACHMENT_SELECT_INIT);
}
}
/**
* @param data
*/
public void doDispatchAction(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
// find the ContentHosting service
ContentHostingService contentService = (ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
// get the parameter-parser
ParameterParser params = data.getParameters();
String action_string = params.getString("rt_action");
String selectedItemId = params.getString("selectedItemId");
String[] parts = action_string.split(ResourceToolAction.ACTION_DELIMITER);
String typeId = parts[0];
String actionId = parts[1];
// ResourceType type = getResourceType(selectedItemId, state);
ResourceTypeRegistry registry = (ResourceTypeRegistry) state.getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
if(registry == null)
{
registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
state.setAttribute(STATE_RESOURCES_TYPE_REGISTRY, registry);
}
ResourceType type = registry.getType(typeId);
Reference reference = EntityManager.newReference(contentService.getReference(selectedItemId));
ResourceToolAction action = type.getAction(actionId);
if(action == null)
{
}
else if(action instanceof InteractionAction)
{
ToolSession toolSession = SessionManager.getCurrentToolSession();
// toolSession.setAttribute(ResourceToolAction.ACTION_ID, actionId);
// toolSession.setAttribute(ResourceToolAction.RESOURCE_TYPE, typeId);
state.setAttribute(ResourcesAction.STATE_CREATE_WIZARD_COLLECTION_ID, selectedItemId);
ContentEntity entity = (ContentEntity) reference.getEntity();
InteractionAction iAction = (InteractionAction) action;
String intitializationId = iAction.initializeAction(reference);
ResourceToolActionPipe pipe = registry.newPipe(intitializationId, action);
pipe.setContentEntity(entity);
pipe.setHelperId(iAction.getHelperId());
toolSession.setAttribute(ResourceToolAction.ACTION_PIPE, pipe);
ResourceProperties props = entity.getProperties();
List propKeys = iAction.getRequiredPropertyKeys();
if(propKeys != null)
{
Iterator it = propKeys.iterator();
while(it.hasNext())
{
String key = (String) it.next();
Object value = props.get(key);
if(value == null)
{
// do nothing
}
else if(value instanceof String)
{
pipe.setResourceProperty(key, (String) value);
}
else if(value instanceof List)
{
pipe.setResourceProperty(key, (List) value);
}
}
}
if(entity.isResource())
{
try
{
pipe.setMimeType(((ContentResource) entity).getContentType());
pipe.setContent(((ContentResource) entity).getContent());
}
catch (ServerOverloadException e)
{
logger.warn(this + ".doDispatchAction ServerOverloadException", e);
}
}
startHelper(data.getRequest(), iAction.getHelperId(), MAIN_PANEL);
}
else if(action instanceof ServiceLevelAction)
{
ServiceLevelAction sAction = (ServiceLevelAction) action;
sAction.initializeAction(reference);
switch(sAction.getActionType())
{
case COPY:
List<String> items_to_be_copied = new Vector<String>();
if(selectedItemId != null)
{
items_to_be_copied.add(selectedItemId);
}
state.setAttribute(ResourcesAction.STATE_ITEMS_TO_BE_COPIED, items_to_be_copied);
break;
case DUPLICATE:
//duplicateItem(state, selectedItemId, contentService.getContainingCollectionId(selectedItemId));
break;
case DELETE:
//deleteItem(state, selectedItemId);
if (state.getAttribute(STATE_MESSAGE) == null)
{
// need new context
//state.setAttribute (STATE_MODE, MODE_DELETE_FINISH);
}
break;
case MOVE:
List<String> items_to_be_moved = new Vector<String>();
if(selectedItemId != null)
{
items_to_be_moved.add(selectedItemId);
}
//state.setAttribute(STATE_ITEMS_TO_BE_MOVED, items_to_be_moved);
break;
case VIEW_METADATA:
break;
case REVISE_METADATA:
state.setAttribute(ResourcesAction.STATE_REVISE_PROPERTIES_ENTITY_ID, selectedItemId);
state.setAttribute(ResourcesAction.STATE_REVISE_PROPERTIES_ACTION, action);
state.setAttribute (STATE_FILEPICKER_MODE, ResourcesAction.MODE_REVISE_METADATA);
break;
case CUSTOM_TOOL_ACTION:
// do nothing
break;
case NEW_UPLOAD:
break;
case NEW_FOLDER:
break;
case CREATE:
break;
case REVISE_CONTENT:
break;
case REPLACE_CONTENT:
break;
case PASTE_MOVED:
//pasteItem(state, selectedItemId);
break;
case PASTE_COPIED:
//pasteItem(state, selectedItemId);
break;
case REVISE_ORDER:
//state.setAttribute(STATE_REORDER_FOLDER, selectedItemId);
//state.setAttribute(STATE_FILEPICKER_MODE, MODE_REORDER);
break;
default:
break;
}
// not quite right for actions involving user interaction in Resources tool.
// For example, with delete, this should be after the confirmation and actual deletion
// Need mechanism to remember to do it later
sAction.finalizeAction(reference);
}
}
/**
* Add the collection id into the expanded collection list
* @throws PermissionException
* @throws TypeException
* @throws IdUnusedException
*/
public void doExpand_collection(RunData data) throws IdUnusedException, TypeException, PermissionException
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
SortedSet expandedItems = (SortedSet) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(expandedItems == null)
{
expandedItems = new TreeSet();
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedItems);
}
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
String id = params.getString("collectionId");
expandedItems.add(id);
} // doExpand_collection
/**
* Remove the collection id from the expanded collection list
*/
public void doCollapse_collection(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
SortedSet expandedItems = (SortedSet) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(expandedItems == null)
{
expandedItems = new TreeSet();
}
// Map folderSortMap = (Map) state.getAttribute(STATE_EXPANDED_FOLDER_SORT_MAP);
// if(folderSortMap == null)
// {
// folderSortMap = new Hashtable();
// state.setAttribute(STATE_EXPANDED_FOLDER_SORT_MAP, folderSortMap);
// }
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
String collectionId = params.getString("collectionId");
SortedSet newSet = new TreeSet();
Iterator l = expandedItems.iterator();
while (l.hasNext ())
{
// remove the collection id and all of the subcollections
// Resource collection = (Resource) l.next();
// String id = (String) collection.getId();
String id = (String) l.next();
if (id.indexOf (collectionId)==-1)
{
// newSet.put(id,collection);
newSet.add(id);
}
// else
// {
// folderSortMap.remove(id);
// }
}
state.setAttribute(STATE_EXPANDED_COLLECTIONS, newSet);
} // doCollapse_collection
/**
* Expand all the collection resources.
*/
public void doExpandall ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
// expansion actually occurs in getBrowseItems method.
state.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.TRUE.toString());
state.setAttribute(STATE_NEED_TO_EXPAND_ALL, Boolean.TRUE.toString());
} // doExpandall
/**
* Unexpand all the collection resources
*/
public void doUnexpandall ( RunData data)
{
// get the state object
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings ("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, new TreeSet());
// state.setAttribute(STATE_EXPANDED_FOLDER_SORT_MAP, new Hashtable());
state.setAttribute(STATE_EXPAND_ALL_FLAG, Boolean.FALSE.toString());
} // doUnexpandall
/**
* @param data
*/
public void doShowOtherSites(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.TRUE.toString());
}
/**
* @param data
*/
public void doHideOtherSites(RunData data)
{
SessionState state = ((JetspeedRunData)data).getPortletSessionState (((JetspeedRunData)data).getJs_peid ());
state.setAttribute(STATE_SHOW_OTHER_SITES, Boolean.FALSE.toString());
//get the ParameterParser from RunData
ParameterParser params = data.getParameters ();
// save the current selections
Set selectedSet = new TreeSet();
String[] selectedItems = params.getStrings("selectedMembers");
if(selectedItems != null)
{
selectedSet.addAll(Arrays.asList(selectedItems));
}
state.setAttribute(STATE_LIST_SELECTIONS, selectedSet);
}
/**
* @param resource
* @param state
* @return
*/
protected boolean checkSelctItemFilter(ContentResource resource, SessionState state)
{
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACHMENT_FILTER);
if (filter != null)
{
return filter.allowSelect(resource);
}
return true;
}
/**
* Find the resource name of a given resource id or filepath.
*
* @param id
* The resource id.
* @return the resource name.
*/
protected static String isolateName(String id)
{
if (id == null) return null;
if (id.length() == 0) return null;
// take after the last resource path separator, not counting one at the very end if there
boolean lastIsSeparator = id.charAt(id.length() - 1) == '/';
return id.substring(id.lastIndexOf('/', id.length() - 2) + 1, (lastIsSeparator ? id.length() - 1 : id.length()));
} // isolateName
/**
* @param url
* @return
* @throws MalformedURLException
*/
protected static String validateURL(String url) throws MalformedURLException
{
if (url.equals (NULL_STRING))
{
// ignore the empty url field
}
else if (url.indexOf ("://") == -1)
{
// if it's missing the transport, add http://
url = "http://" + url;
}
if(!url.equals(NULL_STRING))
{
// valid protocol?
try
{
// test to see if the input validates as a URL.
// Checks string for format only.
URL u = new URL(url);
}
catch (MalformedURLException e1)
{
try
{
Pattern pattern = Pattern.compile("\\s*([a-zA-Z0-9]+)://([^\\n]+)");
Matcher matcher = pattern.matcher(url);
if(matcher.matches())
{
// if URL has "unknown" protocol, check remaider with
// "http" protocol and accept input if that validates.
URL test = new URL("http://" + matcher.group(2));
}
else
{
throw e1;
}
}
catch (MalformedURLException e2)
{
throw e1;
}
}
}
return url;
}
/**
* AttachItem
*
*/
public static class AttachItem
{
protected String m_id;
protected String m_displayName;
protected String m_accessUrl;
protected String m_collectionId;
protected String m_contentType;
protected String m_resourceType;
/**
* @param id
* @param displayName
* @param collectionId
* @param accessUrl
*/
public AttachItem(String id, String displayName, String collectionId, String accessUrl)
{
m_id = id;
m_displayName = displayName;
m_collectionId = collectionId;
m_accessUrl = accessUrl;
}
/**
* @param resource
*/
public AttachItem(ContentEntity entity)
{
m_id = entity.getId();
m_displayName = entity.getProperties().getProperty(ResourceProperties.PROP_DISPLAY_NAME);
m_collectionId = entity.getContainingCollection().getId();
m_accessUrl = entity.getUrl();
if(entity instanceof ContentResource)
{
m_contentType = ((ContentResource) entity).getContentType();
}
m_resourceType = entity.getResourceType();
}
/**
* @param resourceType
*/
public void setResourceType(String resourceType)
{
this.m_resourceType = resourceType;
}
/**
* @return Returns the accessUrl.
*/
public String getAccessUrl()
{
return m_accessUrl;
}
/**
* @param accessUrl The accessUrl to set.
*/
public void setAccessUrl(String accessUrl)
{
m_accessUrl = accessUrl;
}
/**
* @return Returns the collectionId.
*/
public String getCollectionId()
{
return m_collectionId;
}
/**
* @param collectionId The collectionId to set.
*/
public void setCollectionId(String collectionId)
{
m_collectionId = collectionId;
}
/**
* @return Returns the id.
*/
public String getId()
{
return m_id;
}
/**
* @param id The id to set.
*/
public void setId(String id)
{
m_id = id;
}
/**
* @return Returns the name.
*/
public String getDisplayName()
{
String displayName = m_displayName;
if(displayName == null || displayName.trim().equals(""))
{
displayName = isolateName(m_id);
}
return displayName;
}
/**
* @param name The name to set.
*/
public void setDisplayName(String name)
{
m_displayName = name;
}
/**
* @return Returns the contentType.
*/
public String getContentType()
{
return m_contentType;
}
/**
* @param contentType
*/
public void setContentType(String contentType)
{
this.m_contentType = contentType;
}
/**
* @return the resourceType
*/
public String getResourceType()
{
return m_resourceType;
}
} // Inner class AttachItem
} // class FilePickerAction
| false | true | protected String buildSelectAttachmentContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("tlang",rb);
// find the ContentHosting service
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("labeler", new ResourceTypeLabeler());
context.put("ACTION_DELIMITER", ResourceToolAction.ACTION_DELIMITER);
List new_items = (List) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
context.put("attached", new_items);
context.put("last", new Integer(new_items.size() - 1));
Integer max_cardinality = (Integer) state.getAttribute(STATE_ATTACH_CARDINALITY);
if(max_cardinality == null)
{
max_cardinality = FilePickerHelper.CARDINALITY_MULTIPLE;
state.setAttribute(STATE_ATTACH_CARDINALITY, max_cardinality);
}
context.put("max_cardinality", max_cardinality);
if(new_items.size() < max_cardinality.intValue())
{
context.put("can_attach_more", Boolean.TRUE);
}
if(new_items.size() >= max_cardinality.intValue())
{
context.put("disable_attach_links", Boolean.TRUE.toString());
}
if(state.getAttribute(STATE_HELPER_CHANGED) != null)
{
context.put("list_has_changed", Boolean.TRUE.toString());
}
boolean inMyWorkspace = SiteService.isUserSite(ToolManager.getCurrentPlacement().getContext());
// context.put("inMyWorkspace", Boolean.toString(inMyWorkspace));
boolean atHome = false;
// %%STATE_MODE_RESOURCES%%
//boolean dropboxMode = RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES));
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
// make sure the collectionId is set
String collectionId = (String) state.getAttribute(STATE_DEFAULT_COLLECTION_ID);
if(collectionId == null)
{
collectionId = homeCollectionId;
}
context.put ("collectionId", collectionId);
String navRoot = (String) state.getAttribute(STATE_NAVIGATION_ROOT);
// String siteTitle = (String) state.getAttribute (STATE_SITE_TITLE);
if (collectionId.equals(homeCollectionId))
{
atHome = true;
//context.put ("collectionDisplayName", state.getAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME));
}
Comparator userSelectedSort = (Comparator) state.getAttribute(STATE_LIST_VIEW_SORT);
// set the sort values
String sortedBy = (String) state.getAttribute (STATE_SORT_BY);
String sortedAsc = (String) state.getAttribute (STATE_SORT_ASC);
context.put ("currentSortedBy", sortedBy);
context.put ("currentSortAsc", sortedAsc);
context.put("TRUE", Boolean.TRUE.toString());
try
{
try
{
contentService.checkCollection (collectionId);
context.put ("collectionFlag", Boolean.TRUE.toString());
}
catch(IdUnusedException ex)
{
if(logger.isDebugEnabled())
{
logger.debug("ResourcesAction.buildSelectAttachment (static) : IdUnusedException: " + collectionId);
}
try
{
ContentCollectionEdit coll = contentService.addCollection(collectionId);
contentService.commitCollection(coll);
}
catch(IdUsedException inner)
{
// how can this happen??
logger.warn("ResourcesAction.buildSelectAttachment (static) : IdUsedException: " + collectionId);
throw ex;
}
catch(IdInvalidException inner)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : IdInvalidException: " + collectionId);
// what now?
throw ex;
}
catch(InconsistentException inner)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : InconsistentException: " + collectionId);
// what now?
throw ex;
}
}
catch(TypeException ex)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : TypeException.");
throw ex;
}
catch(PermissionException ex)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : PermissionException.");
throw ex;
}
SortedSet<String> expandedCollections = (SortedSet<String>) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(expandedCollections == null)
{
expandedCollections = new TreeSet<String>();
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
expandedCollections.add(collectionId);
ResourceTypeRegistry registry = (ResourceTypeRegistry) state.getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
if(registry == null)
{
registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
state.setAttribute(STATE_RESOURCES_TYPE_REGISTRY, registry);
}
boolean expandAll = Boolean.TRUE.toString().equals(state.getAttribute(STATE_NEED_TO_EXPAND_ALL));
//state.removeAttribute(STATE_PASTE_ALLOWED_FLAG);
List<ListItem> this_site = new Vector<ListItem>();
if(contentService.isInDropbox(collectionId))
{
User[] submitters = (User[]) state.getAttribute(FilePickerHelper.FILE_PICKER_SHOW_DROPBOXES);
if(submitters != null)
{
String dropboxId = contentService.getDropboxCollection();
if(dropboxId == null)
{
contentService.createDropboxCollection();
dropboxId = contentService.getDropboxCollection();
}
if(dropboxId == null)
{
// do nothing
}
else if(contentService.isDropboxMaintainer())
{
for(int i = 0; i < submitters.length; i++)
{
User submitter = submitters[i];
String dbId = dropboxId + StringUtil.trimToZero(submitter.getId()) + "/";
try
{
ContentCollection db = contentService.getCollection(dbId);
expandedCollections.add(dbId);
ListItem item = ListItem.getListItem(db, (ListItem) null, registry, expandAll, expandedCollections, (List<String>) null, (List<String>) null, 0, userSelectedSort);
List<ListItem> items = item.convert2list();
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACHMENT_FILTER);
if(filter != null)
{
items = filterList(items, filter);
}
this_site.addAll(item.convert2list());
// List dbox = getListView(dbId, highlightedItems, (ResourcesBrowseItem) null, false, state);
// getBrowseItems(dbId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, false, state);
// if(dbox != null && dbox.size() > 0)
// {
// ResourcesBrowseItem root = (ResourcesBrowseItem) dbox.remove(0);
// // context.put("site", root);
// root.setName(submitter.getDisplayName() + " " + rb.getString("gen.drop"));
// root.addMembers(dbox);
// this_site.add(root);
// }
}
catch(IdUnusedException e)
{
// ignore a user's dropbox if it's not defined
}
}
}
else
{
try
{
ContentCollection db = contentService.getCollection(dropboxId);
expandedCollections.add(dropboxId);
ListItem item = ListItem.getListItem(db, null, registry, expandAll, expandedCollections, null, null, 0, null);
this_site.addAll(item.convert2list());
// List dbox = getListView(dropboxId, highlightedItems, (ResourcesBrowseItem) null, false, state);
// // List dbox = getBrowseItems(dropboxId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, false, state);
// if(dbox != null && dbox.size() > 0)
// {
// ResourcesBrowseItem root = (ResourcesBrowseItem) dbox.remove(0);
// // context.put("site", root);
// root.setName(ContentHostingService.getDropboxDisplayName());
// root.addMembers(dbox);
// this_site.add(root);
// }
}
catch(IdUnusedException e)
{
// if an id is unused, ignore it
}
}
}
}
else
{
ContentCollection collection = contentService.getCollection(collectionId);
ListItem item = ListItem.getListItem(collection, null, registry, expandAll, expandedCollections, null, null, 0, null);
this_site.addAll(item.convert2list());
}
// List members = getListView(collectionId, highlightedItems, (ResourcesBrowseItem) null, navRoot.equals(homeCollectionId), state);
// // List members = getBrowseItems(collectionId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, navRoot.equals(homeCollectionId), state);
// if(members != null && members.size() > 0)
// {
// ResourcesBrowseItem root = (ResourcesBrowseItem) members.remove(0);
// if(atHome && dropboxMode)
// {
// root.setName(siteTitle + " " + rb.getString("gen.drop"));
// }
// else if(atHome)
// {
// root.setName(siteTitle + " " + rb.getString("gen.reso"));
// }
// context.put("site", root);
// root.addMembers(members);
// this_site.add(root);
// }
context.put ("this_site", this_site);
List other_sites = new Vector();
boolean show_all_sites = false;
String allowed_to_see_other_sites = (String) state.getAttribute(STATE_SHOW_ALL_SITES);
String show_other_sites = (String) state.getAttribute(STATE_SHOW_OTHER_SITES);
context.put("show_other_sites", show_other_sites);
if(Boolean.TRUE.toString().equals(allowed_to_see_other_sites))
{
context.put("allowed_to_see_other_sites", Boolean.TRUE.toString());
show_all_sites = Boolean.TRUE.toString().equals(show_other_sites);
}
if(show_all_sites)
{
// List messages = prepPage(state);
// context.put("other_sites", messages);
//
// if (state.getAttribute(STATE_NUM_MESSAGES) != null)
// {
// context.put("allMsgNumber", state.getAttribute(STATE_NUM_MESSAGES).toString());
// context.put("allMsgNumberInt", state.getAttribute(STATE_NUM_MESSAGES));
// }
//
// context.put("pagesize", ((Integer) state.getAttribute(STATE_PAGESIZE)).toString());
//
// // find the position of the message that is the top first on the page
// if ((state.getAttribute(STATE_TOP_MESSAGE_INDEX) != null) && (state.getAttribute(STATE_PAGESIZE) != null))
// {
// int topMsgPos = ((Integer)state.getAttribute(STATE_TOP_MESSAGE_INDEX)).intValue() + 1;
// context.put("topMsgPos", Integer.toString(topMsgPos));
// int btmMsgPos = topMsgPos + ((Integer)state.getAttribute(STATE_PAGESIZE)).intValue() - 1;
// if (state.getAttribute(STATE_NUM_MESSAGES) != null)
// {
// int allMsgNumber = ((Integer)state.getAttribute(STATE_NUM_MESSAGES)).intValue();
// if (btmMsgPos > allMsgNumber)
// btmMsgPos = allMsgNumber;
// }
// context.put("btmMsgPos", Integer.toString(btmMsgPos));
// }
//
// boolean goPPButton = state.getAttribute(STATE_PREV_PAGE_EXISTS) != null;
// context.put("goPPButton", Boolean.toString(goPPButton));
// boolean goNPButton = state.getAttribute(STATE_NEXT_PAGE_EXISTS) != null;
// context.put("goNPButton", Boolean.toString(goNPButton));
//
// /*
// boolean goFPButton = state.getAttribute(STATE_FIRST_PAGE_EXISTS) != null;
// context.put("goFPButton", Boolean.toString(goFPButton));
// boolean goLPButton = state.getAttribute(STATE_LAST_PAGE_EXISTS) != null;
// context.put("goLPButton", Boolean.toString(goLPButton));
// */
//
// context.put("pagesize", state.getAttribute(STATE_PAGESIZE));
// // context.put("pagesizes", PAGESIZES);
}
// context.put ("root", root);
context.put("expandedCollections", expandedCollections);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfind"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(TypeException e)
{
// logger.warn(this + "TypeException.");
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(PermissionException e)
{
addAlert(state, rb.getString("notpermis1"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
context.put("homeCollection", (String) state.getAttribute (STATE_HOME_COLLECTION_ID));
// context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE));
context.put ("resourceProperties", contentService.newResourceProperties ());
try
{
// TODO: why 'site' here?
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
context.put("siteTitle", site.getTitle());
}
catch (IdUnusedException e)
{
// logger.warn(this + e.toString());
}
context.put("expandallflag", state.getAttribute(STATE_EXPAND_ALL_FLAG));
state.removeAttribute(STATE_NEED_TO_EXPAND_ALL);
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
// justDelivered(state);
// pick the template based on whether client wants links or copies
String template = TEMPLATE_SELECT;
if(state.getAttribute(STATE_ATTACH_LINKS) == null)
{
// user wants copies in hidden attachments area
template = TEMPLATE_ATTACH;
}
return template;
//return TEMPLATE_SELECT;
}
| protected String buildSelectAttachmentContext(VelocityPortlet portlet, Context context, RunData data, SessionState state)
{
context.put("tlang",rb);
// find the ContentHosting service
org.sakaiproject.content.api.ContentHostingService contentService = (org.sakaiproject.content.api.ContentHostingService) state.getAttribute (STATE_CONTENT_SERVICE);
context.put ("contentTypeImageService", state.getAttribute (STATE_CONTENT_TYPE_IMAGE_SERVICE));
context.put("labeler", new ResourceTypeLabeler());
context.put("ACTION_DELIMITER", ResourceToolAction.ACTION_DELIMITER);
List new_items = (List) state.getAttribute(STATE_ADDED_ITEMS);
if(new_items == null)
{
new_items = new Vector();
state.setAttribute(STATE_ADDED_ITEMS, new_items);
}
context.put("attached", new_items);
context.put("last", new Integer(new_items.size() - 1));
Integer max_cardinality = (Integer) state.getAttribute(STATE_ATTACH_CARDINALITY);
if(max_cardinality == null)
{
max_cardinality = FilePickerHelper.CARDINALITY_MULTIPLE;
state.setAttribute(STATE_ATTACH_CARDINALITY, max_cardinality);
}
context.put("max_cardinality", max_cardinality);
if(new_items.size() < max_cardinality.intValue())
{
context.put("can_attach_more", Boolean.TRUE);
}
if(new_items.size() >= max_cardinality.intValue())
{
context.put("disable_attach_links", Boolean.TRUE.toString());
}
if(state.getAttribute(STATE_HELPER_CHANGED) != null)
{
context.put("list_has_changed", Boolean.TRUE.toString());
}
boolean inMyWorkspace = SiteService.isUserSite(ToolManager.getCurrentPlacement().getContext());
// context.put("inMyWorkspace", Boolean.toString(inMyWorkspace));
boolean atHome = false;
// %%STATE_MODE_RESOURCES%%
//boolean dropboxMode = RESOURCES_MODE_DROPBOX.equalsIgnoreCase((String) state.getAttribute(STATE_MODE_RESOURCES));
String homeCollectionId = (String) state.getAttribute(STATE_HOME_COLLECTION_ID);
// make sure the collectionId is set
String collectionId = (String) state.getAttribute(STATE_DEFAULT_COLLECTION_ID);
if(collectionId == null)
{
collectionId = homeCollectionId;
}
context.put ("collectionId", collectionId);
String navRoot = (String) state.getAttribute(STATE_NAVIGATION_ROOT);
// String siteTitle = (String) state.getAttribute (STATE_SITE_TITLE);
if (collectionId.equals(homeCollectionId))
{
atHome = true;
//context.put ("collectionDisplayName", state.getAttribute (STATE_HOME_COLLECTION_DISPLAY_NAME));
}
Comparator userSelectedSort = (Comparator) state.getAttribute(STATE_LIST_VIEW_SORT);
// set the sort values
String sortedBy = (String) state.getAttribute (STATE_SORT_BY);
String sortedAsc = (String) state.getAttribute (STATE_SORT_ASC);
context.put ("currentSortedBy", sortedBy);
context.put ("currentSortAsc", sortedAsc);
context.put("TRUE", Boolean.TRUE.toString());
try
{
try
{
contentService.checkCollection (collectionId);
context.put ("collectionFlag", Boolean.TRUE.toString());
}
catch(IdUnusedException ex)
{
if(logger.isDebugEnabled())
{
logger.debug("ResourcesAction.buildSelectAttachment (static) : IdUnusedException: " + collectionId);
}
try
{
ContentCollectionEdit coll = contentService.addCollection(collectionId);
contentService.commitCollection(coll);
}
catch(IdUsedException inner)
{
// how can this happen??
logger.warn("ResourcesAction.buildSelectAttachment (static) : IdUsedException: " + collectionId);
throw ex;
}
catch(IdInvalidException inner)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : IdInvalidException: " + collectionId);
// what now?
throw ex;
}
catch(InconsistentException inner)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : InconsistentException: " + collectionId);
// what now?
throw ex;
}
}
catch(TypeException ex)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : TypeException.");
throw ex;
}
catch(PermissionException ex)
{
logger.warn("ResourcesAction.buildSelectAttachment (static) : PermissionException.");
throw ex;
}
SortedSet<String> expandedCollections = (SortedSet<String>) state.getAttribute(STATE_EXPANDED_COLLECTIONS);
if(expandedCollections == null)
{
expandedCollections = new TreeSet<String>();
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
expandedCollections.add(collectionId);
ResourceTypeRegistry registry = (ResourceTypeRegistry) state.getAttribute(STATE_RESOURCES_TYPE_REGISTRY);
if(registry == null)
{
registry = (ResourceTypeRegistry) ComponentManager.get("org.sakaiproject.content.api.ResourceTypeRegistry");
state.setAttribute(STATE_RESOURCES_TYPE_REGISTRY, registry);
}
boolean expandAll = Boolean.TRUE.toString().equals(state.getAttribute(STATE_NEED_TO_EXPAND_ALL));
//state.removeAttribute(STATE_PASTE_ALLOWED_FLAG);
List<ListItem> this_site = new Vector<ListItem>();
if(contentService.isInDropbox(collectionId))
{
User[] submitters = (User[]) state.getAttribute(FilePickerHelper.FILE_PICKER_SHOW_DROPBOXES);
if(submitters != null)
{
String dropboxId = contentService.getDropboxCollection();
if(dropboxId == null)
{
contentService.createDropboxCollection();
dropboxId = contentService.getDropboxCollection();
}
if(dropboxId == null)
{
// do nothing
}
else if(contentService.isDropboxMaintainer())
{
for(int i = 0; i < submitters.length; i++)
{
User submitter = submitters[i];
String dbId = dropboxId + StringUtil.trimToZero(submitter.getId()) + "/";
try
{
ContentCollection db = contentService.getCollection(dbId);
expandedCollections.add(dbId);
ListItem item = ListItem.getListItem(db, (ListItem) null, registry, expandAll, expandedCollections, (List<String>) null, (List<String>) null, 0, userSelectedSort);
List<ListItem> items = item.convert2list();
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACHMENT_FILTER);
if(filter != null)
{
items = filterList(items, filter);
}
this_site.addAll(items);
// List dbox = getListView(dbId, highlightedItems, (ResourcesBrowseItem) null, false, state);
// getBrowseItems(dbId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, false, state);
// if(dbox != null && dbox.size() > 0)
// {
// ResourcesBrowseItem root = (ResourcesBrowseItem) dbox.remove(0);
// // context.put("site", root);
// root.setName(submitter.getDisplayName() + " " + rb.getString("gen.drop"));
// root.addMembers(dbox);
// this_site.add(root);
// }
}
catch(IdUnusedException e)
{
// ignore a user's dropbox if it's not defined
}
}
}
else
{
try
{
ContentCollection db = contentService.getCollection(dropboxId);
expandedCollections.add(dropboxId);
ListItem item = ListItem.getListItem(db, null, registry, expandAll, expandedCollections, null, null, 0, null);
this_site.addAll(item.convert2list());
// List dbox = getListView(dropboxId, highlightedItems, (ResourcesBrowseItem) null, false, state);
// // List dbox = getBrowseItems(dropboxId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, false, state);
// if(dbox != null && dbox.size() > 0)
// {
// ResourcesBrowseItem root = (ResourcesBrowseItem) dbox.remove(0);
// // context.put("site", root);
// root.setName(ContentHostingService.getDropboxDisplayName());
// root.addMembers(dbox);
// this_site.add(root);
// }
}
catch(IdUnusedException e)
{
// if an id is unused, ignore it
}
}
}
}
else
{
ContentCollection collection = contentService.getCollection(collectionId);
ListItem item = ListItem.getListItem(collection, null, registry, expandAll, expandedCollections, null, null, 0, null);
List<ListItem> items = item.convert2list();
ContentResourceFilter filter = (ContentResourceFilter)state.getAttribute(STATE_ATTACHMENT_FILTER);
if(filter != null)
{
items = filterList(items, filter);
}
this_site.addAll(items);
}
// List members = getListView(collectionId, highlightedItems, (ResourcesBrowseItem) null, navRoot.equals(homeCollectionId), state);
// // List members = getBrowseItems(collectionId, expandedCollections, highlightedItems, sortedBy, sortedAsc, (ResourcesBrowseItem) null, navRoot.equals(homeCollectionId), state);
// if(members != null && members.size() > 0)
// {
// ResourcesBrowseItem root = (ResourcesBrowseItem) members.remove(0);
// if(atHome && dropboxMode)
// {
// root.setName(siteTitle + " " + rb.getString("gen.drop"));
// }
// else if(atHome)
// {
// root.setName(siteTitle + " " + rb.getString("gen.reso"));
// }
// context.put("site", root);
// root.addMembers(members);
// this_site.add(root);
// }
context.put ("this_site", this_site);
List other_sites = new Vector();
boolean show_all_sites = false;
String allowed_to_see_other_sites = (String) state.getAttribute(STATE_SHOW_ALL_SITES);
String show_other_sites = (String) state.getAttribute(STATE_SHOW_OTHER_SITES);
context.put("show_other_sites", show_other_sites);
if(Boolean.TRUE.toString().equals(allowed_to_see_other_sites))
{
context.put("allowed_to_see_other_sites", Boolean.TRUE.toString());
show_all_sites = Boolean.TRUE.toString().equals(show_other_sites);
}
if(show_all_sites)
{
// List messages = prepPage(state);
// context.put("other_sites", messages);
//
// if (state.getAttribute(STATE_NUM_MESSAGES) != null)
// {
// context.put("allMsgNumber", state.getAttribute(STATE_NUM_MESSAGES).toString());
// context.put("allMsgNumberInt", state.getAttribute(STATE_NUM_MESSAGES));
// }
//
// context.put("pagesize", ((Integer) state.getAttribute(STATE_PAGESIZE)).toString());
//
// // find the position of the message that is the top first on the page
// if ((state.getAttribute(STATE_TOP_MESSAGE_INDEX) != null) && (state.getAttribute(STATE_PAGESIZE) != null))
// {
// int topMsgPos = ((Integer)state.getAttribute(STATE_TOP_MESSAGE_INDEX)).intValue() + 1;
// context.put("topMsgPos", Integer.toString(topMsgPos));
// int btmMsgPos = topMsgPos + ((Integer)state.getAttribute(STATE_PAGESIZE)).intValue() - 1;
// if (state.getAttribute(STATE_NUM_MESSAGES) != null)
// {
// int allMsgNumber = ((Integer)state.getAttribute(STATE_NUM_MESSAGES)).intValue();
// if (btmMsgPos > allMsgNumber)
// btmMsgPos = allMsgNumber;
// }
// context.put("btmMsgPos", Integer.toString(btmMsgPos));
// }
//
// boolean goPPButton = state.getAttribute(STATE_PREV_PAGE_EXISTS) != null;
// context.put("goPPButton", Boolean.toString(goPPButton));
// boolean goNPButton = state.getAttribute(STATE_NEXT_PAGE_EXISTS) != null;
// context.put("goNPButton", Boolean.toString(goNPButton));
//
// /*
// boolean goFPButton = state.getAttribute(STATE_FIRST_PAGE_EXISTS) != null;
// context.put("goFPButton", Boolean.toString(goFPButton));
// boolean goLPButton = state.getAttribute(STATE_LAST_PAGE_EXISTS) != null;
// context.put("goLPButton", Boolean.toString(goLPButton));
// */
//
// context.put("pagesize", state.getAttribute(STATE_PAGESIZE));
// // context.put("pagesizes", PAGESIZES);
}
// context.put ("root", root);
context.put("expandedCollections", expandedCollections);
state.setAttribute(STATE_EXPANDED_COLLECTIONS, expandedCollections);
}
catch (IdUnusedException e)
{
addAlert(state, rb.getString("cannotfind"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(TypeException e)
{
// logger.warn(this + "TypeException.");
context.put ("collectionFlag", Boolean.FALSE.toString());
}
catch(PermissionException e)
{
addAlert(state, rb.getString("notpermis1"));
context.put ("collectionFlag", Boolean.FALSE.toString());
}
context.put("homeCollection", (String) state.getAttribute (STATE_HOME_COLLECTION_ID));
// context.put("siteTitle", state.getAttribute(STATE_SITE_TITLE));
context.put ("resourceProperties", contentService.newResourceProperties ());
try
{
// TODO: why 'site' here?
Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
context.put("siteTitle", site.getTitle());
}
catch (IdUnusedException e)
{
// logger.warn(this + e.toString());
}
context.put("expandallflag", state.getAttribute(STATE_EXPAND_ALL_FLAG));
state.removeAttribute(STATE_NEED_TO_EXPAND_ALL);
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
// justDelivered(state);
// pick the template based on whether client wants links or copies
String template = TEMPLATE_SELECT;
if(state.getAttribute(STATE_ATTACH_LINKS) == null)
{
// user wants copies in hidden attachments area
template = TEMPLATE_ATTACH;
}
return template;
//return TEMPLATE_SELECT;
}
|
diff --git a/src/configuration/Configuration.java b/src/configuration/Configuration.java
index 6e22618..6cf94ce 100644
--- a/src/configuration/Configuration.java
+++ b/src/configuration/Configuration.java
@@ -1,396 +1,396 @@
/**
*
*/
package configuration;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;
import speech.Speech;
/**
* @author Nauman Badar <[email protected]>
* @created Apr 18, 2011
*
*/
public class Configuration {
private static final String HARDCODED_HTTP_PORT = "8080";
private static final String HARDCODED_SIP_USER = "robot";
private static final String HARDCODED_SIP_PORT = "5061";
private final static Logger log = Logger.getLogger(Configuration.class);
public static Configuration INSTANCE = new Configuration();
private Configuration() {
currentFilePath = "";
defaultFilePath = "sipspeaker.cfg";
defaultMessage = "default.wav";
workingFilePath = "wsipspeaker.cfg";
currentMessage = "";
currentText = "";
sipUser = "";
sipPort = "";
httpPort = "";
}
private String defaultMessage;
private String defaultText;
private String currentMessage;
private String currentText;
private String sipUser;
private String sipPort;
private String httpPort;
private String defaultFilePath;
private String currentFilePath;
private String workingFilePath;
private Properties properties = new Properties();
public void insert(String args[]) {
try {
if (args.length == 0 && !(new File(defaultFilePath).exists())) {
// FileOutputStream fileOutputStream = new FileOutputStream(new
// File(defaultFilePath));
// FileOutputStream fileOutputStream = new FileOutputStream(new File(workingFilePath));
FileOutputStream fileOutputStream = new FileOutputStream(new File(defaultFilePath));
properties.setProperty("default_message", "default.wav");
properties.setProperty("message_wav", "");
properties.setProperty("message_text", "");
properties.setProperty("sip_user", HARDCODED_SIP_USER);
properties.setProperty("sip_port", HARDCODED_SIP_PORT);
properties.setProperty("http_port", HARDCODED_HTTP_PORT);
properties.store(fileOutputStream, null);
fileOutputStream.flush();
fileOutputStream.close();
// defaultMessage = "default.wav";
// currentMessage = "";
sipUser = HARDCODED_SIP_USER;
sipPort = HARDCODED_SIP_PORT;
httpPort = HARDCODED_HTTP_PORT;
defaultText = "This is the dynamically generated message when no default configuration file exists.";
Speech.produce("default", "This is the dynamically generated message when no default configuration file exists.");
} else if (args.length == 0 && (new File(defaultFilePath).exists())) {
FileInputStream fileInputStream = new FileInputStream(new File(defaultFilePath));
properties.load(fileInputStream);
fileInputStream.close();
defaultMessage = properties.getProperty("default_message");
currentMessage = properties.getProperty("message_wav");
currentText = properties.getProperty("message_text");
sipUser = properties.getProperty("sip_user");
sipPort = properties.getProperty("sip_port");
httpPort = properties.getProperty("http_port");
defaultText = "No arguments given.";
if (currentMessage.isEmpty()) {
currentMessage = "current.wav";
}
// Speech.produce("default", "No arguments given.");
dumpToFile(properties);
} else if (args.length != 0) {
parseCommandLineArguments(args);
if (new File(currentFilePath).exists()) {
FileInputStream fileInputStream = new FileInputStream(new File(currentFilePath));
properties.load(fileInputStream);
if (sipUser.isEmpty()) {
sipUser = properties.getProperty("sip_user");
}
if (sipPort.isEmpty()) {
sipPort = properties.getProperty("sip_port");
}
if (httpPort.isEmpty()) {
httpPort = properties.getProperty("http_port");
}
defaultMessage = properties.getProperty("default_message");
defaultText = "Default Message, message from given configuration file was loaded.";
currentMessage = properties.getProperty("message_wav");
log.info("current mesg: " + currentMessage);
currentText = properties.getProperty("message_text");
if (currentMessage.isEmpty()) {
currentMessage = "current.wav";
}
log.info("Given configuration loaded.");
} else {
if (sipUser.isEmpty()) {
sipUser = HARDCODED_SIP_USER;
}
if (sipPort.isEmpty()) {
sipPort = HARDCODED_SIP_PORT;
}
if (httpPort.isEmpty()) {
httpPort = HARDCODED_HTTP_PORT;
}
defaultText = "Default Message, Configuration file name was given in arguments but it does not exist.";
- currentMessage = "";
- currentText = "Current Message generated because the given configuration file didn't exist.";
+ currentMessage = "wrongcfg.wav";
+ currentText = "Current Message generated because of wrong configuration file name.";
}
dumpToFile(properties);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
log.info(e.getMessage());
} catch (IOException e) {
log.info(e.getMessage());
e.printStackTrace();
}
}
/**
* @param properties
* @throws FileNotFoundException
* @throws IOException
*/
private void dumpToFile(Properties properties) throws FileNotFoundException, IOException {
if (!(new File(defaultMessage).exists())) {
Speech.produce(defaultMessage.replace(".wav", ""), defaultText);
}
if (!currentText.isEmpty()) {
Speech.produce(currentMessage.replace(".wav", ""), currentText);
}
properties.setProperty("default_message", defaultMessage);
properties.setProperty("message_wav", currentMessage);
properties.setProperty("message_text", currentText);
properties.setProperty("sip_user", sipUser);
properties.setProperty("sip_port", sipPort);
properties.setProperty("http_port", httpPort);
// FileOutputStream fileOutputStream = new FileOutputStream(new File(workingFilePath));
FileOutputStream fileOutputStream = new FileOutputStream(new File(defaultFilePath));
properties.store(fileOutputStream, null);
fileOutputStream.flush();
fileOutputStream.close();
if (!currentFilePath.isEmpty()) {
fileOutputStream = new FileOutputStream(new File(currentFilePath));
properties.store(fileOutputStream, null);
fileOutputStream.flush();
fileOutputStream.close();
}
}
/**
* @param args
*/
private void parseCommandLineArguments(String[] args) {
int index = 0;
for (int i = 0; i < args.length; i++) {
if (args[i].compareTo("-c") == 0) {
currentFilePath = args[i + 1];
}
if (args[i].compareTo("-user") == 0) {
index = args[i + 1].indexOf("@");
sipUser = args[i + 1].substring(0, index);
index = args[i + 1].indexOf(":");
sipPort = args[i + 1].substring(index + 1);
}
if (args[i].compareTo("-http") == 0) {
index = args[i + 1].indexOf(":");
httpPort = args[i + 1].substring(index + 1);
}
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "defaultMessage " + defaultMessage + "\n" + "currentMessage " + currentMessage + "\n" + "currentText " + currentText + "\n" + "sipUser " + sipUser + "\n" + "sipPort " + sipPort + "\n" + "httpPort " + httpPort + "\n" + "defaultFilePath " + defaultFilePath + "\n" + "currentFilePath " + currentFilePath + "\n";
}
/**
* @param iNSTANCE
* the iNSTANCE to set
*/
public static void setINSTANCE(Configuration iNSTANCE) {
INSTANCE = iNSTANCE;
}
/**
* @return the defaultMessage
*/
public String getDefaultMessage() {
return defaultMessage;
}
/**
* @param defaultMessage
* the defaultMessage to set
*/
public void setDefaultMessage(String defaultMessage) {
this.defaultMessage = defaultMessage;
}
/**
* @return the currentMessage
*/
public String getCurrentMessage() {
return currentMessage;
}
/**
* @param currentMessage
* the currentMessage to set
*/
public void setCurrentMessage(String currentMessage) {
this.currentMessage = currentMessage;
}
/**
* @return the currentText
*/
public String getCurrentText() {
if (currentMessage.isEmpty()) {
return "Fall back to default message!!";
}
return currentText;
}
/**
* @param currentText
* the currentText to set
*/
public void setCurrentText(String currentText) {
this.currentText = currentText;
}
/**
* @return the sipUser
*/
public String getSipUser() {
return sipUser;
}
/**
* @param sipUser
* the sipUser to set
*/
public void setSipUser(String sipUser) {
this.sipUser = sipUser;
}
/**
* @return the sipPort
*/
public String getSipPort() {
return sipPort;
}
/**
* @param sipPort
* the sipPort to set
*/
public void setSipPort(String sipPort) {
this.sipPort = sipPort;
}
/**
* @return the httpPort
*/
public String getHttpPort() {
return httpPort;
}
/**
* @param httpPort
* the httpPort to set
*/
public void setHttpPort(String httpPort) {
this.httpPort = httpPort;
}
/**
* @return the defaultFilePath
*/
public String getDefaultFilePath() {
return defaultFilePath;
}
/**
* @param defaultFilePath
* the defaultFilePath to set
*/
public void setDefaultFilePath(String defaultFilePath) {
this.defaultFilePath = defaultFilePath;
}
/**
* @return the currentFilePath
*/
public String getCurrentFilePath() {
return currentFilePath;
}
/**
* @param currentFilePath
* the currentFilePath to set
*/
public void setCurrentFilePath(String currentFilePath) {
this.currentFilePath = currentFilePath;
}
public String getPlayMessage() {
if (currentMessage.isEmpty()) {
return defaultMessage;
} else
return currentMessage;
}
public void updateFromWebserver(String text) {
if (text.isEmpty()) {
currentMessage = "";
} else {
currentText = text;
if (currentMessage.isEmpty()) {
Speech.produce("current", currentText);
currentMessage = "current.wav";
} else {
Speech.produce(currentMessage.replace(".wav", ""), currentText);
}
try {
properties.setProperty("message_text", currentText);
FileOutputStream fileOutputStream;
fileOutputStream = new FileOutputStream(new File(defaultFilePath));
properties.store(fileOutputStream, null);
fileOutputStream.flush();
fileOutputStream.close();
if (!currentFilePath.isEmpty()) {
fileOutputStream = new FileOutputStream(new File(currentFilePath));
properties.store(fileOutputStream, null);
fileOutputStream.flush();
fileOutputStream.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
| true | true | public void insert(String args[]) {
try {
if (args.length == 0 && !(new File(defaultFilePath).exists())) {
// FileOutputStream fileOutputStream = new FileOutputStream(new
// File(defaultFilePath));
// FileOutputStream fileOutputStream = new FileOutputStream(new File(workingFilePath));
FileOutputStream fileOutputStream = new FileOutputStream(new File(defaultFilePath));
properties.setProperty("default_message", "default.wav");
properties.setProperty("message_wav", "");
properties.setProperty("message_text", "");
properties.setProperty("sip_user", HARDCODED_SIP_USER);
properties.setProperty("sip_port", HARDCODED_SIP_PORT);
properties.setProperty("http_port", HARDCODED_HTTP_PORT);
properties.store(fileOutputStream, null);
fileOutputStream.flush();
fileOutputStream.close();
// defaultMessage = "default.wav";
// currentMessage = "";
sipUser = HARDCODED_SIP_USER;
sipPort = HARDCODED_SIP_PORT;
httpPort = HARDCODED_HTTP_PORT;
defaultText = "This is the dynamically generated message when no default configuration file exists.";
Speech.produce("default", "This is the dynamically generated message when no default configuration file exists.");
} else if (args.length == 0 && (new File(defaultFilePath).exists())) {
FileInputStream fileInputStream = new FileInputStream(new File(defaultFilePath));
properties.load(fileInputStream);
fileInputStream.close();
defaultMessage = properties.getProperty("default_message");
currentMessage = properties.getProperty("message_wav");
currentText = properties.getProperty("message_text");
sipUser = properties.getProperty("sip_user");
sipPort = properties.getProperty("sip_port");
httpPort = properties.getProperty("http_port");
defaultText = "No arguments given.";
if (currentMessage.isEmpty()) {
currentMessage = "current.wav";
}
// Speech.produce("default", "No arguments given.");
dumpToFile(properties);
} else if (args.length != 0) {
parseCommandLineArguments(args);
if (new File(currentFilePath).exists()) {
FileInputStream fileInputStream = new FileInputStream(new File(currentFilePath));
properties.load(fileInputStream);
if (sipUser.isEmpty()) {
sipUser = properties.getProperty("sip_user");
}
if (sipPort.isEmpty()) {
sipPort = properties.getProperty("sip_port");
}
if (httpPort.isEmpty()) {
httpPort = properties.getProperty("http_port");
}
defaultMessage = properties.getProperty("default_message");
defaultText = "Default Message, message from given configuration file was loaded.";
currentMessage = properties.getProperty("message_wav");
log.info("current mesg: " + currentMessage);
currentText = properties.getProperty("message_text");
if (currentMessage.isEmpty()) {
currentMessage = "current.wav";
}
log.info("Given configuration loaded.");
} else {
if (sipUser.isEmpty()) {
sipUser = HARDCODED_SIP_USER;
}
if (sipPort.isEmpty()) {
sipPort = HARDCODED_SIP_PORT;
}
if (httpPort.isEmpty()) {
httpPort = HARDCODED_HTTP_PORT;
}
defaultText = "Default Message, Configuration file name was given in arguments but it does not exist.";
currentMessage = "";
currentText = "Current Message generated because the given configuration file didn't exist.";
}
dumpToFile(properties);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
log.info(e.getMessage());
} catch (IOException e) {
log.info(e.getMessage());
e.printStackTrace();
}
}
| public void insert(String args[]) {
try {
if (args.length == 0 && !(new File(defaultFilePath).exists())) {
// FileOutputStream fileOutputStream = new FileOutputStream(new
// File(defaultFilePath));
// FileOutputStream fileOutputStream = new FileOutputStream(new File(workingFilePath));
FileOutputStream fileOutputStream = new FileOutputStream(new File(defaultFilePath));
properties.setProperty("default_message", "default.wav");
properties.setProperty("message_wav", "");
properties.setProperty("message_text", "");
properties.setProperty("sip_user", HARDCODED_SIP_USER);
properties.setProperty("sip_port", HARDCODED_SIP_PORT);
properties.setProperty("http_port", HARDCODED_HTTP_PORT);
properties.store(fileOutputStream, null);
fileOutputStream.flush();
fileOutputStream.close();
// defaultMessage = "default.wav";
// currentMessage = "";
sipUser = HARDCODED_SIP_USER;
sipPort = HARDCODED_SIP_PORT;
httpPort = HARDCODED_HTTP_PORT;
defaultText = "This is the dynamically generated message when no default configuration file exists.";
Speech.produce("default", "This is the dynamically generated message when no default configuration file exists.");
} else if (args.length == 0 && (new File(defaultFilePath).exists())) {
FileInputStream fileInputStream = new FileInputStream(new File(defaultFilePath));
properties.load(fileInputStream);
fileInputStream.close();
defaultMessage = properties.getProperty("default_message");
currentMessage = properties.getProperty("message_wav");
currentText = properties.getProperty("message_text");
sipUser = properties.getProperty("sip_user");
sipPort = properties.getProperty("sip_port");
httpPort = properties.getProperty("http_port");
defaultText = "No arguments given.";
if (currentMessage.isEmpty()) {
currentMessage = "current.wav";
}
// Speech.produce("default", "No arguments given.");
dumpToFile(properties);
} else if (args.length != 0) {
parseCommandLineArguments(args);
if (new File(currentFilePath).exists()) {
FileInputStream fileInputStream = new FileInputStream(new File(currentFilePath));
properties.load(fileInputStream);
if (sipUser.isEmpty()) {
sipUser = properties.getProperty("sip_user");
}
if (sipPort.isEmpty()) {
sipPort = properties.getProperty("sip_port");
}
if (httpPort.isEmpty()) {
httpPort = properties.getProperty("http_port");
}
defaultMessage = properties.getProperty("default_message");
defaultText = "Default Message, message from given configuration file was loaded.";
currentMessage = properties.getProperty("message_wav");
log.info("current mesg: " + currentMessage);
currentText = properties.getProperty("message_text");
if (currentMessage.isEmpty()) {
currentMessage = "current.wav";
}
log.info("Given configuration loaded.");
} else {
if (sipUser.isEmpty()) {
sipUser = HARDCODED_SIP_USER;
}
if (sipPort.isEmpty()) {
sipPort = HARDCODED_SIP_PORT;
}
if (httpPort.isEmpty()) {
httpPort = HARDCODED_HTTP_PORT;
}
defaultText = "Default Message, Configuration file name was given in arguments but it does not exist.";
currentMessage = "wrongcfg.wav";
currentText = "Current Message generated because of wrong configuration file name.";
}
dumpToFile(properties);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
log.info(e.getMessage());
} catch (IOException e) {
log.info(e.getMessage());
e.printStackTrace();
}
}
|
diff --git a/src/main/org/h2/engine/Database.java b/src/main/org/h2/engine/Database.java
index 0389cfba..6d4e1aa0 100644
--- a/src/main/org/h2/engine/Database.java
+++ b/src/main/org/h2/engine/Database.java
@@ -1,3454 +1,3459 @@
/***************************************************************************
* *
* H2O *
* Copyright (C) 2010 Distributed Systems Architecture Research Group *
* University of St Andrews, Scotland *
* http://blogs.cs.st-andrews.ac.uk/h2o/ *
* *
* This file is part of H2O, a distributed database based on the open *
* source database H2 (www.h2database.com). *
* *
* H2O 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. *
* *
* H2O 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 H2O. If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
package org.h2.engine;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Observable;
import java.util.Observer;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import org.h2.api.DatabaseEventListener;
import org.h2.command.dml.SetTypes;
import org.h2.constant.ErrorCode;
import org.h2.constant.LocationPreference;
import org.h2.constant.SysProperties;
import org.h2.constraint.Constraint;
import org.h2.index.Cursor;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.log.LogSystem;
import org.h2.message.Message;
import org.h2.message.Trace;
import org.h2.message.TraceSystem;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObject;
import org.h2.schema.Sequence;
import org.h2.schema.TriggerObject;
import org.h2.store.DataHandler;
import org.h2.store.DataPage;
import org.h2.store.DiskFile;
import org.h2.store.FileLock;
import org.h2.store.FileStore;
import org.h2.store.PageStore;
import org.h2.store.RecordReader;
import org.h2.store.Storage;
import org.h2.store.WriterThread;
import org.h2.store.fs.FileSystem;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.MetaTable;
import org.h2.table.ReplicaSet;
import org.h2.table.Table;
import org.h2.table.TableData;
import org.h2.table.TableLinkConnection;
import org.h2.table.TableView;
import org.h2.tools.DeleteDbFiles;
import org.h2.tools.Server;
import org.h2.util.BitField;
import org.h2.util.ByteUtils;
import org.h2.util.CacheLRU;
import org.h2.util.ClassUtils;
import org.h2.util.FileUtils;
import org.h2.util.IntHashMap;
import org.h2.util.NetUtils;
import org.h2.util.ObjectArray;
import org.h2.util.ObjectUtils;
import org.h2.util.SmallLRUCache;
import org.h2.util.StringUtils;
import org.h2.util.TempFileDeleter;
import org.h2.value.CompareMode;
import org.h2.value.Value;
import org.h2.value.ValueInt;
import org.h2.value.ValueLob;
import org.h2o.autonomic.numonic.ISystemStatus;
import org.h2o.autonomic.numonic.NumonicReporter;
import org.h2o.autonomic.numonic.ThresholdChecker;
import org.h2o.autonomic.numonic.interfaces.INumonic;
import org.h2o.autonomic.numonic.threshold.Threshold;
import org.h2o.autonomic.settings.Settings;
import org.h2o.autonomic.settings.TestingSettings;
import org.h2o.db.DatabaseInstanceServer;
import org.h2o.db.id.DatabaseID;
import org.h2o.db.interfaces.IDatabaseInstanceRemote;
import org.h2o.db.manager.SystemTable;
import org.h2o.db.manager.SystemTableReference;
import org.h2o.db.manager.SystemTableServer;
import org.h2o.db.manager.TableManager;
import org.h2o.db.manager.TableManagerInstanceServer;
import org.h2o.db.manager.interfaces.ISystemTableMigratable;
import org.h2o.db.manager.interfaces.ISystemTableReference;
import org.h2o.db.manager.monitorthreads.MetaDataReplicationThread;
import org.h2o.db.manager.recovery.LocatorException;
import org.h2o.db.query.TableProxyManager;
import org.h2o.db.query.asynchronous.AsynchronousQueryManager;
import org.h2o.db.remote.ChordRemote;
import org.h2o.db.remote.IChordInterface;
import org.h2o.db.remote.IDatabaseRemote;
import org.h2o.db.replication.MetaDataReplicaManager;
import org.h2o.db.wrappers.DatabaseInstanceWrapper;
import org.h2o.locator.client.H2OLocatorInterface;
import org.h2o.util.H2ONetUtils;
import org.h2o.util.H2OPropertiesWrapper;
import org.h2o.util.TransactionNameGenerator;
import org.h2o.util.exceptions.MovedException;
import org.h2o.util.exceptions.StartupException;
import org.h2o.viewer.H2OEventBus;
import org.h2o.viewer.H2OEventConsumer;
import org.h2o.viewer.gwt.client.DatabaseStates;
import org.h2o.viewer.gwt.client.H2OEvent;
import org.h2o.viewer.server.KeepAliveMessageThread;
import uk.ac.standrews.cs.nds.events.bus.EventBus;
import uk.ac.standrews.cs.nds.events.bus.interfaces.IEventBus;
import uk.ac.standrews.cs.nds.rpc.RPCException;
import uk.ac.standrews.cs.nds.util.Diagnostic;
import uk.ac.standrews.cs.nds.util.DiagnosticLevel;
import uk.ac.standrews.cs.nds.util.ErrorHandling;
import uk.ac.standrews.cs.numonic.data.ResourceType;
/**
* There is one database object per open database.
*
* The format of the meta data table is: id int, headPos int (for indexes), objectType int, sql varchar
*
* @since 2004-04-15 22:49
*/
public class Database implements DataHandler, Observer, ISystemStatus {
private static int initialPowerOffCount;
private final boolean persistent;
private final String databaseName;
private final String databaseShortName;
private final String databaseURL;
private final String cipher;
private final byte[] filePasswordHash;
private final HashMap<String, DbObject> roles = new HashMap<String, DbObject>();
private final HashMap<String, DbObject> users = new HashMap<String, DbObject>();
private final HashMap<String, DbObject> settings = new HashMap<String, DbObject>();
private final HashMap<String, DbObject> schemas = new HashMap<String, DbObject>();
private final HashMap<String, DbObject> rights = new HashMap<String, DbObject>();
private final HashMap<String, DbObject> functionAliases = new HashMap<String, DbObject>();
private final HashMap<String, DbObject> userDataTypes = new HashMap<String, DbObject>();
private final HashMap<String, DbObject> aggregates = new HashMap<String, DbObject>();
private final HashMap<String, DbObject> comments = new HashMap<String, DbObject>();
private final IntHashMap tableMap = new IntHashMap();
private final HashMap<Integer, DbObject> databaseObjects = new HashMap<Integer, DbObject>();
private final Set<Session> userSessions = Collections.synchronizedSet(new HashSet<Session>());
private Session exclusiveSession;
private final BitField objectIds = new BitField();
private final Object lobSyncObject = new Object();
private Schema mainSchema;
private Schema infoSchema;
private User systemUser;
private Session systemSession;
private TableData meta;
private Index metaIdIndex;
private FileLock lock;
private LogSystem log;
private WriterThread writer;
private final IntHashMap storageMap = new IntHashMap();
private boolean starting;
private DiskFile fileData, fileIndex;
private TraceSystem traceSystem;
private DataPage dummy;
private final int fileLockMethod;
private Role publicRole;
private long modificationDataId;
private long modificationMetaId;
private CompareMode compareMode;
private String cluster = Constants.CLUSTERING_DISABLED;
private boolean readOnly;
private boolean noDiskSpace;
private int writeDelay = Constants.DEFAULT_WRITE_DELAY;
private DatabaseEventListener eventListener;
private int maxMemoryRows = Constants.DEFAULT_MAX_MEMORY_ROWS;
private int maxMemoryUndo = SysProperties.DEFAULT_MAX_MEMORY_UNDO;
private int lockMode = SysProperties.DEFAULT_LOCK_MODE;
private boolean logIndexChanges;
private int logLevel = 1;
private int maxLengthInplaceLob = Constants.DEFAULT_MAX_LENGTH_INPLACE_LOB;
private int allowLiterals = Constants.DEFAULT_ALLOW_LITERALS;
private int powerOffCount = initialPowerOffCount;
private int closeDelay;
private DatabaseCloser delayedCloser;
private boolean recovery;
private volatile boolean closing;
private boolean ignoreCase;
private boolean deleteFilesOnDisconnect;
private String lobCompressionAlgorithm;
private boolean optimizeReuseResults = true;
private final String cacheType;
private boolean indexSummaryValid = true;
private String accessModeLog;
private final String accessModeData;
private boolean referentialIntegrity = true;
private DatabaseCloser closeOnExit;
private Mode mode = Mode.getInstance(Mode.REGULAR);
private int maxOperationMemory = SysProperties.DEFAULT_MAX_OPERATION_MEMORY;
private boolean lobFilesInDirectories = SysProperties.LOB_FILES_IN_DIRECTORIES;
private final SmallLRUCache lobFileListCache = new SmallLRUCache(128);
private final boolean autoServerMode;
private Server server;
private HashMap<TableLinkConnection, TableLinkConnection> linkConnections;
private final TempFileDeleter tempFileDeleter = TempFileDeleter.getInstance();
private PageStore pageStore;
private Properties reconnectLastLock;
private long reconnectCheckNext;
private boolean reconnectChangePending;
private final ISystemTableReference systemTableRef;
private MetaDataReplicaManager metaDataReplicaManager;
private MetaDataReplicationThread metaDataReplicationThread;
private boolean running = false;
public MetaDataReplicaManager getMetaDataReplicaManager() {
return metaDataReplicaManager;
}
/**
* Interface for this database instance to the rest of the database system.
*/
private final ChordRemote databaseRemote;
private final AsynchronousQueryManager asynchronousQueryManager;
private User h2oSchemaUser;
private Session h2oSession;
private User h2oSystemUser;
private Session h2oSystemSession;
private Settings databaseSettings;
private final TransactionNameGenerator transactionNameGenerator;
private final Set<String> localSchema = new HashSet<String>();
private H2OEventConsumer eventConsumer;
private KeepAliveMessageThread keepAliveMessageThread;
private TableManagerInstanceServer table_manager_instance_server;
private DatabaseInstanceServer database_instance_server;
private SystemTableServer system_table_server = null;
private INumonic numonic = null;
private boolean connected = false;
public Database(final String name, final ConnectionInfo ci, final String cipher) throws SQLException {
localSchema.add(Constants.H2O_SCHEMA);
localSchema.add(Constants.SCHEMA_INFORMATION);
databaseName = name;
databaseShortName = parseDatabaseShortName();
final DatabaseID localMachineLocation = DatabaseID.parseURL(ci.getOriginalURL());
// Ensure testing constants are all set to false.
TestingSettings.IS_TESTING_PRE_COMMIT_FAILURE = false;
TestingSettings.IS_TESTING_PRE_PREPARE_FAILURE = false;
TestingSettings.IS_TESTING_QUERY_FAILURE = false;
TestingSettings.IS_TESTING_CREATETABLE_FAILURE = false;
transactionNameGenerator = new TransactionNameGenerator(localMachineLocation);
asynchronousQueryManager = new AsynchronousQueryManager(this);
compareMode = new CompareMode(null, null, 0);
systemTableRef = new SystemTableReference(this);
databaseRemote = new ChordRemote(localMachineLocation, systemTableRef);
persistent = ci.isPersistent();
filePasswordHash = ci.getFilePasswordHash();
if (!isManagementDB()) {
if (Constants.LOG_INCOMING_UPDATES) {
ErrorHandling.errorNoEvent("WARNING: LOGGING OF QUERIES IS ENABLED IN THE TABLEPROXYMANAGER. This uses massive amounts of memory and should only be used when debugging.");
}
if (Constants.DO_LOCK_LOGGING) {
ErrorHandling.errorNoEvent("WARNING: LOGGING OF LOCK REQUESTS IS ENABLED. This uses massive amounts of memory and should only be used when debugging.");
}
/*
* Get Settings for Database.
*/
final H2OPropertiesWrapper localSettings = setUpLocalDatabaseProperties(localMachineLocation);
setDiagnosticLevel(localMachineLocation);
Diagnostic.traceNoEvent(DiagnosticLevel.FINAL, "H2O, Database '" + localMachineLocation.getURL() + "'.");
try {
final H2OLocatorInterface locatorInterface = databaseRemote.getLocatorInterface();
databaseSettings = new Settings(localSettings, locatorInterface.getDescriptor());
}
catch (final LocatorException e) {
e.printStackTrace();
throw new SQLException(e.getMessage());
}
catch (final StartupException e) {
throw new SQLException(e.getMessage());
}
/*
* Set up events.
*/
if (databaseSettings.get("DATABASE_EVENTS_ENABLED").equals("true")) {
final IEventBus bus = new EventBus();
H2OEventBus.setBus(bus);
eventConsumer = new H2OEventConsumer(this);
bus.register(eventConsumer);
H2OEventBus.publish(new H2OEvent(localMachineLocation.getURL(), DatabaseStates.DATABASE_STARTUP, localMachineLocation.getURL()));
keepAliveMessageThread = new KeepAliveMessageThread(localMachineLocation.getURL());
keepAliveMessageThread.start();
}
}
this.cipher = cipher;
final String lockMethodName = ci.getProperty("FILE_LOCK", null);
accessModeLog = ci.getProperty("ACCESS_MODE_LOG", "rw").toLowerCase();
accessModeData = ci.getProperty("ACCESS_MODE_DATA", "rw").toLowerCase();
autoServerMode = ci.getProperty("AUTO_SERVER", false);
if ("r".equals(accessModeData)) {
readOnly = true;
accessModeLog = "r";
}
fileLockMethod = FileLock.getFileLockMethod(lockMethodName);
if (fileLockMethod == FileLock.LOCK_SERIALIZED) {
writeDelay = SysProperties.MIN_WRITE_DELAY;
}
databaseURL = ci.getURL();
eventListener = ci.getDatabaseEventListenerObject();
ci.removeDatabaseEventListenerObject();
if (eventListener == null) {
String listener = ci.removeProperty("DATABASE_EVENT_LISTENER", null);
if (listener != null) {
listener = StringUtils.trim(listener, true, true, "'");
setEventListenerClass(listener);
}
}
final String log = ci.getProperty(SetTypes.LOG, null);
if (log != null) {
logIndexChanges = "2".equals(log);
}
final String ignoreSummary = ci.getProperty("RECOVER", null);
if (ignoreSummary != null) {
recovery = true;
}
final boolean closeAtVmShutdown = ci.getProperty("DB_CLOSE_ON_EXIT", true);
final int traceLevelFile = ci.getIntProperty(SetTypes.TRACE_LEVEL_FILE, TraceSystem.DEFAULT_TRACE_LEVEL_FILE);
final int traceLevelSystemOut = ci.getIntProperty(SetTypes.TRACE_LEVEL_SYSTEM_OUT, TraceSystem.DEFAULT_TRACE_LEVEL_SYSTEM_OUT);
cacheType = StringUtils.toUpperEnglish(ci.removeProperty("CACHE_TYPE", CacheLRU.TYPE_NAME));
openDatabase(traceLevelFile, traceLevelSystemOut, closeAtVmShutdown, ci, localMachineLocation);
if (!isManagementDB()) {
final boolean metaDataReplicationEnabled = Boolean.parseBoolean(databaseSettings.get("METADATA_REPLICATION_ENABLED"));
if (!Constants.IS_NON_SM_TEST && metaDataReplicationEnabled) {
metaDataReplicationThread.start();
}
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Started database at " + getID());
try {
final String fileSystemName = getFileSystemName(databaseName);
numonic = new NumonicReporter(databaseSettings.get("NUMONIC_MONITORING_FILE_LOCATION"), fileSystemName, getID(), systemTableRef, this, databaseSettings.get("NUMONIC_THRESHOLDS_FILE_LOCATION"));
if (Boolean.parseBoolean(databaseSettings.get("NUMONIC_MONITORING_ENABLED"))) {
numonic.start();
}
}
catch (final IOException e) {
ErrorHandling.exceptionError(e, "Failed to start numonic reporter for H2O.");
}
}
running = true;
connected = true;
}
/**
* Get the name of the filesystem that this database is storing data on (e.g. "C:\" or "/");
* @param databaseName
* @return
*/
private String getFileSystemName(final String databaseName) {
if (databaseName.indexOf(File.separator) >= 0) {
final String nameBeforeSlash = databaseName.substring(0, databaseName.indexOf(File.separator));
return nameBeforeSlash + File.separator;
}
else {
return null;
}
}
private H2OPropertiesWrapper setUpLocalDatabaseProperties(final DatabaseID localMachineLocation) {
final H2OPropertiesWrapper localSettings = H2OPropertiesWrapper.getWrapper(localMachineLocation);
try {
localSettings.loadProperties();
localSettings.setProperty(Settings.JDBC_PORT, localMachineLocation.getPort() + "");
localSettings.saveAndClose();
localSettings.loadProperties();
}
catch (final IOException e) {
try {
localSettings.createNewFile();
localSettings.loadProperties();
localSettings.setProperty(Settings.JDBC_PORT, localMachineLocation.getPort() + "");
localSettings.saveAndClose();
localSettings.loadProperties();
}
catch (final IOException e1) {
ErrorHandling.exceptionError(e1, "Failed to create properties file for database.");
}
}
return localSettings;
}
private void openDatabase(final int traceLevelFile, final int traceLevelSystemOut, final boolean closeAtVmShutdown, final ConnectionInfo ci, final DatabaseID localMachineLocation) throws SQLException {
try {
open(traceLevelFile, traceLevelSystemOut, ci, localMachineLocation);
if (closeAtVmShutdown) {
closeOnExit = new DatabaseCloser(this, 0, true);
try {
Runtime.getRuntime().addShutdownHook(closeOnExit);
}
catch (final IllegalStateException e) {
// shutdown in progress - just don't register the handler
// (maybe an application wants to write something into a
// database at shutdown time)
}
catch (final SecurityException e) {
// applets may not do that - ignore
}
}
}
catch (final Throwable e) {
ErrorHandling.exceptionError(e, "Error starting database. It will now shut down.");
if (traceSystem != null) {
if (e instanceof SQLException) {
final SQLException e2 = (SQLException) e;
if (e2.getErrorCode() != ErrorCode.DATABASE_ALREADY_OPEN_1) {
// only write if the database is not already in use
traceSystem.getTrace(Trace.DATABASE).error("opening " + databaseName, e);
}
}
traceSystem.close();
}
closeOpenFilesAndUnlock();
throw Message.convert(e);
}
}
public static void setInitialPowerOffCount(final int count) {
initialPowerOffCount = count;
}
public void setPowerOffCount(final int count) {
if (powerOffCount == -1) { return; }
powerOffCount = count;
}
/**
* Check if two values are equal with the current comparison mode.
*
* @param a
* the first value
* @param b
* the second value
* @return true if both objects are equal
*/
public boolean areEqual(final Value a, final Value b) throws SQLException {
return a.compareTo(b, compareMode) == 0;
}
/**
* Compare two values with the current comparison mode. The values may not be of the same type.
*
* @param a
* the first value
* @param b
* the second value
* @return 0 if both values are equal, -1 if the first value is smaller, and 1 otherwise
*/
public int compare(final Value a, final Value b) throws SQLException {
return a.compareTo(b, compareMode);
}
/**
* Compare two values with the current comparison mode. The values must be of the same type.
*
* @param a
* the first value
* @param b
* the second value
* @return 0 if both values are equal, -1 if the first value is smaller, and 1 otherwise
*/
@Override
public int compareTypeSave(final Value a, final Value b) throws SQLException {
return a.compareTypeSave(b, compareMode);
}
public long getModificationDataId() {
return modificationDataId;
}
private void reconnectModified(final boolean pending) {
if (readOnly || pending == reconnectChangePending || lock == null) { return; }
try {
if (pending) {
getTrace().debug("wait before writing");
Thread.sleep((int) (SysProperties.RECONNECT_CHECK_DELAY * 1.1));
}
lock.setProperty("modificationDataId", Long.toString(modificationDataId));
lock.setProperty("modificationMetaId", Long.toString(modificationMetaId));
lock.setProperty("changePending", pending ? "true" : null);
lock.save();
reconnectLastLock = lock.load();
reconnectChangePending = pending;
}
catch (final Exception e) {
getTrace().error("pending:" + pending, e);
}
}
public long getNextModificationDataId() {
return ++modificationDataId;
}
public long getModificationMetaId() {
return modificationMetaId;
}
public long getNextModificationMetaId() {
// if the meta data has been modified, the data is modified as well
// (because MetaTable returns modificationDataId)
modificationDataId++;
return modificationMetaId++;
}
public int getPowerOffCount() {
return powerOffCount;
}
@Override
public void checkPowerOff() throws SQLException {
if (powerOffCount == 0) { return; }
if (powerOffCount > 1) {
powerOffCount--;
return;
}
if (powerOffCount != -1) {
try {
powerOffCount = -1;
if (log != null) {
try {
stopWriter();
log.close();
}
catch (final SQLException e) {
// ignore
}
log = null;
}
if (fileData != null) {
try {
fileData.close();
}
catch (final SQLException e) {
// ignore
}
fileData = null;
}
if (fileIndex != null) {
try {
fileIndex.close();
}
catch (final SQLException e) {
// ignore
}
fileIndex = null;
}
if (pageStore != null) {
try {
pageStore.close();
}
catch (final SQLException e) {
// ignore
}
pageStore = null;
}
if (lock != null) {
stopServer();
if (fileLockMethod != FileLock.LOCK_SERIALIZED) {
// allow testing shutdown
lock.unlock();
}
lock = null;
}
}
catch (final Exception e) {
TraceSystem.traceThrowable(e);
}
}
Engine.getInstance().close(databaseName);
throw Message.getSQLException(ErrorCode.SIMULATED_POWER_OFF);
}
/**
* Check if a database with the given name exists.
*
* @param name
* the name of the database (including path)
* @return true if one exists
*/
public static boolean exists(final String name) {
return FileUtils.exists(name + Constants.SUFFIX_DATA_FILE);
}
/**
* Get the trace object for the given module.
*
* @param module
* the module name
* @return the trace object
*/
public Trace getTrace(final String module) {
return traceSystem.getTrace(module);
}
@Override
public FileStore openFile(final String name, final String mode, final boolean mustExist) throws SQLException {
if (mustExist && !FileUtils.exists(name)) { throw Message.getSQLException(ErrorCode.FILE_NOT_FOUND_1, name); }
final FileStore store = FileStore.open(this, name, mode, cipher, filePasswordHash);
try {
store.init();
}
catch (final SQLException e) {
store.closeSilently();
throw e;
}
return store;
}
/**
* Check if the file password hash is correct.
*
* @param cipher
* the cipher algorithm
* @param hash
* the hash code
* @return true if the cipher algorithm and the password match
*/
public boolean validateFilePasswordHash(final String cipher, final byte[] hash) throws SQLException {
if (!StringUtils.equals(cipher, this.cipher)) { return false; }
return ByteUtils.compareSecure(hash, filePasswordHash);
}
private void openFileData() throws SQLException {
fileData = new DiskFile(this, databaseName + Constants.SUFFIX_DATA_FILE, accessModeData, true, true, SysProperties.CACHE_SIZE_DEFAULT);
}
private void openFileIndex() throws SQLException {
fileIndex = new DiskFile(this, databaseName + Constants.SUFFIX_INDEX_FILE, accessModeData, false, logIndexChanges, SysProperties.CACHE_SIZE_INDEX_DEFAULT);
}
public DataPage getDataPage() {
return dummy;
}
private String parseDatabaseShortName() {
String n = databaseName;
if (n.endsWith(":")) {
n = null;
}
if (n != null) {
final StringTokenizer tokenizer = new StringTokenizer(n, "/\\:,;");
while (tokenizer.hasMoreTokens()) {
n = tokenizer.nextToken();
}
}
if (n == null || n.length() == 0) {
n = "UNNAMED";
}
return StringUtils.toUpperEnglish(n);
}
private synchronized void open(final int traceLevelFile, final int traceLevelSystemOut, final ConnectionInfo ci, final DatabaseID localMachineLocation) throws SQLException, StartupException {
boolean databaseExists = false; // whether the database already exists
// on disk. i.e. with .db.data files,
// etc.
if (persistent) {
if (SysProperties.PAGE_STORE) {
final String pageFileName = databaseName + Constants.SUFFIX_PAGE_FILE;
if (FileUtils.exists(pageFileName) && FileUtils.isReadOnly(pageFileName)) {
readOnly = true;
}
}
final String dataFileName = databaseName + Constants.SUFFIX_DATA_FILE;
databaseExists = FileUtils.exists(dataFileName);
if (databaseExists) {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Database already exists at: " + dataFileName);
}
else {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Database doesn't exist at: " + dataFileName);
}
if (FileUtils.exists(dataFileName)) {
// if it is already read-only because ACCESS_MODE_DATA=r
readOnly = readOnly | FileUtils.isReadOnly(dataFileName);
}
if (readOnly) {
traceSystem = new TraceSystem(null, false);
}
else {
traceSystem = new TraceSystem(databaseName + Constants.SUFFIX_TRACE_FILE, true);
}
traceSystem.setLevelFile(traceLevelFile);
traceSystem.setLevelSystemOut(traceLevelSystemOut);
traceSystem.getTrace(Trace.DATABASE).info("opening " + databaseName + " (build " + Constants.BUILD_ID + ")");
if (autoServerMode) {
if (readOnly || fileLockMethod == FileLock.LOCK_NO) { throw Message.getSQLException(ErrorCode.FEATURE_NOT_SUPPORTED); }
}
if (!readOnly && fileLockMethod != FileLock.LOCK_NO) {
lock = new FileLock(traceSystem, databaseName + Constants.SUFFIX_LOCK_FILE, Constants.LOCK_SLEEP);
lock.lock(fileLockMethod);
if (autoServerMode) {
startServer(lock.getUniqueId());
}
}
// wait until pending changes are written
isReconnectNeeded();
if (SysProperties.PAGE_STORE) {
final PageStore store = getPageStore();
store.recover();
}
if (FileUtils.exists(dataFileName)) {
lobFilesInDirectories &= !ValueLob.existsLobFile(getDatabasePath());
lobFilesInDirectories |= FileUtils.exists(databaseName + Constants.SUFFIX_LOBS_DIRECTORY);
}
dummy = DataPage.create(this, 0);
deleteOldTempFiles();
log = new LogSystem(this, databaseName, readOnly, accessModeLog, pageStore);
if (pageStore == null) {
openFileData();
log.open();
openFileIndex();
log.recover();
fileData.init();
try {
fileIndex.init();
}
catch (final Exception e) {
if (recovery) {
traceSystem.getTrace(Trace.DATABASE).error("opening index", e);
final ArrayList<DbObject> list = new ArrayList<DbObject>(storageMap.values());
for (int i = 0; i < list.size(); i++) {
final Storage s = (Storage) list.get(i);
if (s.getDiskFile() == fileIndex) {
removeStorage(s.getId(), fileIndex);
}
}
fileIndex.delete();
openFileIndex();
}
else {
throw Message.convert(e);
}
}
}
reserveLobFileObjectIds();
writer = WriterThread.create(this, writeDelay);
}
else {
traceSystem = new TraceSystem(null, false);
log = new LogSystem(null, null, false, null, null);
}
systemUser = new User(this, 0, Constants.DBA_NAME, true);
h2oSchemaUser = new User(this, 1, "H2O", true);
h2oSystemUser = new User(this, 1, "system", true);
mainSchema = new Schema(this, 0, Constants.SCHEMA_MAIN, systemUser, true);
infoSchema = new Schema(this, -1, Constants.SCHEMA_INFORMATION, systemUser, true);
schemas.put(mainSchema.getName(), mainSchema);
schemas.put(infoSchema.getName(), infoSchema);
publicRole = new Role(this, 0, Constants.PUBLIC_ROLE_NAME, true);
roles.put(Constants.PUBLIC_ROLE_NAME, publicRole);
systemUser.setAdmin(true);
h2oSchemaUser.setAdmin(true);
h2oSystemUser.setAdmin(true);
systemSession = new Session(this, systemUser);
h2oSession = new Session(this, h2oSchemaUser);
h2oSystemSession = new Session(this, h2oSystemUser);
final ObjectArray cols = new ObjectArray();
final Column columnId = new Column("ID", Value.INT);
columnId.setNullable(false);
cols.add(columnId);
cols.add(new Column("HEAD", Value.INT));
cols.add(new Column("TYPE", Value.INT));
cols.add(new Column("SQL", Value.STRING));
int headPos = 0;
if (pageStore != null) {
headPos = pageStore.getMetaTableHeadPos();
}
meta = mainSchema.createTable("SYS", 0, cols, persistent, false, headPos);
tableMap.put(0, meta);
final IndexColumn[] pkCols = IndexColumn.wrap(new Column[]{columnId});
metaIdIndex = meta.addIndex(systemSession, "SYS_ID", 0, pkCols, IndexType.createPrimaryKey(false, false), Index.EMPTY_HEAD, null);
objectIds.set(0);
// there could be views on system tables, so they must be added first
for (int i = 0; i < MetaTable.getMetaTableTypeCount(); i++) {
addMetaData(i);
}
starting = true;
/*
* H2O STARTUP CODE FOR System Table, TABLE INSTANITATION
*/
if (!isManagementDB()) { // don't run this code with the TCP server management DB
databaseRemote.connectToDatabaseSystem(h2oSystemSession, databaseSettings);
// Establish Proxies
startTableManagerInstanceServer();
startDatabaseInstanceServer();
createMetaDataReplicationThread(); //Must be executed after call to databaseRemote because of getLocalDatabaseInstanceInWrapper() call.
}
/*
* ###################################################################### ###### END OF System Table STARTUP CODE At this point in
* the code this database instance will be connected to a System Table, so when tables are generated (below), it will be possible
* for them to re-instantiate Table Managers where possible. ######################################################################
* ######
*/
final Cursor cursor = metaIdIndex.find(systemSession, null, null);
// first, create all function aliases and sequences because
// they might be used in create table / view / constraints and so on
final ObjectArray records = new ObjectArray();
while (cursor.next()) {
final MetaRecord rec = new MetaRecord(cursor.get());
objectIds.set(rec.getId());
records.add(rec);
}
MetaRecord.sort(records);
if (!isManagementDB() && databaseExists) {
/*
* Create or connect to a new System Table instance if this node already has tables on it.
*/
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Database already exists. No need to recreate the System Table.");
createSystemTableOrGetReferenceToIt(true, systemTableRef.isSystemTableLocal(), false);
}
if (records.size() > 0) {
final TableProxyManager proxyManager = new TableProxyManager(this, systemSession, true);
for (int i = 0; i < records.size(); i++) {
final MetaRecord rec = (MetaRecord) records.get(i);
if (rec.getSQL().startsWith("CREATE FORCE LINKED TABLE")) {
continue;
}
- rec.execute(this, systemSession, eventListener, proxyManager);
+ try {
+ rec.execute(this, systemSession, eventListener, proxyManager);
+ }
+ catch (final Exception e) {
+ ErrorHandling.errorNoEvent("Failed to execute meta-record: " + rec.getSQL());
+ }
}
proxyManager.finishTransaction(true, true, this);
}
if (!isManagementDB()) {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, " Executed meta-records.");
}
// try to recompile the views that are invalid
recompileInvalidViews(systemSession);
starting = false;
addDefaultSetting(systemSession, SetTypes.DEFAULT_LOCK_TIMEOUT, null, Constants.INITIAL_LOCK_TIMEOUT);
addDefaultSetting(systemSession, SetTypes.DEFAULT_TABLE_TYPE, null, Constants.DEFAULT_TABLE_TYPE);
addDefaultSetting(systemSession, SetTypes.CACHE_SIZE, null, SysProperties.CACHE_SIZE_DEFAULT);
addDefaultSetting(systemSession, SetTypes.CLUSTER, Constants.CLUSTERING_DISABLED, 0);
addDefaultSetting(systemSession, SetTypes.WRITE_DELAY, null, Constants.DEFAULT_WRITE_DELAY);
addDefaultSetting(systemSession, SetTypes.CREATE_BUILD, null, Constants.BUILD_ID);
if (!readOnly) {
removeUnusedStorages(systemSession);
}
systemSession.commit(true);
traceSystem.getTrace(Trace.DATABASE).info("opened " + databaseName);
if (!isManagementDB() && (!databaseExists || !systemTableRef.isSystemTableLocal())) {
// don't run this code with the TCP server management DB
try {
createH2OTables(false, databaseExists);
}
catch (final Exception e) {
ErrorHandling.exceptionError(e, "Error creating H2O tables.");
}
// called here, because at this point the system is ready to replicate TM state.
databaseRemote.setAsReadyToReplicateMetaData(metaDataReplicaManager);
}
else if (!isManagementDB() && databaseExists && systemTableRef.isSystemTableLocal()) {
/*
* This is the System Table. Reclaim previously held state.
*/
try {
createH2OTables(true, databaseExists);
systemTableRef.getSystemTable().recreateInMemorySystemTableFromLocalPersistedState();
// called here, because at this point the system is ready to replicate TM state.
databaseRemote.setAsReadyToReplicateMetaData(metaDataReplicaManager);
Diagnostic.traceNoEvent(DiagnosticLevel.FINAL, "Re-created System Table state.");
}
catch (final Exception e) {
- Diagnostic.trace(DiagnosticLevel.FULL, "error creating H2O tables");
+ ErrorHandling.exceptionError(e, "Error creating H2O tables.");
}
}
}
public void startDatabaseInstanceServer() {
int preferredDatabaseInstancePort = Integer.parseInt(databaseSettings.get("DATABASE_INSTANCE_SERVER_PORT"));
preferredDatabaseInstancePort = H2ONetUtils.getInactiveTCPPort(preferredDatabaseInstancePort);
database_instance_server = new DatabaseInstanceServer(getLocalDatabaseInstance(), preferredDatabaseInstancePort, getRemoteInterface().getApplicationRegistryIDForLocalDatabase());
Diagnostic.traceNoEvent(DiagnosticLevel.FULL, getID() + ": Database instance server started on port " + preferredDatabaseInstancePort);
try {
database_instance_server.start(true); // true means: allow registry entry for this database ID to be overwritten
Diagnostic.traceNoEvent(DiagnosticLevel.FULL, "Database Instance Server started for database " + getID() + " on port " + preferredDatabaseInstancePort + ".");
}
catch (final Exception e) {
ErrorHandling.hardExceptionError(e, "Couldn't start database instance server.");
}
databaseRemote.setDatabaseInstanceServerPort(preferredDatabaseInstancePort);
}
public void startTableManagerInstanceServer() {
int preferredTableManagerPort = Integer.parseInt(databaseSettings.get("TABLE_MANAGER_SERVER_PORT"));
preferredTableManagerPort = H2ONetUtils.getInactiveTCPPort(preferredTableManagerPort);
table_manager_instance_server = new TableManagerInstanceServer(preferredTableManagerPort);
try {
table_manager_instance_server.start();
Diagnostic.traceNoEvent(DiagnosticLevel.FULL, "Table Manager Instance Server started for database " + getID() + " on port " + preferredTableManagerPort + ".");
}
catch (final Exception e) {
ErrorHandling.hardExceptionError(e, "Couldn't start table manager instance server.");
}
}
public void createMetaDataReplicationThread() {
final boolean metaDataReplicationEnabled = Boolean.parseBoolean(databaseSettings.get("METADATA_REPLICATION_ENABLED"));
final int systemTableReplicationFactor = Integer.parseInt(databaseSettings.get("SYSTEM_TABLE_REPLICATION_FACTOR"));
final int tableManagerReplicationFactor = Integer.parseInt(databaseSettings.get("TABLE_MANAGER_REPLICATION_FACTOR"));
final int replicationThreadSleepTime = Integer.parseInt(databaseSettings.get("METADATA_REPLICATION_THREAD_SLEEP_TIME"));
metaDataReplicaManager = new MetaDataReplicaManager(metaDataReplicationEnabled, systemTableReplicationFactor, tableManagerReplicationFactor, getLocalDatabaseInstanceInWrapper(), this);
metaDataReplicationThread = new MetaDataReplicationThread(metaDataReplicaManager, systemTableRef, this, replicationThreadSleepTime);
metaDataReplicationThread.setName("MetaDataReplicationThread");
}
private void createSystemTableOrGetReferenceToIt(final boolean databaseExists, final boolean persistedTablesExist, final boolean createTables) throws SQLException {
if (systemTableRef.isSystemTableLocal()) {
// Create the System Table tables and immediately add local tables to this manager.
SystemTable systemTable = null;
try {
systemTable = new SystemTable(this, createTables);
}
catch (final Exception e) {
e.printStackTrace();
ErrorHandling.hardError(e.getMessage());
}
startSystemTableServer(systemTable);
systemTableRef.setSystemTable(systemTable);
final boolean successfullyCreated = databaseRemote.commitSystemTableCreation();
if (successfullyCreated) {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Created new System Table locally.");
}
else {
//In the case that another instance has created a system table at the same time, try to get a refrence to this:
connectToRemoteSystemTable();
}
}
else {
connectToRemoteSystemTable();
}
}
/**
* Try to create a connection to an active remote system table.
* @throws SQLException thrown if no connection could be made.
*/
public void connectToRemoteSystemTable() throws SQLException {
systemTableRef.findSystemTable();
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Obtained reference to existing System Table.");
}
public void startSystemTableServer(final ISystemTableMigratable newSystemTable) {
int preferredSystemTablePort = Integer.parseInt(databaseSettings.get("SYSTEM_TABLE_SERVER_PORT"));
preferredSystemTablePort = H2ONetUtils.getInactiveTCPPort(preferredSystemTablePort);
system_table_server = new SystemTableServer(newSystemTable, preferredSystemTablePort); // added if we become a system table.
try {
system_table_server.start();
}
catch (final Exception e) {
ErrorHandling.hardExceptionError(e, "Couldn't start system table instance server.");
}
}
public DatabaseID getID() {
return databaseRemote.getLocalMachineLocation();
}
public Schema getMainSchema() {
return mainSchema;
}
private void startServer(final String key) throws SQLException {
server = Server.createTcpServer(new String[]{"-tcpPort", "0", "-tcpAllowOthers", "true", "-key", key, databaseName});
server.start();
final String address = NetUtils.getLocalAddress() + ":" + server.getPort();
Diagnostic.traceNoEvent(DiagnosticLevel.FINAL, "Server started on: " + address);
lock.setProperty("server", address);
lock.save();
}
private void stopServer() {
if (server != null) {
final Server s = server;
// avoid calling stop recursively
// because stopping the server will
// try to close the database as well
server = null;
s.stop();
}
}
private void recompileInvalidViews(final Session session) {
boolean recompileSuccessful;
do {
recompileSuccessful = false;
final Set<Table> alltables = getAllReplicas();
for (final Table table : alltables) {
if (table instanceof TableView) {
final TableView view = (TableView) table;
if (view.getInvalid()) {
try {
view.recompile(session);
}
catch (final SQLException e) {
// ignore
}
if (!view.getInvalid()) {
recompileSuccessful = true;
}
}
}
}
}
while (recompileSuccessful);
// when opening a database, views are initialized before indexes,
// so they may not have the optimal plan yet
// this is not a problem, it is just nice to see the newest plan
final Set<Table> allTables = getAllReplicas();
for (final Table table : allTables) {
if (table instanceof TableView) {
final TableView view = (TableView) table;
if (!view.getInvalid()) {
try {
view.recompile(systemSession);
}
catch (final SQLException e) {
// ignore
}
}
}
}
}
private void removeUnusedStorages(final Session session) throws SQLException {
if (persistent) {
final ObjectArray storages = getAllStorages();
for (int i = 0; i < storages.size(); i++) {
final Storage storage = (Storage) storages.get(i);
if (storage != null && storage.getRecordReader() == null) {
storage.truncate(session);
}
}
}
}
private void addDefaultSetting(final Session session, final int type, final String stringValue, final int intValue) throws SQLException {
if (readOnly) { return; }
final String name = SetTypes.getTypeName(type);
if (settings.get(name) == null) {
final Setting setting = new Setting(this, allocateObjectId(false, true), name);
if (stringValue == null) {
setting.setIntValue(intValue);
}
else {
setting.setStringValue(stringValue);
}
addDatabaseObject(session, setting);
}
}
/**
* Remove the storage object from the file.
*
* @param id
* the storage id
* @param file
* the file
*/
public void removeStorage(final int id, final DiskFile file) {
if (SysProperties.CHECK) {
final Storage s = (Storage) storageMap.get(id);
if (s == null || s.getDiskFile() != file) {
Message.throwInternalError();
}
}
storageMap.remove(id);
}
/**
* Get the storage object for the given file. An new object is created if required.
*
* @param id
* the storage id
* @param file
* the file
* @return the storage object
*/
public Storage getStorage(final int id, final DiskFile file) {
Storage storage = (Storage) storageMap.get(id);
if (storage != null) {
if (SysProperties.CHECK && storage.getDiskFile() != file) {
Message.throwInternalError();
}
}
else {
storage = new Storage(this, file, null, id);
storageMap.put(id, storage);
}
return storage;
}
private void addMetaData(final int type) throws SQLException {
final MetaTable m = new MetaTable(infoSchema, -1 - type, type);
infoSchema.add(m);
}
private synchronized void addMeta(final Session session, final DbObject obj) throws SQLException {
final int id = obj.getId();
if (id > 0 && !starting && !obj.getTemporary()) {
final Row r = meta.getTemplateRow();
final MetaRecord rec = new MetaRecord(obj);
rec.setRecord(r);
objectIds.set(id);
meta.lock(session, true, true);
meta.addRow(session, r);
}
if (SysProperties.PAGE_STORE && id > 0) {
databaseObjects.put(ObjectUtils.getInteger(id), obj);
}
}
/**
* Remove the given object from the meta data.
*
* @param session
* the session
* @param id
* the id of the object to remove
*/
public synchronized void removeMeta(final Session session, final int id) throws SQLException {
if (id > 0 && !starting) {
final SearchRow r = meta.getTemplateSimpleRow(false);
r.setValue(0, ValueInt.get(id));
final Cursor cursor = metaIdIndex.find(session, r, r);
if (cursor.next()) {
final Row found = cursor.get();
meta.lock(session, true, true);
meta.removeRow(session, found);
objectIds.clear(id);
if (SysProperties.CHECK) {
checkMetaFree(session, id);
}
}
}
if (SysProperties.PAGE_STORE) {
databaseObjects.remove(ObjectUtils.getInteger(id));
}
}
private HashMap<String, DbObject> getMap(final int type) {
switch (type) {
case DbObject.USER:
return users;
case DbObject.SETTING:
return settings;
case DbObject.ROLE:
return roles;
case DbObject.RIGHT:
return rights;
case DbObject.FUNCTION_ALIAS:
return functionAliases;
case DbObject.SCHEMA:
return schemas;
case DbObject.USER_DATATYPE:
return userDataTypes;
case DbObject.COMMENT:
return comments;
case DbObject.AGGREGATE:
return aggregates;
default:
throw Message.throwInternalError("type=" + type);
}
}
/**
* Add a schema object to the database.
*
* @param session
* the session
* @param obj
* the object to add
*/
public synchronized void addSchemaObject(final Session session, final SchemaObject obj) throws SQLException {
final int id = obj.getId();
if (id > 0 && !starting) {
checkWritingAllowed();
}
obj.getSchema().add(obj);
addMeta(session, obj);
if (obj instanceof TableData) {
tableMap.put(id, obj);
}
}
/**
* Add an object to the database.
*
* @param session
* the session
* @param obj
* the object to add
*/
public synchronized void addDatabaseObject(final Session session, final DbObject obj) throws SQLException {
final int id = obj.getId();
if (id > 0 && !starting) {
checkWritingAllowed();
}
final HashMap<String, DbObject> map = getMap(obj.getType());
if (obj.getType() == DbObject.USER) {
final User user = (User) obj;
if (user.getAdmin() && systemUser.getName().equals(Constants.DBA_NAME)) {
systemUser.rename(user.getName());
}
}
final String name = obj.getName();
if (SysProperties.CHECK && map.get(name) != null) {
Message.throwInternalError("object already exists");
}
addMeta(session, obj);
map.put(name, obj);
}
/**
* Get the user defined aggregate function if it exists, or null if not.
*
* @param name
* the name of the user defined aggregate function
* @return the aggregate function or null
*/
public UserAggregate findAggregate(final String name) {
return (UserAggregate) aggregates.get(name);
}
/**
* Get the comment for the given database object if one exists, or null if not.
*
* @param object
* the database object
* @return the comment or null
*/
public Comment findComment(final DbObject object) {
if (object.getType() == DbObject.COMMENT) { return null; }
final String key = Comment.getKey(object);
return (Comment) comments.get(key);
}
/**
* Get the user defined function if it exists, or null if not.
*
* @param name
* the name of the user defined function
* @return the function or null
*/
public FunctionAlias findFunctionAlias(final String name) {
return (FunctionAlias) functionAliases.get(name);
}
/**
* Get the role if it exists, or null if not.
*
* @param roleName
* the name of the role
* @return the role or null
*/
public Role findRole(final String roleName) {
return (Role) roles.get(roleName);
}
/**
* Get the schema if it exists, or null if not.
*
* @param schemaName
* the name of the schema
* @return the schema or null
*/
public Schema findSchema(final String schemaName) {
return (Schema) schemas.get(schemaName);
}
/**
* Get the setting if it exists, or null if not.
*
* @param name
* the name of the setting
* @return the setting or null
*/
public Setting findSetting(final String name) {
return (Setting) settings.get(name);
}
/**
* Get the user if it exists, or null if not.
*
* @param name
* the name of the user
* @return the user or null
*/
public User findUser(final String name) {
return (User) users.get(name);
}
/**
* Get the user defined data type if it exists, or null if not.
*
* @param name
* the name of the user defined data type
* @return the user defined data type or null
*/
public UserDataType findUserDataType(final String name) {
return (UserDataType) userDataTypes.get(name);
}
/**
* Get user with the given name. This method throws an exception if the user does not exist.
*
* @param name
* the user name
* @return the user
* @throws SQLException
* if the user does not exist
*/
public User getUser(final String name) throws SQLException {
User user = findUser(name);
// H2O bug fix (where admin user is not found on startup queries
if (user == null) {
user = systemUser;
}
if (user == null) { throw Message.getSQLException(ErrorCode.USER_NOT_FOUND_1, name); }
return user;
}
/**
* Create a session for the given user.
*
* @param user
* the user
* @return the session
* @throws SQLException
* if the database is in exclusive mode
*/
public synchronized Session createSession(final User user) throws SQLException {
if (exclusiveSession != null) { throw Message.getSQLException(ErrorCode.DATABASE_IS_IN_EXCLUSIVE_MODE); }
final Session session = new Session(this, user);
userSessions.add(session);
traceSystem.getTrace(Trace.SESSION).info("connecting #" + session.getSessionId() + " to " + databaseName);
if (delayedCloser != null) {
delayedCloser.reset();
delayedCloser = null;
}
return session;
}
/**
* Remove a session. This method is called after the user has disconnected.
*
* @param session
* the session
*/
public synchronized void removeSession(final Session session) {
if (session != null) {
if (exclusiveSession == session) {
exclusiveSession = null;
}
userSessions.remove(session);
if (session != systemSession) {
traceSystem.getTrace(Trace.SESSION).info("disconnecting #" + session.getSessionId());
}
}
if (userSessions.size() == 0 && session != systemSession) {
if (closeDelay == 0) {
close(false);
}
else if (closeDelay < 0) {
return;
}
else {
delayedCloser = new DatabaseCloser(this, closeDelay * 1000, false);
delayedCloser.setName("H2 Close Delay " + getShortName());
delayedCloser.setDaemon(true);
delayedCloser.start();
}
}
if (session != systemSession && session != null) {
traceSystem.getTrace(Trace.SESSION).info("disconnected #" + session.getSessionId());
}
}
/**
* Close the database.
*
* @param fromShutdownHook true if this method is called from the shutdown hook
*/
public synchronized void close(final boolean fromShutdownHook) {
if (closing) { return; }
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, getID().getURL());
closing = true;
stopServer();
if (!isManagementDB() && !fromShutdownHook) {
H2OEventBus.publish(new H2OEvent(getID().getURL(), DatabaseStates.DATABASE_SHUTDOWN, null));
metaDataReplicationThread.setRunning(false);
running = false;
removeLocalDatabaseInstance();
try {
table_manager_instance_server.stop();
if (system_table_server != null) {
system_table_server.stop();
}
database_instance_server.stop();
}
catch (final Exception e) {
ErrorHandling.exceptionErrorNoEvent(e, "Failed to shutdown one of the H2O servers on database shutdown.");
}
if (numonic != null) {
numonic.shutdown();
}
}
if (userSessions.size() > 0) {
if (!fromShutdownHook) { return; }
traceSystem.getTrace(Trace.DATABASE).info("closing " + databaseName + " from shutdown hook");
final Session[] all = new Session[userSessions.size()];
userSessions.toArray(all);
for (final Session s : all) {
try {
// Must roll back, otherwise the session is removed and the log file that contains its uncommitted operations as well.
s.rollback();
s.close();
}
catch (final SQLException e) {
traceSystem.getTrace(Trace.SESSION).error("disconnecting #" + s.getSessionId(), e);
}
}
}
if (log != null) {
log.setDisabled(false);
}
traceSystem.getTrace(Trace.DATABASE).info("closing " + databaseName);
if (eventListener != null) {
// allow the event listener to connect to the database
closing = false;
final DatabaseEventListener e = eventListener;
// set it to null, to make sure it's called only once
eventListener = null;
e.closingDatabase();
if (userSessions.size() > 0) {
// if a connection was opened, we can't close the database
return;
}
closing = true;
}
try {
if (systemSession != null) {
final Set<Table> alltables = getAllReplicas();
for (final Table table : alltables) {
table.close(systemSession);
}
final ObjectArray sequences = getAllSchemaObjects(DbObject.SEQUENCE);
for (int i = 0; i < sequences.size(); i++) {
final Sequence sequence = (Sequence) sequences.get(i);
sequence.close();
}
final ObjectArray triggers = getAllSchemaObjects(DbObject.TRIGGER);
for (int i = 0; i < triggers.size(); i++) {
final TriggerObject trigger = (TriggerObject) triggers.get(i);
trigger.close();
}
meta.close(systemSession);
indexSummaryValid = true;
}
}
catch (final SQLException e) {
traceSystem.getTrace(Trace.DATABASE).error("close", e);
}
// remove all session variables
if (persistent) {
try {
ValueLob.removeAllForTable(this, ValueLob.TABLE_ID_SESSION_VARIABLE);
}
catch (final SQLException e) {
traceSystem.getTrace(Trace.DATABASE).error("close", e);
}
}
tempFileDeleter.deleteAll();
try {
closeOpenFilesAndUnlock();
}
catch (final SQLException e) {
traceSystem.getTrace(Trace.DATABASE).error("close", e);
}
traceSystem.getTrace(Trace.DATABASE).info("closed");
traceSystem.close();
if (closeOnExit != null) {
closeOnExit.reset();
try {
Runtime.getRuntime().removeShutdownHook(closeOnExit);
}
catch (final IllegalStateException e) {
// ignore
}
catch (final SecurityException e) {
// applets may not do that - ignore
}
closeOnExit = null;
}
Engine.getInstance().close(databaseName);
if (deleteFilesOnDisconnect && persistent) {
deleteFilesOnDisconnect = false;
try {
final String directory = FileUtils.getParent(databaseName);
final String name = FileUtils.getFileName(databaseName);
DeleteDbFiles.execute(directory, name, true);
}
catch (final Exception e) {
// ignore (the trace is closed already)
}
}
closing = false;
}
private void stopWriter() {
if (writer != null) {
try {
writer.stopThread();
}
catch (final SQLException e) {
traceSystem.getTrace(Trace.DATABASE).error("close", e);
}
writer = null;
}
}
private synchronized void closeOpenFilesAndUnlock() throws SQLException {
if (log != null) {
stopWriter();
try {
log.close();
}
catch (final Throwable e) {
traceSystem.getTrace(Trace.DATABASE).error("close", e);
}
log = null;
}
if (pageStore != null) {
pageStore.checkpoint();
}
closeFiles();
if (persistent && lock == null && fileLockMethod != FileLock.LOCK_NO) {
// everything already closed (maybe in checkPowerOff)
// don't delete temp files in this case because
// the database could be open now (even from within another process)
return;
}
if (persistent) {
deleteOldTempFiles();
}
if (systemSession != null) {
systemSession.close();
systemSession = null;
}
if (lock != null) {
lock.unlock();
lock = null;
}
}
private void closeFiles() {
try {
if (fileData != null) {
fileData.close();
fileData = null;
}
if (fileIndex != null) {
fileIndex.close();
fileIndex = null;
}
if (pageStore != null) {
pageStore.close();
pageStore = null;
}
}
catch (final SQLException e) {
traceSystem.getTrace(Trace.DATABASE).error("close", e);
}
storageMap.clear();
}
private void checkMetaFree(final Session session, final int id) throws SQLException {
final SearchRow r = meta.getTemplateSimpleRow(false);
r.setValue(0, ValueInt.get(id));
final Cursor cursor = metaIdIndex.find(session, r, r);
if (cursor.next()) {
Message.throwInternalError();
}
}
@Override
public synchronized int allocateObjectId(boolean needFresh, final boolean dataFile) {
// TODO refactor: use hash map instead of bit field for object ids
needFresh = true;
int i;
if (needFresh) {
i = objectIds.getLastSetBit() + 1;
if ((i & 1) != (dataFile ? 1 : 0)) {
i++;
}
while (storageMap.get(i) != null || objectIds.get(i)) {
i++;
if ((i & 1) != (dataFile ? 1 : 0)) {
i++;
}
}
}
else {
i = objectIds.nextClearBit(0);
}
if (SysProperties.CHECK && objectIds.get(i)) {
Message.throwInternalError();
}
objectIds.set(i);
return i;
}
public ObjectArray getAllAggregates() {
return new ObjectArray(aggregates.values());
}
public ObjectArray getAllComments() {
return new ObjectArray(comments.values());
}
public ObjectArray getAllFunctionAliases() {
return new ObjectArray(functionAliases.values());
}
public int getAllowLiterals() {
if (starting) { return Constants.ALLOW_LITERALS_ALL; }
return allowLiterals;
}
public ObjectArray getAllRights() {
return new ObjectArray(rights.values());
}
public ObjectArray getAllRoles() {
return new ObjectArray(roles.values());
}
/**
* Get all schema objects of the given type.
*
* @param type
* the object type
* @return all objects of that type
*/
public ObjectArray getAllSchemaObjects(final int type) {
final ObjectArray list = new ObjectArray();
for (final DbObject dbObject : schemas.values()) {
final Schema schema = (Schema) dbObject;
list.addAll(schema.getAll(type));
}
return list;
}
/**
* Get all tables. Replaces the getAllSchemaObjects method for this particular call.
*
* @param type
* the object type
* @return all objects of that type
*/
public Set<ReplicaSet> getAllTables() {
final Set<ReplicaSet> list = new HashSet<ReplicaSet>();
for (final DbObject dbObject : schemas.values()) {
final Schema schema = (Schema) dbObject;
list.addAll(schema.getTablesAndViews().values());
}
return list;
}
/**
* Get every single table instance, including replicas for the same table.
*
* @return
*/
public Set<Table> getAllReplicas() {
final Set<ReplicaSet> allReplicaSets = getAllTables();
final Set<Table> alltables = new HashSet<Table>();
for (final ReplicaSet tableSet : allReplicaSets) {
alltables.addAll(tableSet.getAllCopies());
}
return alltables;
}
public ObjectArray getAllSchemas() {
return new ObjectArray(schemas.values());
}
public ObjectArray getAllSettings() {
return new ObjectArray(settings.values());
}
public ObjectArray getAllStorages() {
return new ObjectArray(storageMap.values());
}
public ObjectArray getAllUserDataTypes() {
return new ObjectArray(userDataTypes.values());
}
public ObjectArray getAllUsers() {
return new ObjectArray(users.values());
}
public String getCacheType() {
return cacheType;
}
@Override
public int getChecksum(final byte[] data, int start, final int end) {
int x = 0;
while (start < end) {
x += data[start++];
}
return x;
}
public String getCluster() {
return cluster;
}
public CompareMode getCompareMode() {
return compareMode;
}
@Override
public String getDatabasePath() {
if (persistent) { return FileUtils.getAbsolutePath(databaseName); }
return null;
}
public String getShortName() {
return databaseShortName;
}
public String getName() {
return databaseName;
}
public LogSystem getLog() {
return log;
}
/**
* Get all sessions that are currently connected to the database.
*
* @param includingSystemSession
* if the system session should also be included
* @return the list of sessions
*/
public Session[] getSessions(final boolean includingSystemSession) {
final ArrayList<Session> list = new ArrayList<Session>(userSessions);
if (includingSystemSession && systemSession != null) {
list.add(systemSession);
}
final Session[] array = new Session[list.size()];
list.toArray(array);
return array;
}
/**
* Update an object in the system table.
*
* @param session
* the session
* @param obj
* the database object
*/
public synchronized void update(final Session session, final DbObject obj) throws SQLException {
final int id = obj.getId();
removeMeta(session, id);
addMeta(session, obj);
}
/**
* Rename a schema object.
*
* @param session
* the session
* @param obj
* the object
* @param newName
* the new name
*/
public synchronized void renameSchemaObject(final Session session, final SchemaObject obj, final String newName) throws SQLException {
checkWritingAllowed();
obj.getSchema().rename(obj, newName);
updateWithChildren(session, obj);
}
private synchronized void updateWithChildren(final Session session, final DbObject obj) throws SQLException {
final ObjectArray list = obj.getChildren();
final Comment comment = findComment(obj);
if (comment != null) {
Message.throwInternalError();
}
update(session, obj);
// remember that this scans only one level deep!
for (int i = 0; list != null && i < list.size(); i++) {
final DbObject o = (DbObject) list.get(i);
if (o.getCreateSQL() != null) {
update(session, o);
}
}
}
/**
* Rename a database object.
*
* @param session
* the session
* @param obj
* the object
* @param newName
* the new name
*/
public synchronized void renameDatabaseObject(final Session session, final DbObject obj, final String newName) throws SQLException {
checkWritingAllowed();
final int type = obj.getType();
final HashMap<String, DbObject> map = getMap(type);
if (SysProperties.CHECK) {
if (!map.containsKey(obj.getName())) {
Message.throwInternalError("not found: " + obj.getName());
}
if (obj.getName().equals(newName) || map.containsKey(newName)) {
Message.throwInternalError("object already exists: " + newName);
}
}
obj.checkRename();
final int id = obj.getId();
removeMeta(session, id);
map.remove(obj.getName());
obj.rename(newName);
map.put(newName, obj);
updateWithChildren(session, obj);
}
@Override
public String createTempFile() throws SQLException {
try {
final boolean inTempDir = readOnly;
String name = databaseName;
if (!persistent) {
name = FileSystem.PREFIX_MEMORY + name;
}
return FileUtils.createTempFile(name, Constants.SUFFIX_TEMP_FILE, true, inTempDir);
}
catch (final IOException e) {
throw Message.convertIOException(e, databaseName);
}
}
private void reserveLobFileObjectIds() throws SQLException {
final String prefix = FileUtils.normalize(databaseName) + ".";
final String path = FileUtils.getParent(databaseName);
final String[] list = FileUtils.listFiles(path);
for (final String element : list) {
String name = element;
if (name.endsWith(Constants.SUFFIX_LOB_FILE) && FileUtils.fileStartsWith(name, prefix)) {
name = name.substring(prefix.length());
name = name.substring(0, name.length() - Constants.SUFFIX_LOB_FILE.length());
final int dot = name.indexOf('.');
if (dot >= 0) {
final String id = name.substring(dot + 1);
final int objectId = Integer.parseInt(id);
objectIds.set(objectId);
}
}
}
}
private void deleteOldTempFiles() throws SQLException {
final String path = FileUtils.getParent(databaseName);
final String prefix = FileUtils.normalize(databaseName);
final String[] list = FileUtils.listFiles(path);
for (final String name : list) {
if (name.endsWith(Constants.SUFFIX_TEMP_FILE) && FileUtils.fileStartsWith(name, prefix)) {
// can't always delete the files, they may still be open
FileUtils.tryDelete(name);
}
}
}
/**
* Get or create the specified storage object.
*
* @param reader
* the record reader
* @param id
* the object id
* @param dataFile
* true if the data is in the data file
* @return the storage
*/
public Storage getStorage(final RecordReader reader, final int id, final boolean dataFile) {
DiskFile file;
if (dataFile) {
file = fileData;
}
else {
file = fileIndex;
}
final Storage storage = getStorage(id, file);
storage.setReader(reader);
return storage;
}
/**
* Get the schema. If the schema does not exist, an exception is thrown.
*
* @param schemaName
* the name of the schema
* @return the schema
* @throws SQLException
* no schema with that name exists
*/
public Schema getSchema(final String schemaName) throws SQLException {
final Schema schema = findSchema(schemaName);
if (schema == null) { throw Message.getSQLException(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName); }
return schema;
}
/**
* Remove the object from the database.
*
* @param session
* the session
* @param obj
* the object to remove
*/
public synchronized void removeDatabaseObject(final Session session, final DbObject obj) throws SQLException {
checkWritingAllowed();
final String objName = obj.getName();
final int type = obj.getType();
final HashMap<String, DbObject> map = getMap(type);
if (SysProperties.CHECK && !map.containsKey(objName)) {
Message.throwInternalError("not found: " + objName);
}
final Comment comment = findComment(obj);
if (comment != null) {
removeDatabaseObject(session, comment);
}
final int id = obj.getId();
obj.removeChildrenAndResources(session);
map.remove(objName);
removeMeta(session, id);
}
/**
* Get the first table that depends on this object.
*
* @param obj
* the object to find
* @param except
* the table to exclude (or null)
* @return the first dependent table, or null
*/
public ReplicaSet getDependentTable(final SchemaObject obj, final Table except) {
switch (obj.getType()) {
case DbObject.COMMENT:
case DbObject.CONSTRAINT:
case DbObject.INDEX:
case DbObject.RIGHT:
case DbObject.TRIGGER:
case DbObject.USER:
return null;
default:
}
final Set<ReplicaSet> list = getAllTables();
final Set set = new HashSet();
final Set<ReplicaSet> allreplicas = getAllTables();
for (final ReplicaSet replicaSet : allreplicas) {
if (except != null && replicaSet.getACopy() != null && except.getName().equalsIgnoreCase(replicaSet.getACopy().getName())) {
continue;
}
set.clear();
replicaSet.addDependencies(set);
if (set.contains(obj)) { return replicaSet; }
}
return null;
}
private String getFirstInvalidTable(final Session session) {
String conflict = null;
try {
final Set<ReplicaSet> list = getAllTables();
for (final ReplicaSet replicaSet : list) {
conflict = replicaSet.getSQL();
session.prepare(replicaSet.getCreateSQL());
}
}
catch (final SQLException e) {
return conflict;
}
return null;
}
/**
* Remove an object from the system table.
*
* @param session
* the session
* @param obj
* the object to be removed
*/
public synchronized void removeSchemaObject(final Session session, final SchemaObject obj) throws SQLException {
final int type = obj.getType();
if (type == DbObject.TABLE_OR_VIEW) {
final Table table = (Table) obj;
if (table.getTemporary() && !table.getGlobalTemporary()) {
session.removeLocalTempTable(table);
return;
}
}
else if (type == DbObject.INDEX) {
final Index index = (Index) obj;
final Table table = index.getTable();
if (table.getTemporary() && !table.getGlobalTemporary()) {
session.removeLocalTempTableIndex(index);
return;
}
}
else if (type == DbObject.CONSTRAINT) {
final Constraint constraint = (Constraint) obj;
final Table table = constraint.getTable();
if (table.getTemporary() && !table.getGlobalTemporary()) {
session.removeLocalTempTableConstraint(constraint);
return;
}
}
checkWritingAllowed();
final Comment comment = findComment(obj);
if (comment != null) {
removeDatabaseObject(session, comment);
}
obj.getSchema().remove(obj);
if (!starting) {
String invalid;
if (SysProperties.OPTIMIZE_DROP_DEPENDENCIES) {
final ReplicaSet replicaSet = getDependentTable(obj, null);
invalid = replicaSet == null ? null : replicaSet.getSQL();
}
else {
invalid = getFirstInvalidTable(session);
}
if (invalid != null) {
obj.getSchema().add(obj);
throw Message.getSQLException(ErrorCode.CANNOT_DROP_2, new String[]{obj.getSQL(), invalid});
}
obj.removeChildrenAndResources(session);
}
final int id = obj.getId();
removeMeta(session, id);
if (obj instanceof TableData) {
tableMap.remove(id);
}
}
/**
* Check if this database disk-based.
*
* @return true if it is disk-based, false it it is in-memory only.
*/
public boolean isPersistent() {
return persistent;
}
public TraceSystem getTraceSystem() {
return traceSystem;
}
public DiskFile getDataFile() {
return fileData;
}
public DiskFile getIndexFile() {
return fileIndex;
}
public synchronized void setCacheSize(final int kb) throws SQLException {
if (fileData != null) {
fileData.getCache().setMaxSize(kb);
final int valueIndex = kb <= 32 ? kb : kb >>> SysProperties.CACHE_SIZE_INDEX_SHIFT;
fileIndex.getCache().setMaxSize(valueIndex);
}
}
public synchronized void setMasterUser(final User user) throws SQLException {
addDatabaseObject(systemSession, user);
systemSession.commit(true);
}
public Role getPublicRole() {
return publicRole;
}
/**
* Get a unique temporary table name.
*
* @param sessionId
* the session id
* @return a unique name
*/
public String getTempTableName(final int sessionId) {
String tempName;
for (int i = 0;; i++) {
tempName = Constants.TEMP_TABLE_PREFIX + sessionId + "_" + i;
if (mainSchema.findTableOrView(null, tempName, LocationPreference.NO_PREFERENCE) == null) {
break;
}
}
return tempName;
}
public void setCompareMode(final CompareMode compareMode) {
this.compareMode = compareMode;
}
public void setCluster(final String cluster) {
this.cluster = cluster;
}
@Override
public void checkWritingAllowed() throws SQLException {
if (readOnly) { throw Message.getSQLException(ErrorCode.DATABASE_IS_READ_ONLY); }
if (noDiskSpace) { throw Message.getSQLException(ErrorCode.NO_DISK_SPACE_AVAILABLE); }
}
public boolean getReadOnly() {
return readOnly;
}
public void setWriteDelay(final int value) {
writeDelay = value;
if (writer != null) {
writer.setWriteDelay(value);
}
}
/**
* Delete an unused log file. It is deleted immediately if no writer thread is running, or deleted later on if one is running. Deleting
* is delayed because the hard drive otherwise may delete the file a bit before the data is written to the new file, which can cause
* problems when recovering.
*
* @param fileName
* the name of the file to be deleted
*/
public void deleteLogFileLater(final String fileName) throws SQLException {
if (writer != null) {
writer.deleteLogFileLater(fileName);
}
else {
FileUtils.delete(fileName);
}
}
public void setEventListener(final DatabaseEventListener eventListener) {
this.eventListener = eventListener;
}
public void setEventListenerClass(final String className) throws SQLException {
if (className == null || className.length() == 0) {
eventListener = null;
}
else {
try {
eventListener = (DatabaseEventListener) ClassUtils.loadUserClass(className).newInstance();
String url = databaseURL;
if (cipher != null) {
url += ";CIPHER=" + cipher;
}
eventListener.init(url);
}
catch (final Throwable e) {
throw Message.getSQLException(ErrorCode.ERROR_SETTING_DATABASE_EVENT_LISTENER_2, new String[]{className, e.toString()}, e);
}
}
}
@Override
public synchronized void freeUpDiskSpace() throws SQLException {
if (eventListener != null) {
eventListener.diskSpaceIsLow(0);
}
}
/**
* Set the progress of a long running operation. This method calls the {@link DatabaseEventListener} if one is registered.
*
* @param state
* the {@link DatabaseEventListener} state
* @param name
* the object name
* @param x
* the current position
* @param max
* the highest value
*/
public void setProgress(final int state, final String name, final int x, final int max) {
if (eventListener != null) {
try {
eventListener.setProgress(state, name, x, max);
}
catch (final Exception e2) {
// ignore this second (user made) exception
}
}
}
/**
* This method is called after an exception occurred, to inform the database event listener (if one is set).
*
* @param e
* the exception
* @param sql
* the SQL statement
*/
public void exceptionThrown(final SQLException e, final String sql) {
if (eventListener != null) {
try {
eventListener.exceptionThrown(e, sql);
}
catch (final Exception e2) {
// ignore this second (user made) exception
}
}
}
/**
* Synchronize the files with the file system. This method is called when executing the SQL statement CHECKPOINT SYNC.
*/
public void sync() throws SQLException {
if (log != null) {
log.sync();
}
if (fileData != null) {
fileData.sync();
}
if (fileIndex != null) {
fileIndex.sync();
}
}
public int getMaxMemoryRows() {
return maxMemoryRows;
}
public void setMaxMemoryRows(final int value) {
maxMemoryRows = value;
}
public void setMaxMemoryUndo(final int value) {
maxMemoryUndo = value;
}
public int getMaxMemoryUndo() {
return maxMemoryUndo;
}
public void setLockMode(final int lockMode) throws SQLException {
switch (lockMode) {
case Constants.LOCK_MODE_OFF:
case Constants.LOCK_MODE_READ_COMMITTED:
case Constants.LOCK_MODE_TABLE:
case Constants.LOCK_MODE_TABLE_GC:
break;
default:
throw Message.getInvalidValueException("lock mode", "" + lockMode);
}
this.lockMode = lockMode;
}
public int getLockMode() {
return lockMode;
}
public synchronized void setCloseDelay(final int value) {
closeDelay = value;
}
public boolean getLogIndexChanges() {
return logIndexChanges;
}
public synchronized void setLog(final int level) throws SQLException {
if (logLevel == level) { return; }
boolean logData;
boolean logIndex;
switch (level) {
case 0:
logData = false;
logIndex = false;
break;
case 1:
logData = true;
logIndex = false;
break;
case 2:
logData = true;
logIndex = true;
break;
default:
throw Message.throwInternalError("level=" + level);
}
if (fileIndex != null) {
fileIndex.setLogChanges(logIndex);
}
logIndexChanges = logIndex;
if (log != null) {
log.setDisabled(!logData);
log.checkpoint();
}
traceSystem.getTrace(Trace.DATABASE).error("SET LOG " + level, null);
logLevel = level;
}
public boolean getRecovery() {
return recovery;
}
public Session getSystemSession() {
return systemSession;
}
@Override
public void handleInvalidChecksum() throws SQLException {
final SQLException e = Message.getSQLException(ErrorCode.FILE_CORRUPTED_1, "wrong checksum");
if (!recovery) { throw e; }
traceSystem.getTrace(Trace.DATABASE).error("recover", e);
}
/**
* Check if the database is in the process of closing.
*
* @return true if the database is closing
*/
public boolean isClosing() {
return closing;
}
public void setMaxLengthInplaceLob(final int value) {
maxLengthInplaceLob = value;
}
@Override
public int getMaxLengthInplaceLob() {
return persistent ? maxLengthInplaceLob : Integer.MAX_VALUE;
}
public void setIgnoreCase(final boolean b) {
ignoreCase = b;
}
public boolean getIgnoreCase() {
if (starting) {
// tables created at startup must not be converted to ignorecase
return false;
}
return ignoreCase;
}
public synchronized void setDeleteFilesOnDisconnect(final boolean b) {
deleteFilesOnDisconnect = b;
}
@Override
public String getLobCompressionAlgorithm(final int type) {
return lobCompressionAlgorithm;
}
public void setLobCompressionAlgorithm(final String stringValue) {
lobCompressionAlgorithm = stringValue;
}
/**
* Called when the size if the data or index file has been changed.
*
* @param length
* the new file size
*/
public void notifyFileSize(final long length) {
// ignore
}
public synchronized void setMaxLogSize(final long value) {
getLog().setMaxLogSize(value);
}
public void setAllowLiterals(final int value) {
allowLiterals = value;
}
public boolean getOptimizeReuseResults() {
return optimizeReuseResults;
}
public void setOptimizeReuseResults(final boolean b) {
optimizeReuseResults = b;
}
/**
* Called when the summary of the index in the log file has become invalid. This method is only called if index changes are not logged,
* and if an index has been changed.
*/
public void invalidateIndexSummary() throws SQLException {
if (indexSummaryValid) {
indexSummaryValid = false;
if (log == null) {
log = new LogSystem(this, databaseName, readOnly, accessModeLog, pageStore);
}
log.invalidateIndexSummary();
}
}
public boolean getIndexSummaryValid() {
return indexSummaryValid;
}
@Override
public Object getLobSyncObject() {
return lobSyncObject;
}
public int getSessionCount() {
return userSessions.size();
}
public void setReferentialIntegrity(final boolean b) {
referentialIntegrity = b;
}
public boolean getReferentialIntegrity() {
return referentialIntegrity;
}
/**
* Check if the database is currently opening. This is true until all stored SQL statements have been executed.
*
* @return true if the database is still starting
*/
public boolean isStarting() {
return starting;
}
/**
* Called after the database has been opened and initialized. This method notifies the event listener if one has been set.
*/
public void opened() {
if (eventListener != null) {
eventListener.opened();
}
}
public void setMode(final Mode mode) {
this.mode = mode;
}
public Mode getMode() {
return mode;
}
public void setMaxOperationMemory(final int maxOperationMemory) {
this.maxOperationMemory = maxOperationMemory;
}
public int getMaxOperationMemory() {
return maxOperationMemory;
}
public Session getExclusiveSession() {
return exclusiveSession;
}
public void setExclusiveSession(final Session session) {
exclusiveSession = session;
}
@Override
public boolean getLobFilesInDirectories() {
return lobFilesInDirectories;
}
@Override
public SmallLRUCache getLobFileListCache() {
return lobFileListCache;
}
/**
* Checks if the system table (containing the catalog) is locked.
*
* @return true if it is currently locked
*/
public boolean isSysTableLocked() {
return meta.isLockedExclusively();
}
/**
* Open a new connection or get an existing connection to another database.
*
* @param driver
* the database driver or null
* @param url
* the database URL
* @param user
* the user name
* @param password
* the password
* @param clearLinkConnectionCache
* @return the connection
*/
public TableLinkConnection getLinkConnection(final String driver, final String url, final String user, final String password, final boolean clearLinkConnectionCache) throws SQLException {
if (linkConnections == null || clearLinkConnectionCache) {
linkConnections = new HashMap<TableLinkConnection, TableLinkConnection>();
}
return TableLinkConnection.open(linkConnections, driver, url, user, password);
}
@Override
public String toString() {
return databaseShortName + ":" + super.toString();
}
/**
* Immediately close the database.
*/
public void shutdownImmediately() {
setPowerOffCount(1);
try {
checkPowerOff();
}
catch (final SQLException e) {
// ignore
}
}
@Override
public TempFileDeleter getTempFileDeleter() {
return tempFileDeleter;
}
@Override
public Trace getTrace() {
return getTrace(Trace.DATABASE);
}
public PageStore getPageStore() throws SQLException {
if (pageStore == null && SysProperties.PAGE_STORE) {
pageStore = new PageStore(this, databaseName + Constants.SUFFIX_PAGE_FILE, accessModeData, SysProperties.CACHE_SIZE_DEFAULT);
pageStore.open();
}
return pageStore;
}
/**
* Redo a change in a table.
*
* @param tableId
* the object id of the table
* @param row
* the row
* @param add
* true if the record is added, false if deleted
*/
public void redo(final int tableId, final Row row, final boolean add) throws SQLException {
final TableData table = (TableData) tableMap.get(tableId);
if (add) {
table.addRow(systemSession, row);
}
else {
table.removeRow(systemSession, row);
}
if (tableId == 0) {
final MetaRecord m = new MetaRecord(row);
if (add) {
objectIds.set(m.getId());
final TableProxyManager proxyManager = new TableProxyManager(this, systemSession, true);
m.execute(this, systemSession, eventListener, proxyManager);
}
else {
m.undo(this, systemSession, eventListener);
}
}
}
/**
* Get the first user defined table.
*
* @return the table or null if no table is defined
*/
public ReplicaSet getFirstUserTable() {
final Set<ReplicaSet> list = getAllTables();
for (final ReplicaSet replicaSet : list) {
if (replicaSet.getCreateSQL() != null) { return replicaSet; }
}
return null;
}
public boolean isReconnectNeeded() {
if (fileLockMethod != FileLock.LOCK_SERIALIZED) { return false; }
final long now = System.currentTimeMillis();
if (now < reconnectCheckNext) { return false; }
reconnectCheckNext = now + SysProperties.RECONNECT_CHECK_DELAY;
if (lock == null) {
lock = new FileLock(traceSystem, databaseName + Constants.SUFFIX_LOCK_FILE, Constants.LOCK_SLEEP);
}
Properties prop;
try {
while (true) {
prop = lock.load();
if (prop.equals(reconnectLastLock)) { return false; }
if (prop.getProperty("changePending", null) == null) {
break;
}
getTrace().debug("delay (change pending)");
Thread.sleep(SysProperties.RECONNECT_CHECK_DELAY);
}
reconnectLastLock = prop;
}
catch (final Exception e) {
getTrace().error("readOnly:" + readOnly, e);
// ignore
}
return true;
}
/**
* This method is called after writing to the database.
*/
public void afterWriting() throws SQLException {
if (fileLockMethod != FileLock.LOCK_SERIALIZED || readOnly) { return; }
reconnectCheckNext = System.currentTimeMillis() + 1;
}
/**
* Flush all changes when using the serialized mode, and if there are pending changes.
*/
public void checkpointIfRequired() throws SQLException {
if (fileLockMethod != FileLock.LOCK_SERIALIZED || readOnly || !reconnectChangePending) { return; }
final long now = System.currentTimeMillis();
if (now > reconnectCheckNext) {
getTrace().debug("checkpoint");
checkpoint();
reconnectModified(false);
}
}
/**
* Flush all changes and open a new log file.
*/
public void checkpoint() throws SQLException {
if (SysProperties.PAGE_STORE) {
pageStore.checkpoint();
}
getLog().checkpoint();
getTempFileDeleter().deleteUnused();
}
/**
* This method is called before writing to the log file.
*/
public void beforeWriting() {
if (fileLockMethod == FileLock.LOCK_SERIALIZED) {
reconnectModified(true);
}
}
/**
* Get a database object.
*
* @param id
* the object id
* @return the database object
*/
DbObject getDbObject(final int id) {
return databaseObjects.get(ObjectUtils.getInteger(id));
}
/**
* H2O Creates H2O schema meta-data tables, including System Table tables if this machine is a System Table.
*
* @throws Exception
* @throws SQLException
*/
private void createH2OTables(final boolean persistedSchemaTablesExist, final boolean databaseExists) throws Exception {
if (!databaseExists) {
createSystemTableOrGetReferenceToIt(databaseExists, persistedSchemaTablesExist, true);
}
if (!persistedSchemaTablesExist) {
try {
TableManager.createTableManagerTables(systemSession);
}
catch (final SQLException e) {
e.printStackTrace();
}
}
systemTableRef.getSystemTable().addConnectionInformation(getID(), new DatabaseInstanceWrapper(getID(), databaseRemote.getLocalDatabaseInstance(), true));
}
public ISystemTableReference getSystemTableReference() {
return systemTableRef;
}
public ISystemTableMigratable getSystemTable() {
return systemTableRef.getSystemTable();
}
/**
* @param dbLocation
* @return
*/
public boolean isLocal(final DatabaseInstanceWrapper dbLocation) {
return dbLocation.getDatabaseInstance().equals(getLocalDatabaseInstance());
}
/**
* Examples:
* <ul>
* <li><code>//mem:management_db_9081</code></li>
* <li><code>//db_data/unittests/schema_test</code></li>
* </ul>
*
* @return the databaseLocation
*/
public String getDatabaseLocation() {
return getID().getDbLocation();
}
/**
* Is this database instance an H2 management database?
*
* @return
*/
public boolean isManagementDB() {
return databaseShortName.startsWith("MANAGEMENT_DB_");
}
/**
* @return the localMachineAddress
*/
public String getLocalMachineAddress() {
return getID().getHostname();
}
/**
* @return the localMachinePort
*/
public int getLocalMachinePort() {
return getID().getPort();
}
/**
* Gets the full address of the database - i.e. one that can be used to connect to it remotely through JDBC. An example path:
* jdbc:h2:sm:tcp://localhost:9090/db_data/one/test_db
*
* @return
*/
public String getFullDatabasePath() {
// String isTCP = (getLocalMachinePort() == -1 &&
// getDatabaseLocation().contains("mem"))? "": "tcp:";
//
// String url = "";
// if (isTCP.equals("tcp:")){
// url = getLocalMachineAddress() + ":" + getLocalMachinePort() + "/";
// }
//
// return "jdbc:h2:" + ((systemTableRef.isSystemTableLocal())? "sm:":
// "") + isTCP + url + getDatabaseLocation();
return databaseRemote.getLocalMachineLocation().getURL();
}
/**
* Returns the type of connection this database is open on (e.g. tcp, mem).
*
* @return
*/
public String getConnectionType() {
return getID().getConnectionType();
}
/**
* @param replicaLocationString
* @return
*/
public IDatabaseInstanceRemote getDatabaseInstance(final DatabaseID databaseURL) {
try {
return systemTableRef.getSystemTable().getDatabaseInstance(databaseURL);
}
catch (final RPCException e) {
e.printStackTrace();
}
catch (final MovedException e) {
e.printStackTrace();
}
return null;
}
/**
* @return
*/
public IDatabaseInstanceRemote getLocalDatabaseInstance() {
return databaseRemote.getLocalDatabaseInstance();
}
/**
* @return
*/
public DatabaseInstanceWrapper getLocalDatabaseInstanceInWrapper() {
return new DatabaseInstanceWrapper(getID(), databaseRemote.getLocalDatabaseInstance(), true);
}
public void removeLocalDatabaseInstance() {
try {
getLocalDatabaseInstance().setAlive(false);
// this.systemTableRef.getSystemTable(true).removeConnectionInformation(this.databaseRemote.getLocalDatabaseInstance());
// new
// RemoveConnectionInfo(this.systemTableRef.getSystemTable(true),
// this.databaseRemote.getLocalDatabaseInstance()).start();
}
catch (final Exception e) {
// An error here isn't critical.
}
}
/**
*
*/
public IDatabaseRemote getRemoteInterface() {
return databaseRemote;
}
/**
*
*/
public IChordInterface getChordInterface() {
return databaseRemote;
}
/**
* @return
*/
public Session getH2OSession() {
return h2oSession;
}
/**
* @return
*/
public int getUserSessionsSize() {
return userSessions.size();
}
public Settings getDatabaseSettings() {
return databaseSettings;
}
public TransactionNameGenerator getTransactionNameGenerator() {
return transactionNameGenerator;
}
public synchronized boolean isRunning() {
return running;
}
public Set<String> getLocalSchema() {
return localSchema;
}
public boolean isTableLocal(final Schema schema) {
return localSchema.contains(schema.getName());
}
private void setDiagnosticLevel(final DatabaseID localMachineLocation) {
final H2OPropertiesWrapper databaseProperties = H2OPropertiesWrapper.getWrapper(localMachineLocation);
try {
databaseProperties.loadProperties();
}
catch (final IOException e) {
ErrorHandling.exceptionErrorNoEvent(e, "Failed to load database properties for database: " + localMachineLocation);
}
redirectSystemOut(databaseProperties);
redirectSystemErr(databaseProperties);
final String diagnosticLevel = databaseProperties.getProperty("diagnosticLevel");
if (diagnosticLevel != null) {
Diagnostic.traceNoEvent(DiagnosticLevel.FINAL, "Setting diagnostic level to " + diagnosticLevel);
if (diagnosticLevel.equals("FINAL")) {
Diagnostic.setLevel(DiagnosticLevel.FINAL);
}
else if (diagnosticLevel.equals("NONE")) {
Diagnostic.setLevel(DiagnosticLevel.NONE);
}
else if (diagnosticLevel.equals("INIT")) {
Diagnostic.setLevel(DiagnosticLevel.INIT);
}
else if (diagnosticLevel.equals("FULL")) {
Diagnostic.setLevel(DiagnosticLevel.FULL);
}
}
Diagnostic.addIgnoredPackage("uk.ac.standrews.cs.stachord");
Diagnostic.addIgnoredPackage("uk.ac.standrews.cs.nds");
Diagnostic.addIgnoredPackage("uk.ac.standrews.cs.numonic");
// Diagnostic.addIgnoredPackage("org.h2o.autonomic.numonic.ranking");
Diagnostic.setTimestampFlag(true);
Diagnostic.setTimestampFormat(new SimpleDateFormat("HH:mm:ss:SSS "));
Diagnostic.setTimestampDelimiterFlag(false);
ErrorHandling.setTimestampFlag(false);
}
public void redirectSystemOut(final H2OPropertiesWrapper databaseProperties) {
final String sysOutFileLocation = databaseProperties.getProperty("sysOutLocation");
if (sysOutFileLocation != null) {
try {
final File sysOutFile = new File(sysOutFileLocation);
if (!sysOutFile.exists()) {
final File parentFolder = sysOutFile.getParentFile();
if (!parentFolder.exists()) {
parentFolder.mkdirs();
}
sysOutFile.createNewFile();
}
final PrintStream printStream = new PrintStream(new FileOutputStream(sysOutFile, true));
System.setOut(printStream);
}
catch (final IOException e) {
ErrorHandling.exceptionErrorNoEvent(e, "Failed to redirect System.out messages to file located at: " + sysOutFileLocation);
}
}
}
public void redirectSystemErr(final H2OPropertiesWrapper databaseProperties) {
final String sysErrFileLocation = databaseProperties.getProperty("sysErrLocation");
if (sysErrFileLocation != null) {
try {
final File sysErrFile = new File(sysErrFileLocation);
if (!sysErrFile.exists()) {
final File parentFolder = sysErrFile.getParentFile();
if (!parentFolder.exists()) {
parentFolder.mkdirs();
}
sysErrFile.createNewFile();
}
final PrintStream printStream = new PrintStream(new FileOutputStream(sysErrFile, true));
System.setErr(printStream);
}
catch (final IOException e) {
ErrorHandling.exceptionErrorNoEvent(e, "Failed to redirect System.out messages to file located at: " + databaseProperties.getProperty("systemOutLocation"));
}
}
}
public AsynchronousQueryManager getAsynchronousQueryManager() {
return asynchronousQueryManager;
}
public TableManagerInstanceServer getTableManagerServer() {
return table_manager_instance_server;
}
public SystemTableServer getSystemTableServer() {
return system_table_server;
}
public DatabaseInstanceServer getDatabaseInstanceServer() {
return database_instance_server;
}
public INumonic getNumonic() {
return numonic;
}
@Override
public void update(final Observable o, final Object arg) {
final Threshold threshold = ThresholdChecker.getThresholdObject(arg);
if (threshold.resourceName == ResourceType.CPU_USER && threshold.above) {
//CPU utilization has been exceeded.
//Act on this.
}
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public void setConnected(final boolean connected) {
this.connected = connected;
}
}
| false | true | private synchronized void open(final int traceLevelFile, final int traceLevelSystemOut, final ConnectionInfo ci, final DatabaseID localMachineLocation) throws SQLException, StartupException {
boolean databaseExists = false; // whether the database already exists
// on disk. i.e. with .db.data files,
// etc.
if (persistent) {
if (SysProperties.PAGE_STORE) {
final String pageFileName = databaseName + Constants.SUFFIX_PAGE_FILE;
if (FileUtils.exists(pageFileName) && FileUtils.isReadOnly(pageFileName)) {
readOnly = true;
}
}
final String dataFileName = databaseName + Constants.SUFFIX_DATA_FILE;
databaseExists = FileUtils.exists(dataFileName);
if (databaseExists) {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Database already exists at: " + dataFileName);
}
else {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Database doesn't exist at: " + dataFileName);
}
if (FileUtils.exists(dataFileName)) {
// if it is already read-only because ACCESS_MODE_DATA=r
readOnly = readOnly | FileUtils.isReadOnly(dataFileName);
}
if (readOnly) {
traceSystem = new TraceSystem(null, false);
}
else {
traceSystem = new TraceSystem(databaseName + Constants.SUFFIX_TRACE_FILE, true);
}
traceSystem.setLevelFile(traceLevelFile);
traceSystem.setLevelSystemOut(traceLevelSystemOut);
traceSystem.getTrace(Trace.DATABASE).info("opening " + databaseName + " (build " + Constants.BUILD_ID + ")");
if (autoServerMode) {
if (readOnly || fileLockMethod == FileLock.LOCK_NO) { throw Message.getSQLException(ErrorCode.FEATURE_NOT_SUPPORTED); }
}
if (!readOnly && fileLockMethod != FileLock.LOCK_NO) {
lock = new FileLock(traceSystem, databaseName + Constants.SUFFIX_LOCK_FILE, Constants.LOCK_SLEEP);
lock.lock(fileLockMethod);
if (autoServerMode) {
startServer(lock.getUniqueId());
}
}
// wait until pending changes are written
isReconnectNeeded();
if (SysProperties.PAGE_STORE) {
final PageStore store = getPageStore();
store.recover();
}
if (FileUtils.exists(dataFileName)) {
lobFilesInDirectories &= !ValueLob.existsLobFile(getDatabasePath());
lobFilesInDirectories |= FileUtils.exists(databaseName + Constants.SUFFIX_LOBS_DIRECTORY);
}
dummy = DataPage.create(this, 0);
deleteOldTempFiles();
log = new LogSystem(this, databaseName, readOnly, accessModeLog, pageStore);
if (pageStore == null) {
openFileData();
log.open();
openFileIndex();
log.recover();
fileData.init();
try {
fileIndex.init();
}
catch (final Exception e) {
if (recovery) {
traceSystem.getTrace(Trace.DATABASE).error("opening index", e);
final ArrayList<DbObject> list = new ArrayList<DbObject>(storageMap.values());
for (int i = 0; i < list.size(); i++) {
final Storage s = (Storage) list.get(i);
if (s.getDiskFile() == fileIndex) {
removeStorage(s.getId(), fileIndex);
}
}
fileIndex.delete();
openFileIndex();
}
else {
throw Message.convert(e);
}
}
}
reserveLobFileObjectIds();
writer = WriterThread.create(this, writeDelay);
}
else {
traceSystem = new TraceSystem(null, false);
log = new LogSystem(null, null, false, null, null);
}
systemUser = new User(this, 0, Constants.DBA_NAME, true);
h2oSchemaUser = new User(this, 1, "H2O", true);
h2oSystemUser = new User(this, 1, "system", true);
mainSchema = new Schema(this, 0, Constants.SCHEMA_MAIN, systemUser, true);
infoSchema = new Schema(this, -1, Constants.SCHEMA_INFORMATION, systemUser, true);
schemas.put(mainSchema.getName(), mainSchema);
schemas.put(infoSchema.getName(), infoSchema);
publicRole = new Role(this, 0, Constants.PUBLIC_ROLE_NAME, true);
roles.put(Constants.PUBLIC_ROLE_NAME, publicRole);
systemUser.setAdmin(true);
h2oSchemaUser.setAdmin(true);
h2oSystemUser.setAdmin(true);
systemSession = new Session(this, systemUser);
h2oSession = new Session(this, h2oSchemaUser);
h2oSystemSession = new Session(this, h2oSystemUser);
final ObjectArray cols = new ObjectArray();
final Column columnId = new Column("ID", Value.INT);
columnId.setNullable(false);
cols.add(columnId);
cols.add(new Column("HEAD", Value.INT));
cols.add(new Column("TYPE", Value.INT));
cols.add(new Column("SQL", Value.STRING));
int headPos = 0;
if (pageStore != null) {
headPos = pageStore.getMetaTableHeadPos();
}
meta = mainSchema.createTable("SYS", 0, cols, persistent, false, headPos);
tableMap.put(0, meta);
final IndexColumn[] pkCols = IndexColumn.wrap(new Column[]{columnId});
metaIdIndex = meta.addIndex(systemSession, "SYS_ID", 0, pkCols, IndexType.createPrimaryKey(false, false), Index.EMPTY_HEAD, null);
objectIds.set(0);
// there could be views on system tables, so they must be added first
for (int i = 0; i < MetaTable.getMetaTableTypeCount(); i++) {
addMetaData(i);
}
starting = true;
/*
* H2O STARTUP CODE FOR System Table, TABLE INSTANITATION
*/
if (!isManagementDB()) { // don't run this code with the TCP server management DB
databaseRemote.connectToDatabaseSystem(h2oSystemSession, databaseSettings);
// Establish Proxies
startTableManagerInstanceServer();
startDatabaseInstanceServer();
createMetaDataReplicationThread(); //Must be executed after call to databaseRemote because of getLocalDatabaseInstanceInWrapper() call.
}
/*
* ###################################################################### ###### END OF System Table STARTUP CODE At this point in
* the code this database instance will be connected to a System Table, so when tables are generated (below), it will be possible
* for them to re-instantiate Table Managers where possible. ######################################################################
* ######
*/
final Cursor cursor = metaIdIndex.find(systemSession, null, null);
// first, create all function aliases and sequences because
// they might be used in create table / view / constraints and so on
final ObjectArray records = new ObjectArray();
while (cursor.next()) {
final MetaRecord rec = new MetaRecord(cursor.get());
objectIds.set(rec.getId());
records.add(rec);
}
MetaRecord.sort(records);
if (!isManagementDB() && databaseExists) {
/*
* Create or connect to a new System Table instance if this node already has tables on it.
*/
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Database already exists. No need to recreate the System Table.");
createSystemTableOrGetReferenceToIt(true, systemTableRef.isSystemTableLocal(), false);
}
if (records.size() > 0) {
final TableProxyManager proxyManager = new TableProxyManager(this, systemSession, true);
for (int i = 0; i < records.size(); i++) {
final MetaRecord rec = (MetaRecord) records.get(i);
if (rec.getSQL().startsWith("CREATE FORCE LINKED TABLE")) {
continue;
}
rec.execute(this, systemSession, eventListener, proxyManager);
}
proxyManager.finishTransaction(true, true, this);
}
if (!isManagementDB()) {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, " Executed meta-records.");
}
// try to recompile the views that are invalid
recompileInvalidViews(systemSession);
starting = false;
addDefaultSetting(systemSession, SetTypes.DEFAULT_LOCK_TIMEOUT, null, Constants.INITIAL_LOCK_TIMEOUT);
addDefaultSetting(systemSession, SetTypes.DEFAULT_TABLE_TYPE, null, Constants.DEFAULT_TABLE_TYPE);
addDefaultSetting(systemSession, SetTypes.CACHE_SIZE, null, SysProperties.CACHE_SIZE_DEFAULT);
addDefaultSetting(systemSession, SetTypes.CLUSTER, Constants.CLUSTERING_DISABLED, 0);
addDefaultSetting(systemSession, SetTypes.WRITE_DELAY, null, Constants.DEFAULT_WRITE_DELAY);
addDefaultSetting(systemSession, SetTypes.CREATE_BUILD, null, Constants.BUILD_ID);
if (!readOnly) {
removeUnusedStorages(systemSession);
}
systemSession.commit(true);
traceSystem.getTrace(Trace.DATABASE).info("opened " + databaseName);
if (!isManagementDB() && (!databaseExists || !systemTableRef.isSystemTableLocal())) {
// don't run this code with the TCP server management DB
try {
createH2OTables(false, databaseExists);
}
catch (final Exception e) {
ErrorHandling.exceptionError(e, "Error creating H2O tables.");
}
// called here, because at this point the system is ready to replicate TM state.
databaseRemote.setAsReadyToReplicateMetaData(metaDataReplicaManager);
}
else if (!isManagementDB() && databaseExists && systemTableRef.isSystemTableLocal()) {
/*
* This is the System Table. Reclaim previously held state.
*/
try {
createH2OTables(true, databaseExists);
systemTableRef.getSystemTable().recreateInMemorySystemTableFromLocalPersistedState();
// called here, because at this point the system is ready to replicate TM state.
databaseRemote.setAsReadyToReplicateMetaData(metaDataReplicaManager);
Diagnostic.traceNoEvent(DiagnosticLevel.FINAL, "Re-created System Table state.");
}
catch (final Exception e) {
Diagnostic.trace(DiagnosticLevel.FULL, "error creating H2O tables");
}
}
}
| private synchronized void open(final int traceLevelFile, final int traceLevelSystemOut, final ConnectionInfo ci, final DatabaseID localMachineLocation) throws SQLException, StartupException {
boolean databaseExists = false; // whether the database already exists
// on disk. i.e. with .db.data files,
// etc.
if (persistent) {
if (SysProperties.PAGE_STORE) {
final String pageFileName = databaseName + Constants.SUFFIX_PAGE_FILE;
if (FileUtils.exists(pageFileName) && FileUtils.isReadOnly(pageFileName)) {
readOnly = true;
}
}
final String dataFileName = databaseName + Constants.SUFFIX_DATA_FILE;
databaseExists = FileUtils.exists(dataFileName);
if (databaseExists) {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Database already exists at: " + dataFileName);
}
else {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Database doesn't exist at: " + dataFileName);
}
if (FileUtils.exists(dataFileName)) {
// if it is already read-only because ACCESS_MODE_DATA=r
readOnly = readOnly | FileUtils.isReadOnly(dataFileName);
}
if (readOnly) {
traceSystem = new TraceSystem(null, false);
}
else {
traceSystem = new TraceSystem(databaseName + Constants.SUFFIX_TRACE_FILE, true);
}
traceSystem.setLevelFile(traceLevelFile);
traceSystem.setLevelSystemOut(traceLevelSystemOut);
traceSystem.getTrace(Trace.DATABASE).info("opening " + databaseName + " (build " + Constants.BUILD_ID + ")");
if (autoServerMode) {
if (readOnly || fileLockMethod == FileLock.LOCK_NO) { throw Message.getSQLException(ErrorCode.FEATURE_NOT_SUPPORTED); }
}
if (!readOnly && fileLockMethod != FileLock.LOCK_NO) {
lock = new FileLock(traceSystem, databaseName + Constants.SUFFIX_LOCK_FILE, Constants.LOCK_SLEEP);
lock.lock(fileLockMethod);
if (autoServerMode) {
startServer(lock.getUniqueId());
}
}
// wait until pending changes are written
isReconnectNeeded();
if (SysProperties.PAGE_STORE) {
final PageStore store = getPageStore();
store.recover();
}
if (FileUtils.exists(dataFileName)) {
lobFilesInDirectories &= !ValueLob.existsLobFile(getDatabasePath());
lobFilesInDirectories |= FileUtils.exists(databaseName + Constants.SUFFIX_LOBS_DIRECTORY);
}
dummy = DataPage.create(this, 0);
deleteOldTempFiles();
log = new LogSystem(this, databaseName, readOnly, accessModeLog, pageStore);
if (pageStore == null) {
openFileData();
log.open();
openFileIndex();
log.recover();
fileData.init();
try {
fileIndex.init();
}
catch (final Exception e) {
if (recovery) {
traceSystem.getTrace(Trace.DATABASE).error("opening index", e);
final ArrayList<DbObject> list = new ArrayList<DbObject>(storageMap.values());
for (int i = 0; i < list.size(); i++) {
final Storage s = (Storage) list.get(i);
if (s.getDiskFile() == fileIndex) {
removeStorage(s.getId(), fileIndex);
}
}
fileIndex.delete();
openFileIndex();
}
else {
throw Message.convert(e);
}
}
}
reserveLobFileObjectIds();
writer = WriterThread.create(this, writeDelay);
}
else {
traceSystem = new TraceSystem(null, false);
log = new LogSystem(null, null, false, null, null);
}
systemUser = new User(this, 0, Constants.DBA_NAME, true);
h2oSchemaUser = new User(this, 1, "H2O", true);
h2oSystemUser = new User(this, 1, "system", true);
mainSchema = new Schema(this, 0, Constants.SCHEMA_MAIN, systemUser, true);
infoSchema = new Schema(this, -1, Constants.SCHEMA_INFORMATION, systemUser, true);
schemas.put(mainSchema.getName(), mainSchema);
schemas.put(infoSchema.getName(), infoSchema);
publicRole = new Role(this, 0, Constants.PUBLIC_ROLE_NAME, true);
roles.put(Constants.PUBLIC_ROLE_NAME, publicRole);
systemUser.setAdmin(true);
h2oSchemaUser.setAdmin(true);
h2oSystemUser.setAdmin(true);
systemSession = new Session(this, systemUser);
h2oSession = new Session(this, h2oSchemaUser);
h2oSystemSession = new Session(this, h2oSystemUser);
final ObjectArray cols = new ObjectArray();
final Column columnId = new Column("ID", Value.INT);
columnId.setNullable(false);
cols.add(columnId);
cols.add(new Column("HEAD", Value.INT));
cols.add(new Column("TYPE", Value.INT));
cols.add(new Column("SQL", Value.STRING));
int headPos = 0;
if (pageStore != null) {
headPos = pageStore.getMetaTableHeadPos();
}
meta = mainSchema.createTable("SYS", 0, cols, persistent, false, headPos);
tableMap.put(0, meta);
final IndexColumn[] pkCols = IndexColumn.wrap(new Column[]{columnId});
metaIdIndex = meta.addIndex(systemSession, "SYS_ID", 0, pkCols, IndexType.createPrimaryKey(false, false), Index.EMPTY_HEAD, null);
objectIds.set(0);
// there could be views on system tables, so they must be added first
for (int i = 0; i < MetaTable.getMetaTableTypeCount(); i++) {
addMetaData(i);
}
starting = true;
/*
* H2O STARTUP CODE FOR System Table, TABLE INSTANITATION
*/
if (!isManagementDB()) { // don't run this code with the TCP server management DB
databaseRemote.connectToDatabaseSystem(h2oSystemSession, databaseSettings);
// Establish Proxies
startTableManagerInstanceServer();
startDatabaseInstanceServer();
createMetaDataReplicationThread(); //Must be executed after call to databaseRemote because of getLocalDatabaseInstanceInWrapper() call.
}
/*
* ###################################################################### ###### END OF System Table STARTUP CODE At this point in
* the code this database instance will be connected to a System Table, so when tables are generated (below), it will be possible
* for them to re-instantiate Table Managers where possible. ######################################################################
* ######
*/
final Cursor cursor = metaIdIndex.find(systemSession, null, null);
// first, create all function aliases and sequences because
// they might be used in create table / view / constraints and so on
final ObjectArray records = new ObjectArray();
while (cursor.next()) {
final MetaRecord rec = new MetaRecord(cursor.get());
objectIds.set(rec.getId());
records.add(rec);
}
MetaRecord.sort(records);
if (!isManagementDB() && databaseExists) {
/*
* Create or connect to a new System Table instance if this node already has tables on it.
*/
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, "Database already exists. No need to recreate the System Table.");
createSystemTableOrGetReferenceToIt(true, systemTableRef.isSystemTableLocal(), false);
}
if (records.size() > 0) {
final TableProxyManager proxyManager = new TableProxyManager(this, systemSession, true);
for (int i = 0; i < records.size(); i++) {
final MetaRecord rec = (MetaRecord) records.get(i);
if (rec.getSQL().startsWith("CREATE FORCE LINKED TABLE")) {
continue;
}
try {
rec.execute(this, systemSession, eventListener, proxyManager);
}
catch (final Exception e) {
ErrorHandling.errorNoEvent("Failed to execute meta-record: " + rec.getSQL());
}
}
proxyManager.finishTransaction(true, true, this);
}
if (!isManagementDB()) {
Diagnostic.traceNoEvent(DiagnosticLevel.INIT, " Executed meta-records.");
}
// try to recompile the views that are invalid
recompileInvalidViews(systemSession);
starting = false;
addDefaultSetting(systemSession, SetTypes.DEFAULT_LOCK_TIMEOUT, null, Constants.INITIAL_LOCK_TIMEOUT);
addDefaultSetting(systemSession, SetTypes.DEFAULT_TABLE_TYPE, null, Constants.DEFAULT_TABLE_TYPE);
addDefaultSetting(systemSession, SetTypes.CACHE_SIZE, null, SysProperties.CACHE_SIZE_DEFAULT);
addDefaultSetting(systemSession, SetTypes.CLUSTER, Constants.CLUSTERING_DISABLED, 0);
addDefaultSetting(systemSession, SetTypes.WRITE_DELAY, null, Constants.DEFAULT_WRITE_DELAY);
addDefaultSetting(systemSession, SetTypes.CREATE_BUILD, null, Constants.BUILD_ID);
if (!readOnly) {
removeUnusedStorages(systemSession);
}
systemSession.commit(true);
traceSystem.getTrace(Trace.DATABASE).info("opened " + databaseName);
if (!isManagementDB() && (!databaseExists || !systemTableRef.isSystemTableLocal())) {
// don't run this code with the TCP server management DB
try {
createH2OTables(false, databaseExists);
}
catch (final Exception e) {
ErrorHandling.exceptionError(e, "Error creating H2O tables.");
}
// called here, because at this point the system is ready to replicate TM state.
databaseRemote.setAsReadyToReplicateMetaData(metaDataReplicaManager);
}
else if (!isManagementDB() && databaseExists && systemTableRef.isSystemTableLocal()) {
/*
* This is the System Table. Reclaim previously held state.
*/
try {
createH2OTables(true, databaseExists);
systemTableRef.getSystemTable().recreateInMemorySystemTableFromLocalPersistedState();
// called here, because at this point the system is ready to replicate TM state.
databaseRemote.setAsReadyToReplicateMetaData(metaDataReplicaManager);
Diagnostic.traceNoEvent(DiagnosticLevel.FINAL, "Re-created System Table state.");
}
catch (final Exception e) {
ErrorHandling.exceptionError(e, "Error creating H2O tables.");
}
}
}
|
diff --git a/src/actors/Player.java b/src/actors/Player.java
index 7bc6152..8e52df4 100644
--- a/src/actors/Player.java
+++ b/src/actors/Player.java
@@ -1,865 +1,861 @@
package actors;
import engine.Engine;
import graphics.Sprite;
import item.Item;
import java.awt.Graphics;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.prefs.Preferences;
import org.ini4j.Ini;
import org.ini4j.IniPreferences;
import scenes.BattleScene.BattleScene;
import spell.Spell;
/**
* Player.java
* @author Nicholas Hydock
*
* User controllable actors
*/
public class Player extends Actor {
//All defined jobs can be found within the jobs directory
public static final ArrayList<String> AVAILABLEJOBS = new ArrayList<String>(){
{
for (String s : new File("data/actors/jobs").list())
if (new File("data/actors/jobs/" + s + "/job.ini").exists())
this.add(s);
}
};
/*
* S = STR
* A = AGILITY/SPEED
* V = VITALITY
* I = INTELLIGENCE
* L = LUCK
* + = STRONG HP BOOST
*
* First two lines define linear growth value of hit% and mdef
*/
protected String[] growth;
protected int[][] magicGrowth;
protected int state; //the player's current state for animation
// 0 = stand, 1 = walk, 2 = act, 3 = cast, 4 = victory
protected int moving; //moving is a declared variable that states when the
// character sprite is moving back and forth so we can
// tell it when it moves
//setting character state is still important because
// that's what controls animation
boolean canCast = true; //determined by if the job can learn spells, if it can
//then the player is marked as not being able to cast
//spells
//constant values for different state animations
public static final int STAND = 1;
public static final int WALK = 2;
public static final int ACT = 3;
public static final int CAST = 4;
public static final int VICT = 5;
public static final int DEAD = 6;
public static final int WEAK = 7;
protected Sprite drawSprite; //sprite to draw to screen that represents the player
protected double x; //sprite position x
protected double y; //sprite position y
protected String jobname; //actual name of the job
private String pathname; //name of the path to the job
/*
* spells are actually learned through items that teach the spell
* but just for current testing purposes and capabilities, they
* will learn the spells they are capable of learning at a level
* automatically
*
* This list is of the spells that job is actually capable of learning
*/
protected List<String> spellList;
/*
* Player equipment in FF1 is a little complex. Players are able
* to have a small personal inventory for holding up to 4 weapons,
* then another one for 4 pieces of armor. They may have up to
* 4 different typed pieces of armor equipped, and only 1 weapon
* equipped.
*/
int weight = 0; //maximum equipment weight
//defines the type of armor the job is able to wear
//currently equipped pieces
Item weapon;
ArrayList<Item> equippedArmor = new ArrayList<Item>();
//currently held pieces
Item[] armor;
Item[] weapons;
/**
* Constructs a basic player
* @param n
*/
public Player(String n, String j)
{
super(n);
name = name.substring(0,Math.min(name.length(), 4)); //char limit of 4
level = 1;
exp = 0;
commands = null;
level = 1;
weapons = new Item[4];
armor = new Item[4];
loadJob(j);
loadSprites();
}
/**
* Constructs a player from a save file ini section
* @param p section that contains the player's data
*/
public Player(Preferences p)
{
this(p.get("name", "aaaa"), p.get("job", "Fighter"));
/**
* loads all the stats for the player,
* if the stats don't exist then just use
* the job's initial stats
*/
level = p.getInt("level", 1);
maxhp = p.getInt("maxhp", maxhp);
setHP(p.getInt("hp", hp));
for (int i = 0; i < mp.length; i++)
{
mp[i][0] = p.getInt("maxMpLvl"+(i+1), mp[i][0]);
mp[i][1] = p.getInt("curMpLvl"+(i+1), mp[i][1]);
}
str = p.getInt("str", str);
itl = p.getInt("int", itl);
spd = p.getInt("spd", spd);
acc = p.getInt("acc", acc);
vit = p.getInt("vit", vit);
mdef = p.getInt("mdef", mdef);
luk = p.getInt("luck", luk);
exp = p.getInt("exp", 0);
}
/**
* Saves a player to the save data file
* @param p
*/
public void savePlayer(Ini ini, String section)
{
ini.put(section, "name", name);
ini.put(section, "job", pathname);
/**
* loads all the stats for the player,
* if the stats don't exist then just use
* the job's initial stats
*/
ini.put(section, "level", level);
ini.put(section, "maxhp", maxhp);
ini.put(section, "hp", hp);
for (int i = 0; i < mp.length; i++)
{
ini.put(section, "maxMpLvl"+(i+1), mp[i][0]);
ini.put(section, "curMpLvl"+(i+1), mp[i][1]);
}
ini.put(section, "str", str);
ini.put(section, "int", itl);
ini.put(section, "spd", spd);
ini.put(section, "acc", acc);
ini.put(section, "vit", vit);
ini.put(section, "mdef", mdef);
ini.put(section, "luck", luk);
ini.put(section, "exp", exp);
}
/**
* Loads the main data for a job
* @param j job name
*/
public void loadJob(String j)
{
pathname = j;
spells = null;
jobname = j;
//set up initial stats if player is level 1
if (level == 1)
try {
Preferences p = new IniPreferences(new Ini(new File("data/actors/jobs/" + pathname + "/job.ini"))).node("initial");
maxhp = p.getInt("hp", 1);
hp = maxhp;
str = p.getInt("str", 1);
itl = p.getInt("int", 1);
spd = p.getInt("spd", 1);
evd = p.getInt("evd", 1);
acc = p.getInt("acc", 1);
vit = p.getInt("vit", 1);
mdef = p.getInt("mdef", 1);
jobname = p.get("name", j);
} catch (Exception e) {
System.err.println("can not find file: " + "data/actors/jobs/" + pathname + "/job.ini\n Initial job stats have not been loaded");
}
def = 0; //def will always be 0 because no equipment is on by default
//load growth curves
growth = new String[MAXLVL+1];
try {
FileInputStream f = new FileInputStream("data/actors/jobs/" + pathname + "/growth.txt");
Scanner s = new Scanner(f);
for (int i = 0; i <= MAXLVL; i++)
growth[i] = s.nextLine();
} catch (Exception e) {
System.err.println("can not find file: " + "data/actors/jobs/" + pathname + "/growth.txt");
Arrays.fill(growth, "");
}
//load mp level table
magicGrowth = new int[MAXLVL+1][8];
try {
FileInputStream f = new FileInputStream("data/actors/jobs/" + pathname + "/magicGrowth.txt");
Scanner s = new Scanner(f);
for (int i = 0; i < MAXLVL; i++)
{
String[] str = s.nextLine().split("/");
for (int x = 0; x < magicGrowth[i].length; x++)
magicGrowth[i][x] = Integer.valueOf(str[x]).intValue();
}
} catch (Exception e) {
System.err.println("can not find file: " + "data/actors/jobs/" + pathname + "/magicGrowth.txt");
}
for (int i = 0; i < mp.length; i++)
{
mp[i][0] = magicGrowth[level-1][i];
mp[i][1] = magicGrowth[level-1][i];
}
//load spells
spells = new Spell[8][3];
try {
FileInputStream f = new FileInputStream("data/actors/jobs/" + pathname + "/spells.txt");
Scanner s = new Scanner(f);
while (s.hasNext())
- {
- String spellName = s.next();
- if (new File("data/spells/" + spellName + "/spell.ini").exists())
- addSpell(Spell.getSpell(spellName));
- }
+ addSpell(Spell.getSpell(s.next()));
} catch (Exception e) {
canCast = false;
}
}
/**
* Get current evasionPlayer
* @return
*/
@Override
public int getEvd() {
return 48+spd;
}
/**
* Loads all the sprites that the job will use in battle
*/
@Override
public void loadSprites()
{
sprites = new Sprite[2];
//battle sprite
sprites[0] = new Sprite("actors/jobs/" + pathname + "/battle.png", 1, 7);
//map wandering sprites
sprites[1] = new Sprite("actors/jobs/" + pathname + "/mapwalk.png", 2, 4);
drawSprite = sprites[0];
}
/**
* Returns the sprite to be rendered
* Animation is very simple in FF1, only flipping between the current
* animation frame for the state and the standing frame.
*/
@Override
public Sprite getSprite() {
return drawSprite;
}
/**
* Curve calculated to figure out the amount of total exp needed to level up
* Cubic-Regression equation calculated from the first 20 levels of the list of
* experience requirements
* @param level
* @return
*/
final public int getExpCurve(int l)
{
return (int)(4.6666666669919*Math.pow(l, 3)+-13.99999999985*Math.pow(l,2)+
37.3333333321*l+-27.9999999985);
}
/**
* @return the amount of exp required to level up
*/
public int getExpToLevel()
{
return getExpCurve(level+1) - exp;
}
/**
* Sets the player's animation state
* @param i The numerical state representation
* also matches up on the battle sprite vertically
*/
public void setState(int i) {
state = i;
}
/**
* Returns the player's animation state
* @return
*/
public int getState() {
return state;
}
/**
* Moves all the player's sprites to position
* @param x
* @param y
*/
public void setPosition(double x, double y)
{
if (Engine.getInstance().getCurrentScene() instanceof BattleScene)
{
setX(x);
setY(y);
}
}
/**
* Moves all the player's sprites x coord to position
* @param x
*/
public void setX(double x)
{
this.x = x;
if (Engine.getInstance().getCurrentScene() instanceof BattleScene)
for (Sprite s : sprites)
s.setX(this.x);
}
/**
* Moves all the player's sprites y coord to position
* @param y
*/
public void setY(double y)
{
this.y = y;
if (Engine.getInstance().getCurrentScene() instanceof BattleScene)
for (Sprite s : sprites)
s.setY(this.y);
}
/**
* Get's the player's sprite's x coordinate
* @return
*/
public double getX()
{
return x;
}
/**
* Get's the player's sprite's y coordinate
* @return
*/
public double getY()
{
return y;
}
/**
* Draws the actor to the screen and animates the graphic
* @param g
*/
@Override
public void draw(Graphics g)
{
if (Engine.getInstance().getCurrentScene() instanceof BattleScene)
{
drawSprite = sprites[0]; //draw sprite is the battle sprite
//if the player is dead show they're dead graphic
if (getState() == DEAD)
drawSprite.setFrame(1, DEAD);
//if the battle is over show victory stances if they're alive
else if (getState() == VICT)
drawSprite.setFrame(1, VICT);
//when they're not standing or dead, they're probably walking
else if (getState() != STAND)
{
//so when it's called and the frame isn't the walk step, switch back to standing
if (drawSprite.getFrame()[1] != STAND)
drawSprite.setFrame(1, STAND);
//if the frame is standing, show walking, or whatever state it is
else
drawSprite.setFrame(1, getState());
}
else
{
//if the player has low HP, show they're weakened frame
if (hp < maxhp*.25)
drawSprite.setFrame(1, WEAK);
//else just show them standing
else
drawSprite.setFrame(1, STAND);
}
}
//if asking for the character sprite and it's not the battle scene, just show them standing
else
{
drawSprite = sprites[0];
drawSprite.setFrame(1, STAND);
}
//draw the sprite
drawSprite.paint(g);
}
/**
* Set step of movement
* @param i
*/
public void setMoving(int i)
{
moving = i;
}
/**
* Get the step of movement
* @return
*/
public int getMoving()
{
return moving;
}
/**
* Retrieves the sprite used to represent the character on a map
* @return
*/
public Sprite getMapSelf() {
return sprites[1];
}
/**
* Retrieves the sprites that are used for the job
* @return
*/
public Sprite[] getSprites()
{
return sprites;
}
/**
* Retrieves the name by with the job is identified
* @return
*/
public String getJobName() {
return jobname;
}
/*
* Players have overriding getter methods for stats that have
* equipment stat buffs factored in.
*/
/**
* Retrieves current str
* @return
*/
@Override
public int getStr() {
int i = str;
if (weapon != null)
i += weapon.getStr();
return i;
}
/**
* Gets current def
* @return
*/
@Override
public int getDef() {
int i = def;
for (int n = 0; n < equippedArmor.size(); n++)
i += equippedArmor.get(n).getDef();
return i;
}
/**
* Get current spd
* @return
*/
@Override
public int getSpd() {
int i = spd;
for (int n = 0; n < equippedArmor.size(); n++)
i += equippedArmor.get(n).getSpd();
return i;
}
/**
* Get accuracy
* @return
*/
@Override
public int getAcc() {
int i = acc;
for (int n = 0; n < equippedArmor.size(); n++)
i += equippedArmor.get(n).getAcc();
return i;
}
/**
* Get vitality
* @return
*/
@Override
public int getVit() {
int i = vit;
for (int n = 0; n < equippedArmor.size(); n++)
i += equippedArmor.get(n).getVit();
return i;
}
/**
* Get intelligence
* @return
*/
@Override
public int getInt() {
int i = itl;
for (int n = 0; n < equippedArmor.size(); n++)
i += equippedArmor.get(n).getInt();
return i;
}
/**
* Get magic def
* @return
*/
@Override
public int getMDef() {
int i = mdef;
for (int n = 0; n < equippedArmor.size(); n++)
i += equippedArmor.get(n).getMDef();
return i;
}
/*
* Jobs do not have setter methods for retrieving stat values.
* This is because stat getters should be equations dependent on
* the actor's level. Additionally, these should only be
* called upon level up.
* @param lvl
* level of the actor
* @return
* the value of the stat when that actor is at the passed level
*/
/**
* Strength growth on level up
*/
protected int getStr(int lvl)
{
if (growth[lvl].contains("S"))
return 1;
else
return (Math.random() < .25)?0:1;
}
/**
* Speed/Agility growth on level up
*/
protected int getSpd(int lvl)
{
if (growth[lvl].contains("A"))
return 1;
else
return (Math.random() < .25)?0:1;
}
/**
* Intellegence growth on level up
*/
protected int getInt(int lvl)
{
if (growth[lvl].contains("I"))
return 1;
else
return (Math.random() < .25)?0:1;
}
/**
* Luck growth on level up
*/
protected int getLuck(int lvl)
{
if (growth[lvl].contains("L"))
return 1;
else
return (Math.random() < .25)?0:1;
}
/**
* Get vitality on level up
*/
protected int getVit(int lvl)
{
if (growth[lvl].contains("V"))
return 1;
else
return (Math.random() < .25)?0:1;
}
/**
* Growth for Hit%/Acc is linear
*/
protected int getAcc(int lvl)
{
return Integer.valueOf(growth[0]).intValue();
}
/**
* Growth for Hit%/Acc is linear
*/
protected int getMDef(int lvl)
{
return Integer.valueOf(growth[1]).intValue();
}
/**
* HP can have strong levels where hp will go
* up the default vit/4 plus an additional 20-25 points
*/
protected int getHP(int lvl)
{
int i = vit/4;
if (growth[lvl].contains("+"))
i += Math.random() * 5 + 20;
return i;
}
/**
* When required exp is met, the player will level up
* all the player's stats will be updated
* Defense does not grow because def is determined by armor
*/
public void levelUp()
{
level++;
//stats for level 1 are force on instantiation
// never should it ask for less than 2, error trap just in case
if (level < 2)
return;
vit += getVit(level);
maxhp += getHP(level);
hp = maxhp;
str += getStr(level);
spd += getSpd(level);
itl += getInt(level);
mdef += getMDef(level);
acc += getAcc(level);
luk += getLuck(level);
evd += getEvd();
for (int i = 0; i < mp.length; i++)
{
mp[i][0] = magicGrowth[level-1][i];
mp[i][1] = magicGrowth[level-1][i];
}
//reset exp
exp = 0;
}
/**
* @return a string representation of a message that shows the increase in each stat
*/
public List<String> previewLevelUp()
{
List<String> output = new ArrayList<String>();
output.add(getVit(level) + " vit");
output.add(getHP(level) + " hp");
output.add(getStr(level) + " str");
output.add(getSpd(level) + " spd");
output.add(getInt(level) + " int");
//output += getMDef(level) + " mdef\n";
//output += getAcc(level) + " hit %\n";
return output;
}
/**
* @return is the player able to cast magic
*/
public boolean canCast()
{
return canCast;
}
/**
* @return the currently equipped weapon of the player
*/
public Item getWeapon() {
return weapon;
}
/**
* @return the weapons that the player is carrying
*/
public Item[] getWeapons() {
return weapons;
}
/**
* Equips the weapon
* @param w the weapon to equip
*/
public void setWeapon(Item w) {
//weight also applies to weapon weight
if (w == null || w.isEquipment() && w.getWeight() <= weight)
weapon = w;
}
/**
* @return armor in player's possession
*/
public Item[] getArmor() {
return armor;
}
/**
* @return the armor that is currently being worn
*/
public Item[] getEquippedArmor(){
return equippedArmor.toArray(new Item[]{});
}
/**
* Checks to see if the player is currently wearing the piece of armor
* @param item piece of armor
* @return
*/
public boolean isWearing(Item item) {
//ignore null items
if (item == null)
return false;
return equippedArmor.contains(item);
}
/**
* Equips a piece of armor
* @param i
* @return if the piece was able to be equipped or not
*/
public boolean wearArmor(Item armor)
{
if (armor.isEquipment() && armor.getWeight() <= weight)
{
//only equip the armor if there is a piece of armor of that type that is not already equipped
for (int i = 0; i < equippedArmor.size(); i++)
if (armor.getArmorSlot() == equippedArmor.get(i).getArmorSlot())
return false;
equippedArmor.add(armor);
return true;
}
return false;
}
/**
* Removes a piece of armor
* @param i
*/
public void takeOffArmor(Item i)
{
equippedArmor.remove(i);
}
/**
* Adds a weapon to hold
* @param i
* @return if the player was able to hold the weapon
*/
public boolean holdWeapon(Item i)
{
//can't hold weapon because the item isn't a weapon
if (!i.isEquipment() && i.getEquipmentType() == Item.WEAPON_TYPE)
return false;
for (int n = 0; n < weapons.length; n++)
if (weapons[n] == null)
{
weapons[n] = i;
return true;
}
return false;
}
/**
* Adds a piece of armor to hold
* @param i
* @return if the player was able to hold the piece of armor
*/
public boolean holdArmor(Item i)
{
//can't hold armor because the item isn't a piece of armor
if (!i.isEquipment())
return false;
for (int n = 0; n < armor.length; n++)
if (armor[n] == null)
{
armor[n] = i;
return true;
}
return false;
}
/**
* Adds a set amount of exp to how much the player has earned
* @param i
*/
public void addExp(int i)
{
exp += i;
}
}
| true | true | public void loadJob(String j)
{
pathname = j;
spells = null;
jobname = j;
//set up initial stats if player is level 1
if (level == 1)
try {
Preferences p = new IniPreferences(new Ini(new File("data/actors/jobs/" + pathname + "/job.ini"))).node("initial");
maxhp = p.getInt("hp", 1);
hp = maxhp;
str = p.getInt("str", 1);
itl = p.getInt("int", 1);
spd = p.getInt("spd", 1);
evd = p.getInt("evd", 1);
acc = p.getInt("acc", 1);
vit = p.getInt("vit", 1);
mdef = p.getInt("mdef", 1);
jobname = p.get("name", j);
} catch (Exception e) {
System.err.println("can not find file: " + "data/actors/jobs/" + pathname + "/job.ini\n Initial job stats have not been loaded");
}
def = 0; //def will always be 0 because no equipment is on by default
//load growth curves
growth = new String[MAXLVL+1];
try {
FileInputStream f = new FileInputStream("data/actors/jobs/" + pathname + "/growth.txt");
Scanner s = new Scanner(f);
for (int i = 0; i <= MAXLVL; i++)
growth[i] = s.nextLine();
} catch (Exception e) {
System.err.println("can not find file: " + "data/actors/jobs/" + pathname + "/growth.txt");
Arrays.fill(growth, "");
}
//load mp level table
magicGrowth = new int[MAXLVL+1][8];
try {
FileInputStream f = new FileInputStream("data/actors/jobs/" + pathname + "/magicGrowth.txt");
Scanner s = new Scanner(f);
for (int i = 0; i < MAXLVL; i++)
{
String[] str = s.nextLine().split("/");
for (int x = 0; x < magicGrowth[i].length; x++)
magicGrowth[i][x] = Integer.valueOf(str[x]).intValue();
}
} catch (Exception e) {
System.err.println("can not find file: " + "data/actors/jobs/" + pathname + "/magicGrowth.txt");
}
for (int i = 0; i < mp.length; i++)
{
mp[i][0] = magicGrowth[level-1][i];
mp[i][1] = magicGrowth[level-1][i];
}
//load spells
spells = new Spell[8][3];
try {
FileInputStream f = new FileInputStream("data/actors/jobs/" + pathname + "/spells.txt");
Scanner s = new Scanner(f);
while (s.hasNext())
{
String spellName = s.next();
if (new File("data/spells/" + spellName + "/spell.ini").exists())
addSpell(Spell.getSpell(spellName));
}
} catch (Exception e) {
canCast = false;
}
}
| public void loadJob(String j)
{
pathname = j;
spells = null;
jobname = j;
//set up initial stats if player is level 1
if (level == 1)
try {
Preferences p = new IniPreferences(new Ini(new File("data/actors/jobs/" + pathname + "/job.ini"))).node("initial");
maxhp = p.getInt("hp", 1);
hp = maxhp;
str = p.getInt("str", 1);
itl = p.getInt("int", 1);
spd = p.getInt("spd", 1);
evd = p.getInt("evd", 1);
acc = p.getInt("acc", 1);
vit = p.getInt("vit", 1);
mdef = p.getInt("mdef", 1);
jobname = p.get("name", j);
} catch (Exception e) {
System.err.println("can not find file: " + "data/actors/jobs/" + pathname + "/job.ini\n Initial job stats have not been loaded");
}
def = 0; //def will always be 0 because no equipment is on by default
//load growth curves
growth = new String[MAXLVL+1];
try {
FileInputStream f = new FileInputStream("data/actors/jobs/" + pathname + "/growth.txt");
Scanner s = new Scanner(f);
for (int i = 0; i <= MAXLVL; i++)
growth[i] = s.nextLine();
} catch (Exception e) {
System.err.println("can not find file: " + "data/actors/jobs/" + pathname + "/growth.txt");
Arrays.fill(growth, "");
}
//load mp level table
magicGrowth = new int[MAXLVL+1][8];
try {
FileInputStream f = new FileInputStream("data/actors/jobs/" + pathname + "/magicGrowth.txt");
Scanner s = new Scanner(f);
for (int i = 0; i < MAXLVL; i++)
{
String[] str = s.nextLine().split("/");
for (int x = 0; x < magicGrowth[i].length; x++)
magicGrowth[i][x] = Integer.valueOf(str[x]).intValue();
}
} catch (Exception e) {
System.err.println("can not find file: " + "data/actors/jobs/" + pathname + "/magicGrowth.txt");
}
for (int i = 0; i < mp.length; i++)
{
mp[i][0] = magicGrowth[level-1][i];
mp[i][1] = magicGrowth[level-1][i];
}
//load spells
spells = new Spell[8][3];
try {
FileInputStream f = new FileInputStream("data/actors/jobs/" + pathname + "/spells.txt");
Scanner s = new Scanner(f);
while (s.hasNext())
addSpell(Spell.getSpell(s.next()));
} catch (Exception e) {
canCast = false;
}
}
|
diff --git a/Fanorona/test/team01/BoardTest.java b/Fanorona/test/team01/BoardTest.java
index 23e759b..b2328ac 100644
--- a/Fanorona/test/team01/BoardTest.java
+++ b/Fanorona/test/team01/BoardTest.java
@@ -1,136 +1,136 @@
package team01;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class BoardTest {
private Board board;
private Move move;
@Before
public void setUp() throws Exception {
board = new Board(9, 5);
move = new Move(board);
}
@Test
- public void avaiableMovesTest() {
+ public void availableMovesTest() {
int player = Board.WHITE;
assertEquals(board.numWhite(), 22);
assertEquals(board.numBlack(), 22);
assertEquals(board.numEmpty(), 1);
board.setPosition(new Point(2, 2), Board.EMPTY);
board.setPosition(new Point(3, 2), Board.EMPTY);
assertEquals(board.numWhite(), 21);
assertEquals(board.numBlack(), 21);
assertEquals(board.numEmpty(), 3);
System.out.println(board);
int count = 0;
System.out.println("available moves");
for (Point from : board)
{
if (board.getPosition(from) == player)
{
// TODO: possibly add a delta iterator?
for (int dx = Delta.MIN_DELTA; dx <= Delta.MAX_DELTA; dx++)
{
for (int dy = Delta.MIN_DELTA; dy <= Delta.MAX_DELTA; dy++)
{
Point to = from.getApproach(dx, dy);
if (move.isValidMove(from, to))
{
++ count;
System.out.printf("%s -> %s\n", from, to);
}
}
}
}
}
assertEquals(count, 8);
System.out.println();
}
@Test
public void approachUpTest() {
assertEquals(board.numWhite(), 22);
assertEquals(board.numBlack(), 22);
assertEquals(board.numEmpty(), 1);
Point from = new Point(4, 3);
Point to = new Point(4, 2);
System.out.println("before:");
System.out.println(board);
assertTrue(move.isValidMove(from, to));
assertFalse(move.approach(from, to));
assertEquals(board.numWhite(), 22);
assertEquals(board.numBlack(), 20);
assertEquals(board.numEmpty(), 3);
System.out.println("after:");
System.out.println(board);
}
@Test
public void approachDiagTest() {
assertEquals(board.numWhite(), 22);
assertEquals(board.numBlack(), 22);
assertEquals(board.numEmpty(), 1);
Point from = new Point(3, 3);
Point to = new Point(4, 2);
System.out.println("before:");
System.out.println(board);
assertTrue(move.isValidMove(from, to));
assertFalse(move.approach(from, to));
assertEquals(board.numWhite(), 22);
assertEquals(board.numBlack(), 20);
assertEquals(board.numEmpty(), 3);
System.out.println("after:");
System.out.println(board);
}
@Test
public void approachSideTest() {
assertEquals(board.numWhite(), 22);
assertEquals(board.numBlack(), 22);
assertEquals(board.numEmpty(), 1);
Point from = new Point(3, 2);
Point to = new Point(4, 2);
System.out.println("before:");
System.out.println(board);
assertTrue(move.isValidMove(from, to));
assertFalse(move.approach(from, to));
assertEquals(board.numWhite(), 22);
assertEquals(board.numBlack(), 21);
assertEquals(board.numEmpty(), 2);
System.out.println("after:");
System.out.println(board);
}
}
| true | true | public void avaiableMovesTest() {
int player = Board.WHITE;
assertEquals(board.numWhite(), 22);
assertEquals(board.numBlack(), 22);
assertEquals(board.numEmpty(), 1);
board.setPosition(new Point(2, 2), Board.EMPTY);
board.setPosition(new Point(3, 2), Board.EMPTY);
assertEquals(board.numWhite(), 21);
assertEquals(board.numBlack(), 21);
assertEquals(board.numEmpty(), 3);
System.out.println(board);
int count = 0;
System.out.println("available moves");
for (Point from : board)
{
if (board.getPosition(from) == player)
{
// TODO: possibly add a delta iterator?
for (int dx = Delta.MIN_DELTA; dx <= Delta.MAX_DELTA; dx++)
{
for (int dy = Delta.MIN_DELTA; dy <= Delta.MAX_DELTA; dy++)
{
Point to = from.getApproach(dx, dy);
if (move.isValidMove(from, to))
{
++ count;
System.out.printf("%s -> %s\n", from, to);
}
}
}
}
}
assertEquals(count, 8);
System.out.println();
}
| public void availableMovesTest() {
int player = Board.WHITE;
assertEquals(board.numWhite(), 22);
assertEquals(board.numBlack(), 22);
assertEquals(board.numEmpty(), 1);
board.setPosition(new Point(2, 2), Board.EMPTY);
board.setPosition(new Point(3, 2), Board.EMPTY);
assertEquals(board.numWhite(), 21);
assertEquals(board.numBlack(), 21);
assertEquals(board.numEmpty(), 3);
System.out.println(board);
int count = 0;
System.out.println("available moves");
for (Point from : board)
{
if (board.getPosition(from) == player)
{
// TODO: possibly add a delta iterator?
for (int dx = Delta.MIN_DELTA; dx <= Delta.MAX_DELTA; dx++)
{
for (int dy = Delta.MIN_DELTA; dy <= Delta.MAX_DELTA; dy++)
{
Point to = from.getApproach(dx, dy);
if (move.isValidMove(from, to))
{
++ count;
System.out.printf("%s -> %s\n", from, to);
}
}
}
}
}
assertEquals(count, 8);
System.out.println();
}
|
diff --git a/src/main/java/hudson/plugins/bazaar/BazaarChangeLogParser.java b/src/main/java/hudson/plugins/bazaar/BazaarChangeLogParser.java
index eb6dbd2..919ca58 100644
--- a/src/main/java/hudson/plugins/bazaar/BazaarChangeLogParser.java
+++ b/src/main/java/hudson/plugins/bazaar/BazaarChangeLogParser.java
@@ -1,216 +1,217 @@
package hudson.plugins.bazaar;
import hudson.model.AbstractBuild;
import hudson.scm.ChangeLogParser;
import hudson.scm.EditType;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
/**
* Parses the output of bzr log.
*
* @author Trond Norbye
*/
public class BazaarChangeLogParser extends ChangeLogParser {
public BazaarChangeSetList parse(AbstractBuild build, File changelogFile) throws IOException {
List<BazaarChangeSet> entries = new ArrayList<BazaarChangeSet>();
BufferedReader in = new BufferedReader(new FileReader(changelogFile));
StringBuilder message = new StringBuilder();
String s;
BazaarChangeSet entry = null;
int state = 0;
int ident = 0;
while ((s = in.readLine()) != null) {
int nident = 0;
int len = s.length();
while (nident < len && s.charAt(nident) == ' ') {
++nident;
}
s = s.trim();
len = s.length();
if ("------------------------------------------------------------".equals(s)) {
if (entry != null && state > 2) {
if (message.length() != 0) {
entry.setMsg(message.toString());
}
entries.add(entry);
}
entry = new BazaarChangeSet();
state = 0;
message.setLength(0);
ident = nident;
continue;
}
switch (state) {
case 0:
if (ident == nident && s.startsWith("revno:")) {
String rev = s.substring("revno:".length()).trim();
if (rev.contains("[merge]")) {
entry.setMerge(true);
rev = rev.substring(0, rev.length() - "[merge]".length()).trim();
}
entry.setRevno(rev);
++state;
}
break;
case 1:
if (ident == nident && s.startsWith("tags:")) {
String tags = s.substring("tags:".length()).trim();
entry.setTags(Arrays.asList(tags.split(", ")));
}
if (ident == nident && s.startsWith("revision-id:")) {
String rev = s.substring("revision-id:".length()).trim();
entry.setRevid(rev);
++state;
}
break;
case 2:
if (ident == nident && s.startsWith("committer:")) {
int emailStartIndex = s.indexOf('<');
String author = s.substring("committer:".length(), emailStartIndex < 0 ? len : emailStartIndex).trim();
entry.setAuthor(author);
if (emailStartIndex >= 0) {
int emailEndIndex = s.indexOf('>');
if (emailEndIndex >= emailStartIndex) {
String authorEmail = s.substring(1 + emailStartIndex, emailEndIndex).trim();
entry.setAuthorEmail(authorEmail);
}
}
++state;
}
break;
case 3:
if (ident == nident && s.startsWith("timestamp:")) {
entry.setDate(s.substring("timestamp:".length()).trim());
++state;
}
break;
case 4:
if (!(ident == nident && s.startsWith("message:"))) {
if (ident == nident && (s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:") || s.startsWith("renamed:"))) {
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
}
entry.setMsg(message.toString());
message.setLength(0);
} else {
if (message.length() != 0) {
message.append("\n");
}
message.append(s);
}
}
break;
case 5: // modified
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.EDIT, s));
}
break;
case 6: // added
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.ADD, s));
}
break;
case 7: // removed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.DELETE, s));
}
break;
case 8: // renamed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.EDIT, s));
}
break;
default: {
Logger logger = Logger.getLogger(BazaarChangeLogParser.class.getName());
logger.warning("Unknown parser state: " + state);
}
}
}
if (entry != null && state > 2) {
if (message.length() != 0) {
entry.setMsg(message.toString());
}
entries.add(entry);
}
// Remove current revision entry
entries = entries.subList(0, Math.max(0 ,entries.size() -1));
+ in.close();
return new BazaarChangeSetList(build, entries);
}
private BazaarAffectedFile createAffectedFile(EditType editType, String changelogLine) {
String oldPath = null;
String path = changelogLine.trim();
String fileId = "";
int index = changelogLine.lastIndexOf(' ');
if (index >= 0) {
path = changelogLine.substring(0, index).trim();
fileId = changelogLine.substring(index, changelogLine.length()).trim();
}
if (path.contains("=>")) {
String[] paths = path.split("=>");
oldPath = paths[0].trim();
path = paths[1].trim();
}
return new BazaarAffectedFile(editType, oldPath, path, fileId);
}
}
| true | true | public BazaarChangeSetList parse(AbstractBuild build, File changelogFile) throws IOException {
List<BazaarChangeSet> entries = new ArrayList<BazaarChangeSet>();
BufferedReader in = new BufferedReader(new FileReader(changelogFile));
StringBuilder message = new StringBuilder();
String s;
BazaarChangeSet entry = null;
int state = 0;
int ident = 0;
while ((s = in.readLine()) != null) {
int nident = 0;
int len = s.length();
while (nident < len && s.charAt(nident) == ' ') {
++nident;
}
s = s.trim();
len = s.length();
if ("------------------------------------------------------------".equals(s)) {
if (entry != null && state > 2) {
if (message.length() != 0) {
entry.setMsg(message.toString());
}
entries.add(entry);
}
entry = new BazaarChangeSet();
state = 0;
message.setLength(0);
ident = nident;
continue;
}
switch (state) {
case 0:
if (ident == nident && s.startsWith("revno:")) {
String rev = s.substring("revno:".length()).trim();
if (rev.contains("[merge]")) {
entry.setMerge(true);
rev = rev.substring(0, rev.length() - "[merge]".length()).trim();
}
entry.setRevno(rev);
++state;
}
break;
case 1:
if (ident == nident && s.startsWith("tags:")) {
String tags = s.substring("tags:".length()).trim();
entry.setTags(Arrays.asList(tags.split(", ")));
}
if (ident == nident && s.startsWith("revision-id:")) {
String rev = s.substring("revision-id:".length()).trim();
entry.setRevid(rev);
++state;
}
break;
case 2:
if (ident == nident && s.startsWith("committer:")) {
int emailStartIndex = s.indexOf('<');
String author = s.substring("committer:".length(), emailStartIndex < 0 ? len : emailStartIndex).trim();
entry.setAuthor(author);
if (emailStartIndex >= 0) {
int emailEndIndex = s.indexOf('>');
if (emailEndIndex >= emailStartIndex) {
String authorEmail = s.substring(1 + emailStartIndex, emailEndIndex).trim();
entry.setAuthorEmail(authorEmail);
}
}
++state;
}
break;
case 3:
if (ident == nident && s.startsWith("timestamp:")) {
entry.setDate(s.substring("timestamp:".length()).trim());
++state;
}
break;
case 4:
if (!(ident == nident && s.startsWith("message:"))) {
if (ident == nident && (s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:") || s.startsWith("renamed:"))) {
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
}
entry.setMsg(message.toString());
message.setLength(0);
} else {
if (message.length() != 0) {
message.append("\n");
}
message.append(s);
}
}
break;
case 5: // modified
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.EDIT, s));
}
break;
case 6: // added
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.ADD, s));
}
break;
case 7: // removed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.DELETE, s));
}
break;
case 8: // renamed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.EDIT, s));
}
break;
default: {
Logger logger = Logger.getLogger(BazaarChangeLogParser.class.getName());
logger.warning("Unknown parser state: " + state);
}
}
}
if (entry != null && state > 2) {
if (message.length() != 0) {
entry.setMsg(message.toString());
}
entries.add(entry);
}
// Remove current revision entry
entries = entries.subList(0, Math.max(0 ,entries.size() -1));
return new BazaarChangeSetList(build, entries);
}
| public BazaarChangeSetList parse(AbstractBuild build, File changelogFile) throws IOException {
List<BazaarChangeSet> entries = new ArrayList<BazaarChangeSet>();
BufferedReader in = new BufferedReader(new FileReader(changelogFile));
StringBuilder message = new StringBuilder();
String s;
BazaarChangeSet entry = null;
int state = 0;
int ident = 0;
while ((s = in.readLine()) != null) {
int nident = 0;
int len = s.length();
while (nident < len && s.charAt(nident) == ' ') {
++nident;
}
s = s.trim();
len = s.length();
if ("------------------------------------------------------------".equals(s)) {
if (entry != null && state > 2) {
if (message.length() != 0) {
entry.setMsg(message.toString());
}
entries.add(entry);
}
entry = new BazaarChangeSet();
state = 0;
message.setLength(0);
ident = nident;
continue;
}
switch (state) {
case 0:
if (ident == nident && s.startsWith("revno:")) {
String rev = s.substring("revno:".length()).trim();
if (rev.contains("[merge]")) {
entry.setMerge(true);
rev = rev.substring(0, rev.length() - "[merge]".length()).trim();
}
entry.setRevno(rev);
++state;
}
break;
case 1:
if (ident == nident && s.startsWith("tags:")) {
String tags = s.substring("tags:".length()).trim();
entry.setTags(Arrays.asList(tags.split(", ")));
}
if (ident == nident && s.startsWith("revision-id:")) {
String rev = s.substring("revision-id:".length()).trim();
entry.setRevid(rev);
++state;
}
break;
case 2:
if (ident == nident && s.startsWith("committer:")) {
int emailStartIndex = s.indexOf('<');
String author = s.substring("committer:".length(), emailStartIndex < 0 ? len : emailStartIndex).trim();
entry.setAuthor(author);
if (emailStartIndex >= 0) {
int emailEndIndex = s.indexOf('>');
if (emailEndIndex >= emailStartIndex) {
String authorEmail = s.substring(1 + emailStartIndex, emailEndIndex).trim();
entry.setAuthorEmail(authorEmail);
}
}
++state;
}
break;
case 3:
if (ident == nident && s.startsWith("timestamp:")) {
entry.setDate(s.substring("timestamp:".length()).trim());
++state;
}
break;
case 4:
if (!(ident == nident && s.startsWith("message:"))) {
if (ident == nident && (s.startsWith("modified:") || s.startsWith("added:") || s.startsWith("removed:") || s.startsWith("renamed:"))) {
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
}
entry.setMsg(message.toString());
message.setLength(0);
} else {
if (message.length() != 0) {
message.append("\n");
}
message.append(s);
}
}
break;
case 5: // modified
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.EDIT, s));
}
break;
case 6: // added
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.ADD, s));
}
break;
case 7: // removed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.DELETE, s));
}
break;
case 8: // renamed
if (s.startsWith("modified")) {
state = 5;
} else if (s.startsWith("added:")) {
state = 6;
} else if (s.startsWith("removed:")) {
state = 7;
} else if (s.startsWith("renamed:")){
state = 8;
} else {
entry.addAffectedFile(createAffectedFile(EditType.EDIT, s));
}
break;
default: {
Logger logger = Logger.getLogger(BazaarChangeLogParser.class.getName());
logger.warning("Unknown parser state: " + state);
}
}
}
if (entry != null && state > 2) {
if (message.length() != 0) {
entry.setMsg(message.toString());
}
entries.add(entry);
}
// Remove current revision entry
entries = entries.subList(0, Math.max(0 ,entries.size() -1));
in.close();
return new BazaarChangeSetList(build, entries);
}
|
diff --git a/src/tesla/app/ui/AbstractTeslaActivity.java b/src/tesla/app/ui/AbstractTeslaActivity.java
index ca59cf6..fd2452b 100644
--- a/src/tesla/app/ui/AbstractTeslaActivity.java
+++ b/src/tesla/app/ui/AbstractTeslaActivity.java
@@ -1,239 +1,241 @@
/* Copyright 2009 Sean Hodges <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tesla.app.ui;
import tesla.app.command.Command;
import tesla.app.command.provider.AppConfigProvider;
import tesla.app.service.CommandService;
import tesla.app.service.business.ICommandController;
import tesla.app.service.business.IErrorHandler;
import tesla.app.ui.task.GetMediaInfoTask;
import tesla.app.ui.task.GetVolumeLevelTask;
import tesla.app.ui.task.IsPlayingTask;
import tesla.app.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteException;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
public abstract class AbstractTeslaActivity extends Activity {
protected ICommandController commandService;
private PowerManager.WakeLock wakeLock;
private boolean phoneIsBusy = false;
protected ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
commandService = ICommandController.Stub.asInterface(service);
// Detect phone calls
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
tm.listen(callStateHandler, PhoneStateListener.LISTEN_CALL_STATE);
onTeslaServiceConnected();
}
public void onServiceDisconnected(ComponentName name) {
commandService = null;
onTeslaServiceDisconnected();
}
};
protected IErrorHandler errorHandler = new IErrorHandler.Stub() {
public void onServiceError(String title, String message, boolean fatal) throws RemoteException {
showErrorMessage(AbstractTeslaActivity.this.getClass(), title, message, null);
}
};
private PhoneStateListener callStateHandler = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
case TelephonyManager.CALL_STATE_OFFHOOK:
// Pause playback during a call
if (!phoneIsBusy) {
phoneIsBusy = true;
try {
commandService.registerErrorHandler(errorHandler);
Command command = commandService.queryForCommand(Command.PAUSE);
if (command != null) {
commandService.sendCommand(command);
onPhoneIsBusy();
}
commandService.unregisterErrorHandler(errorHandler);
} catch (RemoteException e) {
// Failed to send command
e.printStackTrace();
}
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Resume playback when call ends
if (phoneIsBusy) {
phoneIsBusy = false;
try {
commandService.registerErrorHandler(errorHandler);
Command command = commandService.queryForCommand(Command.PLAY);
if (command != null) {
commandService.sendCommand(command);
onPhoneIsIdle();
}
commandService.unregisterErrorHandler(errorHandler);
} catch (RemoteException e) {
// Failed to send command
e.printStackTrace();
}
}
default:
// Do nothing
}
}
};
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Used to keep the Wifi available as long as the activity is running
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Tesla SSH session");
}
protected void onPause() {
super.onPause();
if (connection != null) unbindService(connection);
wakeLock.release();
}
protected void onResume() {
super.onResume();
wakeLock.acquire();
bindService(new Intent(AbstractTeslaActivity.this, CommandService.class), connection, Context.BIND_AUTO_CREATE);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_HOME:
// If the HOME button is pressed, the application is shutting down.
// Therefore, stop the service...
stopService(new Intent(AbstractTeslaActivity.this, CommandService.class));
}
return super.onKeyDown(keyCode, event);
}
protected abstract void onTeslaServiceConnected();
protected abstract void onTeslaServiceDisconnected();
protected abstract void onPhoneIsBusy();
protected abstract void onPhoneIsIdle();
protected void showErrorMessage(Class<? extends Object> invoker, String title, String message, Command command) {
if (!isFinishing()) {
// Digest message for user-friendly display
String errorCode = generateErrorCode(invoker, title, command);
title = getResources().getString(R.string.user_error_title);
message = getResources().getString(R.string.user_error_body);
message = message.replaceAll("%errorcode%", errorCode);
// Show error message
new AlertDialog.Builder(AbstractTeslaActivity.this)
.setTitle(title)
.setMessage(message)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// Close the activity to avoid more of these
finish();
}
})
.show();
}
}
private String generateErrorCode(Class<? extends Object> invoker, String title, Command command) {
// This is a little hacky, but should suffice for the time being
// Get the invoker ID
int idInvoker = 0;
if (invoker.equals(Playback.class)) { idInvoker = 1; }
else if (invoker.equals(VolumeControl.class)) { idInvoker = 2; }
else if (invoker.equals(GetMediaInfoTask.class)) { idInvoker = 3; }
else if (invoker.equals(GetVolumeLevelTask.class)) { idInvoker = 4; }
else if (invoker.equals(IsPlayingTask.class)) { idInvoker = 5; }
// Get the service function ID
int idServiceCall = 0;
if (title.equals("Failed to connect to remote machine")) { idServiceCall = 1; } // Failed to connect
if (title.equals("Failed to send command to remote machine")) { idServiceCall = 2; } // Failed to send command
if (title.equals("Failed to send query to remote machine")) { idServiceCall = 3; } // Failed to perform query
int idApp = 0;
int idCommand = 0;
if (command != null) {
// Get the player ID
String app = command.getTargetApp();
if (app.equals(AppConfigProvider.APP_AMAROK)) { idApp = 1; }
else if (app.equals(AppConfigProvider.APP_BANSHEE)) { idApp = 2; }
else if (app.equals(AppConfigProvider.APP_DRAGONPLAYER)) { idApp = 3; }
else if (app.equals(AppConfigProvider.APP_RHYTHMBOX)) { idApp = 4; }
else if (app.equals(AppConfigProvider.APP_TOTEM)) { idApp = 5; }
else if (app.equals(AppConfigProvider.APP_VLC)) { idApp = 6; }
else if (app.equals(AppConfigProvider.APP_EXAILE)) { idApp = 7; }
+ else if (app.equals(AppConfigProvider.APP_KAFFEINE)) { idApp = 8; }
// Get the command ID
String commandKey = command.getKey();
if (commandKey.equals(Command.GET_MEDIA_INFO)) { idCommand = 1; }
else if (commandKey.equals(Command.INIT)) { idCommand = 2; }
else if (commandKey.equals(Command.IS_PLAYING)) { idCommand = 3; }
else if (commandKey.equals(Command.NEXT)) { idCommand = 4; }
else if (commandKey.equals(Command.PAUSE)) { idCommand = 5; }
else if (commandKey.equals(Command.PLAY)) { idCommand = 6; }
else if (commandKey.equals(Command.POWER)) { idCommand = 7; }
else if (commandKey.equals(Command.PREV)) { idCommand = 8; }
else if (commandKey.equals(Command.VOL_CHANGE)) { idCommand = 9; }
else if (commandKey.equals(Command.VOL_CURRENT)) { idCommand = 10; }
else if (commandKey.equals(Command.VOL_MUTE)) { idCommand = 11; }
+ else if (commandKey.equals(Command.LAUNCH_PLAYER)) { idCommand = 12; }
}
// Build the code
StringBuilder builder = new StringBuilder();
builder.append("8"); // Sanity number
builder.append(idInvoker);
builder.append(idServiceCall);
builder.append(idApp);
builder.append(idCommand);
return builder.toString();
}
}
| false | true | private String generateErrorCode(Class<? extends Object> invoker, String title, Command command) {
// This is a little hacky, but should suffice for the time being
// Get the invoker ID
int idInvoker = 0;
if (invoker.equals(Playback.class)) { idInvoker = 1; }
else if (invoker.equals(VolumeControl.class)) { idInvoker = 2; }
else if (invoker.equals(GetMediaInfoTask.class)) { idInvoker = 3; }
else if (invoker.equals(GetVolumeLevelTask.class)) { idInvoker = 4; }
else if (invoker.equals(IsPlayingTask.class)) { idInvoker = 5; }
// Get the service function ID
int idServiceCall = 0;
if (title.equals("Failed to connect to remote machine")) { idServiceCall = 1; } // Failed to connect
if (title.equals("Failed to send command to remote machine")) { idServiceCall = 2; } // Failed to send command
if (title.equals("Failed to send query to remote machine")) { idServiceCall = 3; } // Failed to perform query
int idApp = 0;
int idCommand = 0;
if (command != null) {
// Get the player ID
String app = command.getTargetApp();
if (app.equals(AppConfigProvider.APP_AMAROK)) { idApp = 1; }
else if (app.equals(AppConfigProvider.APP_BANSHEE)) { idApp = 2; }
else if (app.equals(AppConfigProvider.APP_DRAGONPLAYER)) { idApp = 3; }
else if (app.equals(AppConfigProvider.APP_RHYTHMBOX)) { idApp = 4; }
else if (app.equals(AppConfigProvider.APP_TOTEM)) { idApp = 5; }
else if (app.equals(AppConfigProvider.APP_VLC)) { idApp = 6; }
else if (app.equals(AppConfigProvider.APP_EXAILE)) { idApp = 7; }
// Get the command ID
String commandKey = command.getKey();
if (commandKey.equals(Command.GET_MEDIA_INFO)) { idCommand = 1; }
else if (commandKey.equals(Command.INIT)) { idCommand = 2; }
else if (commandKey.equals(Command.IS_PLAYING)) { idCommand = 3; }
else if (commandKey.equals(Command.NEXT)) { idCommand = 4; }
else if (commandKey.equals(Command.PAUSE)) { idCommand = 5; }
else if (commandKey.equals(Command.PLAY)) { idCommand = 6; }
else if (commandKey.equals(Command.POWER)) { idCommand = 7; }
else if (commandKey.equals(Command.PREV)) { idCommand = 8; }
else if (commandKey.equals(Command.VOL_CHANGE)) { idCommand = 9; }
else if (commandKey.equals(Command.VOL_CURRENT)) { idCommand = 10; }
else if (commandKey.equals(Command.VOL_MUTE)) { idCommand = 11; }
}
// Build the code
StringBuilder builder = new StringBuilder();
builder.append("8"); // Sanity number
builder.append(idInvoker);
builder.append(idServiceCall);
builder.append(idApp);
builder.append(idCommand);
return builder.toString();
}
| private String generateErrorCode(Class<? extends Object> invoker, String title, Command command) {
// This is a little hacky, but should suffice for the time being
// Get the invoker ID
int idInvoker = 0;
if (invoker.equals(Playback.class)) { idInvoker = 1; }
else if (invoker.equals(VolumeControl.class)) { idInvoker = 2; }
else if (invoker.equals(GetMediaInfoTask.class)) { idInvoker = 3; }
else if (invoker.equals(GetVolumeLevelTask.class)) { idInvoker = 4; }
else if (invoker.equals(IsPlayingTask.class)) { idInvoker = 5; }
// Get the service function ID
int idServiceCall = 0;
if (title.equals("Failed to connect to remote machine")) { idServiceCall = 1; } // Failed to connect
if (title.equals("Failed to send command to remote machine")) { idServiceCall = 2; } // Failed to send command
if (title.equals("Failed to send query to remote machine")) { idServiceCall = 3; } // Failed to perform query
int idApp = 0;
int idCommand = 0;
if (command != null) {
// Get the player ID
String app = command.getTargetApp();
if (app.equals(AppConfigProvider.APP_AMAROK)) { idApp = 1; }
else if (app.equals(AppConfigProvider.APP_BANSHEE)) { idApp = 2; }
else if (app.equals(AppConfigProvider.APP_DRAGONPLAYER)) { idApp = 3; }
else if (app.equals(AppConfigProvider.APP_RHYTHMBOX)) { idApp = 4; }
else if (app.equals(AppConfigProvider.APP_TOTEM)) { idApp = 5; }
else if (app.equals(AppConfigProvider.APP_VLC)) { idApp = 6; }
else if (app.equals(AppConfigProvider.APP_EXAILE)) { idApp = 7; }
else if (app.equals(AppConfigProvider.APP_KAFFEINE)) { idApp = 8; }
// Get the command ID
String commandKey = command.getKey();
if (commandKey.equals(Command.GET_MEDIA_INFO)) { idCommand = 1; }
else if (commandKey.equals(Command.INIT)) { idCommand = 2; }
else if (commandKey.equals(Command.IS_PLAYING)) { idCommand = 3; }
else if (commandKey.equals(Command.NEXT)) { idCommand = 4; }
else if (commandKey.equals(Command.PAUSE)) { idCommand = 5; }
else if (commandKey.equals(Command.PLAY)) { idCommand = 6; }
else if (commandKey.equals(Command.POWER)) { idCommand = 7; }
else if (commandKey.equals(Command.PREV)) { idCommand = 8; }
else if (commandKey.equals(Command.VOL_CHANGE)) { idCommand = 9; }
else if (commandKey.equals(Command.VOL_CURRENT)) { idCommand = 10; }
else if (commandKey.equals(Command.VOL_MUTE)) { idCommand = 11; }
else if (commandKey.equals(Command.LAUNCH_PLAYER)) { idCommand = 12; }
}
// Build the code
StringBuilder builder = new StringBuilder();
builder.append("8"); // Sanity number
builder.append(idInvoker);
builder.append(idServiceCall);
builder.append(idApp);
builder.append(idCommand);
return builder.toString();
}
|
diff --git a/src/org/objectweb/proactive/core/group/ExceptionListException.java b/src/org/objectweb/proactive/core/group/ExceptionListException.java
index faff189d1..e9892c2b3 100644
--- a/src/org/objectweb/proactive/core/group/ExceptionListException.java
+++ b/src/org/objectweb/proactive/core/group/ExceptionListException.java
@@ -1,96 +1,96 @@
/*
* ################################################################
*
* ProActive: The Java(TM) library for Parallel, Distributed,
* Concurrent computing with Security and Mobility
*
* Copyright (C) 1997-2005 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 Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*
* Initial developer(s): The ProActive Team
* http://www.inria.fr/oasis/ProActive/contacts.html
* Contributor(s):
*
* ################################################################
*/
package org.objectweb.proactive.core.group;
import java.util.Iterator;
import java.util.Vector;
/**
* An exception that contains a list of the ExceptionInGroup occured in a group.
*
* @author Laurent Baduel
*/
public class ExceptionListException extends RuntimeException {
/** A vector implements the list */
private Vector list;
/**
* Builds a new empty list of exception
*/
public ExceptionListException() {
super("Exception list, only one cause in the stacktrace");
this.list = new Vector();
}
/**
* Adds an exception into this list
* @param exception - the exception to add
*/
- public void add(ExceptionInGroup exception) {
+ public synchronized void add(ExceptionInGroup exception) {
if (getCause() == this) {
initCause(exception);
}
this.list.add(exception);
}
/**
* Removes all of the exceptions from this list.
*/
public void clear() {
this.list.clear();
}
/**
* Returns an iterator over the exceptions in this list in proper sequence.
* @return an iterator over the exceptions in this list in proper sequence.
*/
public Iterator iterator() {
return this.list.iterator();
}
/**
* Returns the number of exceptions in this list.
* @return the number of exceptions in this list.
*/
public int size() {
return this.list.size();
}
/**
* Tests if this ExceptionListException has no ExceptionInGroup.
* @return <code>true</code> if and only if this list has no components, that is, its size is zero; <code>false otherwise.
*/
public boolean isEmpty() {
return this.list.isEmpty();
}
}
| true | true | public void add(ExceptionInGroup exception) {
if (getCause() == this) {
initCause(exception);
}
this.list.add(exception);
}
| public synchronized void add(ExceptionInGroup exception) {
if (getCause() == this) {
initCause(exception);
}
this.list.add(exception);
}
|
diff --git a/src/de/typology/executables/MultiKneserNeyBuilder.java b/src/de/typology/executables/MultiKneserNeyBuilder.java
index e5d261d3..09811094 100644
--- a/src/de/typology/executables/MultiKneserNeyBuilder.java
+++ b/src/de/typology/executables/MultiKneserNeyBuilder.java
@@ -1,16 +1,16 @@
package de.typology.executables;
import de.typology.utils.Config;
public class MultiKneserNeyBuilder {
public static void main(String[] args) {
- String[] languages = Config.get().acquisLanguages.split(",");
+ String[] languages = Config.get().languages.split(",");
String inputDataSet = Config.get().inputDataSet;
for (String language : languages) {
Config.get().inputDataSet = inputDataSet + "/" + language;
KneserNeyBuilder.main(args);
}
}
}
| true | true | public static void main(String[] args) {
String[] languages = Config.get().acquisLanguages.split(",");
String inputDataSet = Config.get().inputDataSet;
for (String language : languages) {
Config.get().inputDataSet = inputDataSet + "/" + language;
KneserNeyBuilder.main(args);
}
}
| public static void main(String[] args) {
String[] languages = Config.get().languages.split(",");
String inputDataSet = Config.get().inputDataSet;
for (String language : languages) {
Config.get().inputDataSet = inputDataSet + "/" + language;
KneserNeyBuilder.main(args);
}
}
|
diff --git a/Osm2GpsMid/src/de/ueller/osmToGpsMid/RouteSoundSyntax.java b/Osm2GpsMid/src/de/ueller/osmToGpsMid/RouteSoundSyntax.java
index 00ceb862..f645c9be 100644
--- a/Osm2GpsMid/src/de/ueller/osmToGpsMid/RouteSoundSyntax.java
+++ b/Osm2GpsMid/src/de/ueller/osmToGpsMid/RouteSoundSyntax.java
@@ -1,173 +1,180 @@
package de.ueller.osmToGpsMid;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.MissingResourceException;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
public class RouteSoundSyntax {
private final static byte SYNTAX_FORMAT_VERSION = 1;
private ResourceBundle rb = null;
private InputStream is = null;
private DataOutputStream dsi = null;
private ArrayList<String> soundNames = new ArrayList<String>(1);
public RouteSoundSyntax(String styleFileDirectory, String additionalSrcPath, String destinationPathAndFile) {
String info = "Using " + styleFileDirectory + additionalSrcPath + "/syntax.cfg";
// try syntax.cfg from file system
try {
is = new FileInputStream(styleFileDirectory + additionalSrcPath + "/syntax.cfg");
} catch (Exception e) {
// try internal syntax.cfg
try {
info = "Using internal syntax.cfg from " + additionalSrcPath;
is = getClass().getResourceAsStream("/media/" + additionalSrcPath + "/syntax.cfg");
} catch (Exception e2) {
;
}
}
System.out.println(info + " for specifying route and sound syntax");
if (is != null) {
try {
InputStreamReader isr;
// try reading syntax.cfg with UTF-8 encoding
try {
isr = new InputStreamReader(is, "UTF-8");
+ try {
+ rb = new PropertyResourceBundle(isr);
+ } catch (Exception e) {
+ System.out.println ("ERROR: PropertyResourceBundle for syntax.cfg could not be created from InputStreamReader");
+ e.printStackTrace();
+ System.exit(1);
+ }
} catch (NoSuchMethodError nsme) {
/* Give warning if creating the UTF-8-reader for syntax.cfg fails and continue with default encoding,
+ * this can happen with Java 1.5 environments
* e.g. on OS X Leopard: http://sourceforge.net/projects/gpsmid/forums/forum/677687/topic/4063854
*/
- System.out.println("Warning: Cannot use UTF-8 encoding for decoding syntax.cfg file");
- isr = new InputStreamReader(is);
- }
- try {
- rb = new PropertyResourceBundle(isr);
- } catch (Exception e) {
- System.out.println ("ERROR: PropertyResourceBundle for syntax.cfg could not be created");
- e.printStackTrace();
- System.exit(1);
+ System.out.println("Warning: Cannot use UTF-8 encoding for decoding syntax.cfg file as it requires Java 1.6+");
+ try {
+ rb = new PropertyResourceBundle(is);
+ } catch (Exception e) {
+ System.out.println ("ERROR: PropertyResourceBundle for syntax.cfg could not be created from InputStream");
+ e.printStackTrace();
+ System.exit(1);
+ }
}
} catch (UnsupportedEncodingException e1) {
System.out.println ("ERROR: InputStreamReader for syntax.cfg could not be created");
e1.printStackTrace();
System.exit(1);
}
} else {
System.out.println ("ERROR: syntax.cfg not found in the " + additionalSrcPath + " directory");
System.exit(1);
}
// create syntax.dat
try {
FileOutputStream foi = new FileOutputStream(destinationPathAndFile);
dsi = new DataOutputStream(foi);
} catch (Exception e) {
;
}
if (dsi == null) {
System.out.println ("ERROR: could not create " + destinationPathAndFile);
System.exit(1);
}
try {
dsi.writeByte(SYNTAX_FORMAT_VERSION);
final String directionNames[] = { "default", "hardright", "right", "halfright", "straighton", "halfleft", "left", "hardleft"};
for (int i=0; i < directionNames.length; i++) {
getAndWriteString("direction." + directionNames[i] + ".screen");
getAndWriteString("direction." + directionNames[i] + ".sound");
}
final String bearDirectionNames[] = { "right", "left"};
for (int i=0; i < bearDirectionNames.length; i++) {
getAndWriteString("beardir." + bearDirectionNames[i] + ".screen");
getAndWriteString("beardir." + bearDirectionNames[i] + ".sound");
}
final String exitNames[] = { "1", "2", "3", "4", "5", "6"};
for (int i=0; i < exitNames.length; i++) {
getAndWriteString("roundabout.exit." + exitNames[i] + ".screen");
getAndWriteString("roundabout.exit." + exitNames[i] + ".sound");
}
final String meterNames[] = { "100", "200", "300", "400", "500", "600", "700", "800"};
for (int i=0; i < meterNames.length; i++) {
getAndWriteString("meters." + meterNames[i] + ".sound");
}
String componentNames[] = { "normal.sound", "prepare.sound", "in.sound", "then.sound", "normal.screen", "in.screen" };
String instructionTypes[] = {"simpledirection", "beardir", "uturn", "roundabout",
"entermotorway", "beardirandentermotorway",
"leavemotorway", "beardirandleavemotorway",
"intotunnel", "outoftunnel", "areacross", "areacrossed", "destreached" };
for (int i=0; i < instructionTypes.length; i++) {
for (int c=0; c < componentNames.length; c++) {
getAndWriteString(instructionTypes[i] + "." + componentNames[c]);
}
}
getAndWriteString("soon.sound");
getAndWriteString("again.sound");
getAndWriteString("checkdirection.screen");
getAndWriteString("checkdirection.sound");
getAndWriteString("followstreet.sound");
getAndWriteString("speedlimit.sound");
getAndWriteString("recalculation.sound");
// magic number
dsi.writeShort(0x3550);
} catch (IOException ioe) {
System.out.println ("ERROR writing to " + destinationPathAndFile);
System.exit(1);
}
}
public void getAndWriteString(String key) throws IOException {
String s = key;
try {
s = rb.getString(key).trim();
} catch (MissingResourceException e) {
System.out.println("syntax.cfg: " + key + " not found"); ;
}
dsi.writeUTF(s);
if (key.endsWith(".sound")) {
rememberSounds(s);
}
//System.out.println(key + ": " + s);
}
private void rememberSounds(String sequence) {
String s[] = sequence.split("[;]");
for (int i = 0; i < s.length; i++) {
if (s[i].length() > 0 && !s[i].startsWith("%")) {
if (!soundNames.contains(s[i])) {
soundNames.add(s[i]);
//System.out.println(s[i]);
}
}
}
}
public Object[] getSoundNames() {
rememberSounds("CONNECT;DISCONNECT");
return soundNames.toArray();
}
}
| false | true | public RouteSoundSyntax(String styleFileDirectory, String additionalSrcPath, String destinationPathAndFile) {
String info = "Using " + styleFileDirectory + additionalSrcPath + "/syntax.cfg";
// try syntax.cfg from file system
try {
is = new FileInputStream(styleFileDirectory + additionalSrcPath + "/syntax.cfg");
} catch (Exception e) {
// try internal syntax.cfg
try {
info = "Using internal syntax.cfg from " + additionalSrcPath;
is = getClass().getResourceAsStream("/media/" + additionalSrcPath + "/syntax.cfg");
} catch (Exception e2) {
;
}
}
System.out.println(info + " for specifying route and sound syntax");
if (is != null) {
try {
InputStreamReader isr;
// try reading syntax.cfg with UTF-8 encoding
try {
isr = new InputStreamReader(is, "UTF-8");
} catch (NoSuchMethodError nsme) {
/* Give warning if creating the UTF-8-reader for syntax.cfg fails and continue with default encoding,
* e.g. on OS X Leopard: http://sourceforge.net/projects/gpsmid/forums/forum/677687/topic/4063854
*/
System.out.println("Warning: Cannot use UTF-8 encoding for decoding syntax.cfg file");
isr = new InputStreamReader(is);
}
try {
rb = new PropertyResourceBundle(isr);
} catch (Exception e) {
System.out.println ("ERROR: PropertyResourceBundle for syntax.cfg could not be created");
e.printStackTrace();
System.exit(1);
}
} catch (UnsupportedEncodingException e1) {
System.out.println ("ERROR: InputStreamReader for syntax.cfg could not be created");
e1.printStackTrace();
System.exit(1);
}
} else {
System.out.println ("ERROR: syntax.cfg not found in the " + additionalSrcPath + " directory");
System.exit(1);
}
// create syntax.dat
try {
FileOutputStream foi = new FileOutputStream(destinationPathAndFile);
dsi = new DataOutputStream(foi);
} catch (Exception e) {
;
}
if (dsi == null) {
System.out.println ("ERROR: could not create " + destinationPathAndFile);
System.exit(1);
}
try {
dsi.writeByte(SYNTAX_FORMAT_VERSION);
final String directionNames[] = { "default", "hardright", "right", "halfright", "straighton", "halfleft", "left", "hardleft"};
for (int i=0; i < directionNames.length; i++) {
getAndWriteString("direction." + directionNames[i] + ".screen");
getAndWriteString("direction." + directionNames[i] + ".sound");
}
final String bearDirectionNames[] = { "right", "left"};
for (int i=0; i < bearDirectionNames.length; i++) {
getAndWriteString("beardir." + bearDirectionNames[i] + ".screen");
getAndWriteString("beardir." + bearDirectionNames[i] + ".sound");
}
final String exitNames[] = { "1", "2", "3", "4", "5", "6"};
for (int i=0; i < exitNames.length; i++) {
getAndWriteString("roundabout.exit." + exitNames[i] + ".screen");
getAndWriteString("roundabout.exit." + exitNames[i] + ".sound");
}
final String meterNames[] = { "100", "200", "300", "400", "500", "600", "700", "800"};
for (int i=0; i < meterNames.length; i++) {
getAndWriteString("meters." + meterNames[i] + ".sound");
}
String componentNames[] = { "normal.sound", "prepare.sound", "in.sound", "then.sound", "normal.screen", "in.screen" };
String instructionTypes[] = {"simpledirection", "beardir", "uturn", "roundabout",
"entermotorway", "beardirandentermotorway",
"leavemotorway", "beardirandleavemotorway",
"intotunnel", "outoftunnel", "areacross", "areacrossed", "destreached" };
for (int i=0; i < instructionTypes.length; i++) {
for (int c=0; c < componentNames.length; c++) {
getAndWriteString(instructionTypes[i] + "." + componentNames[c]);
}
}
getAndWriteString("soon.sound");
getAndWriteString("again.sound");
getAndWriteString("checkdirection.screen");
getAndWriteString("checkdirection.sound");
getAndWriteString("followstreet.sound");
getAndWriteString("speedlimit.sound");
getAndWriteString("recalculation.sound");
// magic number
dsi.writeShort(0x3550);
} catch (IOException ioe) {
System.out.println ("ERROR writing to " + destinationPathAndFile);
System.exit(1);
}
}
| public RouteSoundSyntax(String styleFileDirectory, String additionalSrcPath, String destinationPathAndFile) {
String info = "Using " + styleFileDirectory + additionalSrcPath + "/syntax.cfg";
// try syntax.cfg from file system
try {
is = new FileInputStream(styleFileDirectory + additionalSrcPath + "/syntax.cfg");
} catch (Exception e) {
// try internal syntax.cfg
try {
info = "Using internal syntax.cfg from " + additionalSrcPath;
is = getClass().getResourceAsStream("/media/" + additionalSrcPath + "/syntax.cfg");
} catch (Exception e2) {
;
}
}
System.out.println(info + " for specifying route and sound syntax");
if (is != null) {
try {
InputStreamReader isr;
// try reading syntax.cfg with UTF-8 encoding
try {
isr = new InputStreamReader(is, "UTF-8");
try {
rb = new PropertyResourceBundle(isr);
} catch (Exception e) {
System.out.println ("ERROR: PropertyResourceBundle for syntax.cfg could not be created from InputStreamReader");
e.printStackTrace();
System.exit(1);
}
} catch (NoSuchMethodError nsme) {
/* Give warning if creating the UTF-8-reader for syntax.cfg fails and continue with default encoding,
* this can happen with Java 1.5 environments
* e.g. on OS X Leopard: http://sourceforge.net/projects/gpsmid/forums/forum/677687/topic/4063854
*/
System.out.println("Warning: Cannot use UTF-8 encoding for decoding syntax.cfg file as it requires Java 1.6+");
try {
rb = new PropertyResourceBundle(is);
} catch (Exception e) {
System.out.println ("ERROR: PropertyResourceBundle for syntax.cfg could not be created from InputStream");
e.printStackTrace();
System.exit(1);
}
}
} catch (UnsupportedEncodingException e1) {
System.out.println ("ERROR: InputStreamReader for syntax.cfg could not be created");
e1.printStackTrace();
System.exit(1);
}
} else {
System.out.println ("ERROR: syntax.cfg not found in the " + additionalSrcPath + " directory");
System.exit(1);
}
// create syntax.dat
try {
FileOutputStream foi = new FileOutputStream(destinationPathAndFile);
dsi = new DataOutputStream(foi);
} catch (Exception e) {
;
}
if (dsi == null) {
System.out.println ("ERROR: could not create " + destinationPathAndFile);
System.exit(1);
}
try {
dsi.writeByte(SYNTAX_FORMAT_VERSION);
final String directionNames[] = { "default", "hardright", "right", "halfright", "straighton", "halfleft", "left", "hardleft"};
for (int i=0; i < directionNames.length; i++) {
getAndWriteString("direction." + directionNames[i] + ".screen");
getAndWriteString("direction." + directionNames[i] + ".sound");
}
final String bearDirectionNames[] = { "right", "left"};
for (int i=0; i < bearDirectionNames.length; i++) {
getAndWriteString("beardir." + bearDirectionNames[i] + ".screen");
getAndWriteString("beardir." + bearDirectionNames[i] + ".sound");
}
final String exitNames[] = { "1", "2", "3", "4", "5", "6"};
for (int i=0; i < exitNames.length; i++) {
getAndWriteString("roundabout.exit." + exitNames[i] + ".screen");
getAndWriteString("roundabout.exit." + exitNames[i] + ".sound");
}
final String meterNames[] = { "100", "200", "300", "400", "500", "600", "700", "800"};
for (int i=0; i < meterNames.length; i++) {
getAndWriteString("meters." + meterNames[i] + ".sound");
}
String componentNames[] = { "normal.sound", "prepare.sound", "in.sound", "then.sound", "normal.screen", "in.screen" };
String instructionTypes[] = {"simpledirection", "beardir", "uturn", "roundabout",
"entermotorway", "beardirandentermotorway",
"leavemotorway", "beardirandleavemotorway",
"intotunnel", "outoftunnel", "areacross", "areacrossed", "destreached" };
for (int i=0; i < instructionTypes.length; i++) {
for (int c=0; c < componentNames.length; c++) {
getAndWriteString(instructionTypes[i] + "." + componentNames[c]);
}
}
getAndWriteString("soon.sound");
getAndWriteString("again.sound");
getAndWriteString("checkdirection.screen");
getAndWriteString("checkdirection.sound");
getAndWriteString("followstreet.sound");
getAndWriteString("speedlimit.sound");
getAndWriteString("recalculation.sound");
// magic number
dsi.writeShort(0x3550);
} catch (IOException ioe) {
System.out.println ("ERROR writing to " + destinationPathAndFile);
System.exit(1);
}
}
|
diff --git a/OsmAnd/src/net/osmand/plus/views/LockInfoControl.java b/OsmAnd/src/net/osmand/plus/views/LockInfoControl.java
index 9b5bcbe5..54e9a8f5 100644
--- a/OsmAnd/src/net/osmand/plus/views/LockInfoControl.java
+++ b/OsmAnd/src/net/osmand/plus/views/LockInfoControl.java
@@ -1,211 +1,211 @@
package net.osmand.plus.views;
import java.util.ArrayList;
import java.util.List;
import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import net.osmand.access.AccessibleToast;
import net.osmand.plus.R;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.graphics.drawable.Drawable;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class LockInfoControl {
protected boolean isScreenLocked;
private View transparentLockView;
private Drawable lockEnabled;
private Drawable lockDisabled;
private List<LockInfoControlActions> lockActions = new ArrayList<LockInfoControl.LockInfoControlActions>();
public interface LockInfoControlActions {
public void addLockActions(QuickAction qa, LockInfoControl li, OsmandMapTileView view);
}
public void addLockActions(LockInfoControlActions la){
lockActions.add(la);
}
public List<LockInfoControlActions> getLockActions() {
return lockActions;
}
public ImageView createLockScreenWidget(final OsmandMapTileView view) {
final ImageView lockView = new ImageView(view.getContext());
lockEnabled = view.getResources().getDrawable(R.drawable.lock_enabled);
lockDisabled = view.getResources().getDrawable(R.drawable.lock_disabled);
updateLockIcon(view, lockView);
lockView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showBgServiceQAction(lockView, view);
}
});
return lockView;
}
private void updateLockIcon(final OsmandMapTileView view, final ImageView lockView) {
if (isScreenLocked) {
lockView.setBackgroundDrawable(lockEnabled);
} else {
lockView.setBackgroundDrawable(lockDisabled);
}
}
private void showBgServiceQAction(final ImageView lockView, final OsmandMapTileView view) {
final QuickAction qa = new QuickAction(lockView);
if (transparentLockView == null) {
transparentLockView = new FrameLayout(view.getContext());
FrameLayout.LayoutParams fparams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
Gravity.CENTER);
transparentLockView.setLayoutParams(fparams);
transparentLockView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
int[] locs = new int[2];
lockView.getLocationOnScreen(locs);
int x = (int) event.getX() - locs[0];
int y = (int) event.getY() - locs[1];
transparentLockView.getLocationOnScreen(locs);
x += locs[0];
y += locs[1];
if(lockView.getWidth() >= x && x >= 0 &&
lockView.getHeight() >= y && y >= 0) {
showBgServiceQAction(lockView, view);
return true;
}
blinkIcon();
AccessibleToast.makeText(transparentLockView.getContext(), R.string.screen_is_locked, Toast.LENGTH_LONG)
.show();
return true;
}
return true;
}
private void blinkIcon() {
lockView.setBackgroundDrawable(lockDisabled);
view.postDelayed(new Runnable() {
@Override
public void run() {
lockView.setBackgroundDrawable(lockEnabled);
}
}, 300);
}
});
}
final FrameLayout parent = (FrameLayout) view.getParent();
final ActionItem lockScreenAction = new ActionItem();
lockScreenAction.setTitle(view.getResources().getString(
isScreenLocked ? R.string.bg_service_screen_unlock : R.string.bg_service_screen_lock));
- lockScreenAction.setIcon(view.getResources().getDrawable(isScreenLocked ? R.drawable.lock_disabled : R.drawable.lock_enabled));
+ lockScreenAction.setIcon(view.getResources().getDrawable(isScreenLocked ? R.drawable.lock_enabled : R.drawable.lock_disabled));
lockScreenAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isScreenLocked) {
parent.addView(transparentLockView);
} else {
parent.removeView(transparentLockView);
}
isScreenLocked = !isScreenLocked;
qa.dismiss();
updateLockIcon(view, lockView);
}
});
qa.addActionItem(lockScreenAction);
for(LockInfoControlActions la : lockActions){
la.addLockActions(qa, this, view);
}
qa.show();
}
public static class ValueHolder<T> {
public T value;
}
public void showIntervalChooseDialog(final OsmandMapTileView view, final String patternMsg,
String title, final int[] seconds, final int[] minutes, final ValueHolder<Integer> v, OnClickListener onclick){
final Context ctx = view.getContext();
Builder dlg = new AlertDialog.Builder(view.getContext());
dlg.setTitle(title);
LinearLayout ll = new LinearLayout(view.getContext());
final TextView tv = new TextView(view.getContext());
tv.setPadding(7, 3, 7, 0);
tv.setText(String.format(patternMsg, ctx.getString(R.string.int_continuosly)));
SeekBar sp = new SeekBar(view.getContext());
sp.setPadding(7, 5, 7, 0);
final int secondsLength = seconds.length;
final int minutesLength = minutes.length;
sp.setMax(secondsLength + minutesLength - 1);
sp.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String s;
if(progress == 0) {
s = ctx.getString(R.string.int_continuosly);
} else {
if(progress < secondsLength) {
s = seconds[progress] + ctx.getString(R.string.int_seconds);
v.value = seconds[progress] * 1000;
} else {
s = minutes[progress - secondsLength] + ctx.getString(R.string.int_min);
v.value = minutes[progress - secondsLength] * 60 * 1000;
}
}
tv.setText(String.format(patternMsg, s));
}
});
for(int i=0; i<secondsLength +minutesLength - 1; i++) {
if(i < secondsLength) {
if(v.value <= seconds[i] * 1000) {
sp.setProgress(i);
break;
}
} else {
if(v.value <= minutes[i - secondsLength] * 1000 * 60) {
sp.setProgress(i);
break;
}
}
}
ll.setOrientation(LinearLayout.VERTICAL);
ll.addView(tv);
ll.addView(sp);
dlg.setView(ll);
dlg.setPositiveButton(R.string.default_buttons_ok, onclick);
dlg.setNegativeButton(R.string.default_buttons_cancel, null);
dlg.show();
}
}
| true | true | private void showBgServiceQAction(final ImageView lockView, final OsmandMapTileView view) {
final QuickAction qa = new QuickAction(lockView);
if (transparentLockView == null) {
transparentLockView = new FrameLayout(view.getContext());
FrameLayout.LayoutParams fparams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
Gravity.CENTER);
transparentLockView.setLayoutParams(fparams);
transparentLockView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
int[] locs = new int[2];
lockView.getLocationOnScreen(locs);
int x = (int) event.getX() - locs[0];
int y = (int) event.getY() - locs[1];
transparentLockView.getLocationOnScreen(locs);
x += locs[0];
y += locs[1];
if(lockView.getWidth() >= x && x >= 0 &&
lockView.getHeight() >= y && y >= 0) {
showBgServiceQAction(lockView, view);
return true;
}
blinkIcon();
AccessibleToast.makeText(transparentLockView.getContext(), R.string.screen_is_locked, Toast.LENGTH_LONG)
.show();
return true;
}
return true;
}
private void blinkIcon() {
lockView.setBackgroundDrawable(lockDisabled);
view.postDelayed(new Runnable() {
@Override
public void run() {
lockView.setBackgroundDrawable(lockEnabled);
}
}, 300);
}
});
}
final FrameLayout parent = (FrameLayout) view.getParent();
final ActionItem lockScreenAction = new ActionItem();
lockScreenAction.setTitle(view.getResources().getString(
isScreenLocked ? R.string.bg_service_screen_unlock : R.string.bg_service_screen_lock));
lockScreenAction.setIcon(view.getResources().getDrawable(isScreenLocked ? R.drawable.lock_disabled : R.drawable.lock_enabled));
lockScreenAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isScreenLocked) {
parent.addView(transparentLockView);
} else {
parent.removeView(transparentLockView);
}
isScreenLocked = !isScreenLocked;
qa.dismiss();
updateLockIcon(view, lockView);
}
});
qa.addActionItem(lockScreenAction);
for(LockInfoControlActions la : lockActions){
la.addLockActions(qa, this, view);
}
qa.show();
}
| private void showBgServiceQAction(final ImageView lockView, final OsmandMapTileView view) {
final QuickAction qa = new QuickAction(lockView);
if (transparentLockView == null) {
transparentLockView = new FrameLayout(view.getContext());
FrameLayout.LayoutParams fparams = new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT,
Gravity.CENTER);
transparentLockView.setLayoutParams(fparams);
transparentLockView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
int[] locs = new int[2];
lockView.getLocationOnScreen(locs);
int x = (int) event.getX() - locs[0];
int y = (int) event.getY() - locs[1];
transparentLockView.getLocationOnScreen(locs);
x += locs[0];
y += locs[1];
if(lockView.getWidth() >= x && x >= 0 &&
lockView.getHeight() >= y && y >= 0) {
showBgServiceQAction(lockView, view);
return true;
}
blinkIcon();
AccessibleToast.makeText(transparentLockView.getContext(), R.string.screen_is_locked, Toast.LENGTH_LONG)
.show();
return true;
}
return true;
}
private void blinkIcon() {
lockView.setBackgroundDrawable(lockDisabled);
view.postDelayed(new Runnable() {
@Override
public void run() {
lockView.setBackgroundDrawable(lockEnabled);
}
}, 300);
}
});
}
final FrameLayout parent = (FrameLayout) view.getParent();
final ActionItem lockScreenAction = new ActionItem();
lockScreenAction.setTitle(view.getResources().getString(
isScreenLocked ? R.string.bg_service_screen_unlock : R.string.bg_service_screen_lock));
lockScreenAction.setIcon(view.getResources().getDrawable(isScreenLocked ? R.drawable.lock_enabled : R.drawable.lock_disabled));
lockScreenAction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isScreenLocked) {
parent.addView(transparentLockView);
} else {
parent.removeView(transparentLockView);
}
isScreenLocked = !isScreenLocked;
qa.dismiss();
updateLockIcon(view, lockView);
}
});
qa.addActionItem(lockScreenAction);
for(LockInfoControlActions la : lockActions){
la.addLockActions(qa, this, view);
}
qa.show();
}
|
diff --git a/modules/src/main/java/org/archive/modules/extractor/ExtractorHTTP.java b/modules/src/main/java/org/archive/modules/extractor/ExtractorHTTP.java
index d5cc50ac..b16abe43 100644
--- a/modules/src/main/java/org/archive/modules/extractor/ExtractorHTTP.java
+++ b/modules/src/main/java/org/archive/modules/extractor/ExtractorHTTP.java
@@ -1,95 +1,95 @@
/* Copyright (C) 2003 Internet Archive.
*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Heritrix is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* any later version.
*
* Heritrix 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with Heritrix; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* SimpleHTTPExtractor.java
* Created on Jul 3, 2003
*
* $Header$
*/
package org.archive.modules.extractor;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.archive.modules.ProcessorURI;
import org.archive.modules.ProcessorURI.FetchType;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
/**
* Extracts URIs from HTTP response headers.
* @author gojomo
*/
public class ExtractorHTTP extends Extractor {
private static final long serialVersionUID = 3L;
// protected long numberOfCURIsHandled = 0;
protected long numberOfLinksExtracted = 0;
public ExtractorHTTP() {
}
@Override
protected boolean shouldProcess(ProcessorURI uri) {
if (uri.getFetchStatus() <= 0) {
return false;
}
FetchType ft = uri.getFetchType();
return (ft == FetchType.HTTP_GET) || (ft == FetchType.HTTP_POST);
}
@Override
protected void extract(ProcessorURI curi) {
HttpMethod method = curi.getHttpMethod();
addHeaderLink(curi, method.getResponseHeader("Location"));
addHeaderLink(curi, method.getResponseHeader("Content-Location"));
}
protected void addHeaderLink(ProcessorURI curi, Header loc) {
if (loc == null) {
// If null, return without adding anything.
return;
}
// TODO: consider possibility of multiple headers
try {
UURI dest = UURIFactory.getInstance(curi.getUURI(), loc.getValue());
- LinkContext lc = new HTMLLinkContext(loc.getName()); // FIXME
+ LinkContext lc = new HTMLLinkContext(loc.getName()+":");
Link link = new Link(curi.getUURI(), dest, lc, Hop.REFER);
curi.getOutLinks().add(link);
numberOfLinksExtracted++;
} catch (URIException e) {
logUriError(e, curi.getUURI(), loc.getValue());
}
}
public String report() {
StringBuffer ret = new StringBuffer();
ret.append("Processor: org.archive.crawler.extractor.ExtractorHTTP\n");
ret.append(" Function: " +
"Extracts URIs from HTTP response headers\n");
ret.append(" CrawlURIs handled: " + this.getURICount());
ret.append(" Links extracted: " + numberOfLinksExtracted + "\n\n");
return ret.toString();
}
}
| true | true | protected void addHeaderLink(ProcessorURI curi, Header loc) {
if (loc == null) {
// If null, return without adding anything.
return;
}
// TODO: consider possibility of multiple headers
try {
UURI dest = UURIFactory.getInstance(curi.getUURI(), loc.getValue());
LinkContext lc = new HTMLLinkContext(loc.getName()); // FIXME
Link link = new Link(curi.getUURI(), dest, lc, Hop.REFER);
curi.getOutLinks().add(link);
numberOfLinksExtracted++;
} catch (URIException e) {
logUriError(e, curi.getUURI(), loc.getValue());
}
}
| protected void addHeaderLink(ProcessorURI curi, Header loc) {
if (loc == null) {
// If null, return without adding anything.
return;
}
// TODO: consider possibility of multiple headers
try {
UURI dest = UURIFactory.getInstance(curi.getUURI(), loc.getValue());
LinkContext lc = new HTMLLinkContext(loc.getName()+":");
Link link = new Link(curi.getUURI(), dest, lc, Hop.REFER);
curi.getOutLinks().add(link);
numberOfLinksExtracted++;
} catch (URIException e) {
logUriError(e, curi.getUURI(), loc.getValue());
}
}
|
diff --git a/src/main/java/tconstruct/tools/TinkerTools.java b/src/main/java/tconstruct/tools/TinkerTools.java
index c9f61f08d..5e96d4c20 100644
--- a/src/main/java/tconstruct/tools/TinkerTools.java
+++ b/src/main/java/tconstruct/tools/TinkerTools.java
@@ -1,979 +1,979 @@
package tconstruct.tools;
import mantle.items.abstracts.CraftingItem;
import mantle.pulsar.pulse.Handler;
import mantle.pulsar.pulse.Pulse;
import mantle.pulsar.pulse.PulseProxy;
import mantle.utils.RecipeRemover;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.potion.Potion;
import net.minecraft.util.StatCollector;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe;
import tconstruct.TConstruct;
import tconstruct.common.itemblocks.MetadataItemBlock;
import tconstruct.items.tools.Arrow;
import tconstruct.items.tools.BattleSign;
import tconstruct.items.tools.Battleaxe;
import tconstruct.items.tools.Broadsword;
import tconstruct.items.tools.Chisel;
import tconstruct.items.tools.Cleaver;
import tconstruct.items.tools.Cutlass;
import tconstruct.items.tools.Dagger;
import tconstruct.items.tools.Excavator;
import tconstruct.items.tools.FryingPan;
import tconstruct.items.tools.Hammer;
import tconstruct.items.tools.Hatchet;
import tconstruct.items.tools.Longsword;
import tconstruct.items.tools.LumberAxe;
import tconstruct.items.tools.Mattock;
import tconstruct.items.tools.Pickaxe;
import tconstruct.items.tools.PotionLauncher;
import tconstruct.items.tools.Rapier;
import tconstruct.items.tools.Scythe;
import tconstruct.items.tools.Shortbow;
import tconstruct.items.tools.Shovel;
import tconstruct.library.TConstructRegistry;
import tconstruct.library.client.TConstructClientRegistry;
import tconstruct.library.crafting.*;
import tconstruct.library.tools.ToolCore;
import tconstruct.library.util.IPattern;
import tconstruct.modifiers.tools.ModAntiSpider;
import tconstruct.modifiers.tools.ModAttack;
import tconstruct.modifiers.tools.ModAutoSmelt;
import tconstruct.modifiers.tools.ModBlaze;
import tconstruct.modifiers.tools.ModButtertouch;
import tconstruct.modifiers.tools.ModCreativeToolModifier;
import tconstruct.modifiers.tools.ModDurability;
import tconstruct.modifiers.tools.ModExtraModifier;
import tconstruct.modifiers.tools.ModFlux;
import tconstruct.modifiers.tools.ModInteger;
import tconstruct.modifiers.tools.ModLapis;
import tconstruct.modifiers.tools.ModPiston;
import tconstruct.modifiers.tools.ModRedstone;
import tconstruct.modifiers.tools.ModReinforced;
import tconstruct.modifiers.tools.ModSmite;
import tconstruct.modifiers.tools.ModToolRepair;
import tconstruct.smeltery.TinkerSmeltery;
import tconstruct.tools.blocks.CraftingSlab;
import tconstruct.tools.blocks.CraftingStationBlock;
import tconstruct.tools.blocks.EquipBlock;
import tconstruct.tools.blocks.FurnaceSlab;
import tconstruct.tools.blocks.ToolForgeBlock;
import tconstruct.tools.blocks.ToolStationBlock;
import tconstruct.tools.itemblocks.CraftingSlabItemBlock;
import tconstruct.tools.itemblocks.ToolStationItemBlock;
import tconstruct.tools.items.Bowstring;
import tconstruct.tools.items.CreativeModifier;
import tconstruct.tools.items.Fletching;
import tconstruct.tools.items.Manual;
import tconstruct.tools.items.MaterialItem;
import tconstruct.tools.items.Pattern;
import tconstruct.tools.items.TitleIcon;
import tconstruct.tools.items.ToolPart;
import tconstruct.tools.items.ToolPartHidden;
import tconstruct.tools.items.ToolShard;
import tconstruct.tools.logic.CraftingStationLogic;
import tconstruct.tools.logic.FrypanLogic;
import tconstruct.tools.logic.FurnaceLogic;
import tconstruct.tools.logic.PartBuilderLogic;
import tconstruct.tools.logic.PatternChestLogic;
import tconstruct.tools.logic.StencilTableLogic;
import tconstruct.tools.logic.ToolForgeLogic;
import tconstruct.tools.logic.ToolStationLogic;
import tconstruct.util.ItemHelper;
import tconstruct.util.config.PHConstruct;
import tconstruct.world.TinkerWorld;
import tconstruct.world.blocks.SoilBlock;
import tconstruct.world.itemblocks.CraftedSoilItemBlock;
import tconstruct.world.items.GoldenHead;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.event.FMLInitializationEvent;
import cpw.mods.fml.common.event.FMLPostInitializationEvent;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.common.registry.GameRegistry.ObjectHolder;
@ObjectHolder(TConstruct.modID)
@Pulse(id = "Tinkers' Tools", description = "The main core of the mod! All of the tools, the tables, and the patterns are here.")
public class TinkerTools
{
/* Proxies for sides, used for graphics processing */
@PulseProxy(clientSide = "tconstruct.tools.ToolProxyClient", serverSide = "tconstruct.tools.ToolProxyCommon")
public static ToolProxyCommon proxy;
// Crafting blocks
public static Block toolStationWood;
public static Block toolStationStone;
public static Block toolForge;
public static Block craftingStationWood;
public static Block craftingSlabWood;
public static Block furnaceSlab;
public static Block heldItemBlock;
public static Block battlesignBlock;
// Tool parts
public static Item binding;
public static Item toughBinding;
public static Item toughRod;
public static Item largePlate;
public static Item pickaxeHead;
public static Item shovelHead;
public static Item hatchetHead;
public static Item frypanHead;
public static Item signHead;
public static Item chiselHead;
public static Item scytheBlade;
public static Item broadAxeHead;
public static Item excavatorHead;
public static Item hammerHead;
public static Item swordBlade;
public static Item largeSwordBlade;
public static Item knifeBlade;
public static Item wideGuard;
// Patterns and other materials
public static Item blankPattern;
public static Item materials; //TODO: Untwine this item
public static Item toolRod;
public static Item toolShard;
public static Item titleIcon;
// Tools
public static ToolCore pickaxe;
public static ToolCore shovel;
public static ToolCore hatchet;
public static ToolCore broadsword;
public static ToolCore longsword;
public static ToolCore rapier;
public static ToolCore dagger;
public static ToolCore cutlass;
public static ToolCore frypan;
public static ToolCore battlesign;
public static ToolCore chisel;
public static ToolCore mattock;
public static ToolCore scythe;
public static ToolCore lumberaxe;
public static ToolCore cleaver;
public static ToolCore hammer;
public static ToolCore battleaxe;
public static ToolCore shortbow;
public static ToolCore arrow;
public static Item potionLauncher;
public static Item handGuard;
public static Item crossbar;
public static Item fullGuard;
public static Item bowstring;
public static Item arrowhead;
public static Item fletching;
public static Block craftedSoil; //TODO: Untwine this
public static Block multiBrick;
public static Block multiBrickFancy;
// Tool modifiers
public static ModFlux modFlux;
public static ModLapis modLapis;
public static ModAttack modAttack;
public static Item[] patternOutputs;
public static Item woodPattern;
public static Item manualBook;
public static ToolCore excavator;
public static Item creativeModifier;
public static Item goldHead;
// recipe stuff
public static boolean thaumcraftAvailable;
@Handler
public void preInit (FMLPreInitializationEvent event)
{
MinecraftForge.EVENT_BUS.register(new TinkerToolEvents());
//Blocks
TinkerTools.toolStationWood = new ToolStationBlock(Material.wood).setBlockName("ToolStation");
TinkerTools.toolForge = new ToolForgeBlock(Material.iron).setBlockName("ToolForge");
TinkerTools.craftingStationWood = new CraftingStationBlock(Material.wood).setBlockName("CraftingStation");
TinkerTools.craftingSlabWood = new CraftingSlab(Material.wood).setBlockName("CraftingSlab");
TinkerTools.furnaceSlab = new FurnaceSlab(Material.rock).setBlockName("FurnaceSlab");
TinkerTools.heldItemBlock = new EquipBlock(Material.wood).setBlockName("Frypan");
/* battlesignBlock = new BattlesignBlock(PHConstruct.battlesignBlock).setUnlocalizedName("Battlesign");
GameRegistry.registerBlock(battlesignBlock, "BattlesignBlock");
ameRegistry.registerTileEntity(BattlesignLogic.class, "BattlesignLogic");*/
TinkerTools.craftedSoil = new SoilBlock().setLightOpacity(0).setBlockName("TConstruct.Soil");
TinkerTools.craftedSoil.stepSound = Block.soundTypeGravel;
GameRegistry.registerBlock(TinkerTools.toolStationWood, ToolStationItemBlock.class, "ToolStationBlock");
GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation");
GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter");
GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder");
GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper");
GameRegistry.registerBlock(TinkerTools.toolForge, MetadataItemBlock.class, "ToolForgeBlock");
GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge");
GameRegistry.registerBlock(TinkerTools.craftingStationWood, "CraftingStation");
GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation");
GameRegistry.registerBlock(TinkerTools.craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab");
GameRegistry.registerBlock(TinkerTools.furnaceSlab, "FurnaceSlab");
GameRegistry.registerTileEntity(FurnaceLogic.class, "TConstruct.Furnace");
GameRegistry.registerBlock(TinkerTools.heldItemBlock, "HeldItemBlock");
GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic");
GameRegistry.registerBlock(TinkerTools.craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil");
//Items
TinkerTools.titleIcon = new TitleIcon().setUnlocalizedName("tconstruct.titleicon");
GameRegistry.registerItem(TinkerTools.titleIcon, "titleIcon");
String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" };
TinkerTools.blankPattern = new CraftingItem(blanks, blanks, "materials/", "tinker", TConstructRegistry.materialTab).setUnlocalizedName("tconstruct.Pattern");
GameRegistry.registerItem(TinkerTools.blankPattern, "blankPattern");
TinkerTools.materials = new MaterialItem().setUnlocalizedName("tconstruct.Materials");
TinkerTools.toolRod = new ToolPart("_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod");
TinkerTools.toolShard = new ToolShard("_chunk").setUnlocalizedName("tconstruct.ToolShard");
TinkerTools.woodPattern = new Pattern("pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern");
GameRegistry.registerItem(TinkerTools.materials, "materials");
GameRegistry.registerItem(TinkerTools.woodPattern, "woodPattern");
TConstructRegistry.addItemToDirectory("blankPattern", TinkerTools.blankPattern);
TConstructRegistry.addItemToDirectory("woodPattern", TinkerTools.woodPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 1; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(TinkerTools.woodPattern, 1, i));
}
TinkerTools.manualBook = new Manual();
GameRegistry.registerItem(TinkerTools.manualBook, "manualBook");
TinkerTools.pickaxe = new Pickaxe();
TinkerTools.shovel = new Shovel();
TinkerTools.hatchet = new Hatchet();
TinkerTools.broadsword = new Broadsword();
TinkerTools.longsword = new Longsword();
TinkerTools.rapier = new Rapier();
TinkerTools.dagger = new Dagger();
TinkerTools.cutlass = new Cutlass();
TinkerTools.frypan = new FryingPan();
TinkerTools.battlesign = new BattleSign();
TinkerTools.mattock = new Mattock();
TinkerTools.chisel = new Chisel();
TinkerTools.lumberaxe = new LumberAxe();
TinkerTools.cleaver = new Cleaver();
TinkerTools.scythe = new Scythe();
TinkerTools.excavator = new Excavator();
TinkerTools.hammer = new Hammer();
TinkerTools.battleaxe = new Battleaxe();
TinkerTools.shortbow = new Shortbow();
TinkerTools.arrow = new Arrow();
Item[] tools = { TinkerTools.pickaxe, TinkerTools.shovel, TinkerTools.hatchet, TinkerTools.broadsword, TinkerTools.longsword, TinkerTools.rapier, TinkerTools.dagger, TinkerTools.cutlass, TinkerTools.frypan, TinkerTools.battlesign, TinkerTools.mattock,
TinkerTools.chisel, TinkerTools.lumberaxe, TinkerTools.cleaver, TinkerTools.scythe, TinkerTools.excavator, TinkerTools.hammer, TinkerTools.battleaxe, TinkerTools.shortbow, TinkerTools.arrow };
String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "dagger", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver",
"scythe", "excavator", "hammer", "battleaxe", "shortbow", "arrow" };
for (int i = 0; i < tools.length; i++)
{
GameRegistry.registerItem(tools[i], toolStrings[i]); // 1.7 compat
TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]);
}
TinkerTools.potionLauncher = new PotionLauncher().setUnlocalizedName("tconstruct.PotionLauncher");
GameRegistry.registerItem(TinkerTools.potionLauncher, "potionLauncher");
TinkerTools.pickaxeHead = new ToolPart("_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead");
TinkerTools.shovelHead = new ToolPart("_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead");
TinkerTools.hatchetHead = new ToolPart("_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead");
TinkerTools.binding = new ToolPart("_binding", "Binding").setUnlocalizedName("tconstruct.Binding");
TinkerTools.toughBinding = new ToolPart("_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding");
TinkerTools.toughRod = new ToolPart("_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod");
TinkerTools.largePlate = new ToolPart("_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate");
TinkerTools.swordBlade = new ToolPart("_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade");
TinkerTools.wideGuard = new ToolPart("_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard");
TinkerTools.handGuard = new ToolPart("_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard");
TinkerTools.crossbar = new ToolPart("_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar");
TinkerTools.knifeBlade = new ToolPart("_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade");
TinkerTools.fullGuard = new ToolPartHidden("_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard");
TinkerTools.frypanHead = new ToolPart("_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead");
TinkerTools.signHead = new ToolPart("_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead");
TinkerTools.chiselHead = new ToolPart("_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead");
TinkerTools.scytheBlade = new ToolPart("_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade");
TinkerTools.broadAxeHead = new ToolPart("_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead");
TinkerTools.excavatorHead = new ToolPart("_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead");
TinkerTools.largeSwordBlade = new ToolPart("_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade");
TinkerTools.hammerHead = new ToolPart("_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead");
TinkerTools.bowstring = new Bowstring().setUnlocalizedName("tconstruct.Bowstring");
TinkerTools.arrowhead = new ToolPart("_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead");
TinkerTools.fletching = new Fletching().setUnlocalizedName("tconstruct.Fletching");
Item[] toolParts = { TinkerTools.toolRod, TinkerTools.toolShard, TinkerTools.pickaxeHead, TinkerTools.shovelHead, TinkerTools.hatchetHead, TinkerTools.binding, TinkerTools.toughBinding, TinkerTools.toughRod, TinkerTools.largePlate,
TinkerTools.swordBlade, TinkerTools.wideGuard, TinkerTools.handGuard, TinkerTools.crossbar, TinkerTools.knifeBlade, TinkerTools.fullGuard, TinkerTools.frypanHead, TinkerTools.signHead, TinkerTools.chiselHead, TinkerTools.scytheBlade,
TinkerTools.broadAxeHead, TinkerTools.excavatorHead, TinkerTools.largeSwordBlade, TinkerTools.hammerHead, TinkerTools.bowstring, TinkerTools.fletching, TinkerTools.arrowhead };
String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard",
"crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring",
"fletching", "arrowhead" };
for (int i = 0; i < toolParts.length; i++)
{
GameRegistry.registerItem(toolParts[i], toolPartStrings[i]); // 1.7
// compat
TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]);
}
goldHead = new GoldenHead(4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead");
GameRegistry.registerItem(TinkerTools.goldHead, "goldHead");
TinkerTools.creativeModifier = new CreativeModifier().setUnlocalizedName("tconstruct.modifier.creative");
GameRegistry.registerItem(TinkerTools.creativeModifier, "creativeModifier");
String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper",
"ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper",
"nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze",
"nuggetAlumite", "nuggetSteel", "ingotPigIron", "nuggetPigIron", "glueball" };
for (int i = 0; i < materialStrings.length; i++)
{
TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(TinkerTools.materials, 1, i));
}
registerMaterials();
registerStencils();
- //TODO: Redesign stencil table to be a sensible block
+ // this array is only used to register the remaining pattern-part-interactions
TinkerTools.patternOutputs = new Item[] { TinkerTools.toolRod, TinkerTools.pickaxeHead, TinkerTools.shovelHead, TinkerTools.hatchetHead, TinkerTools.swordBlade, TinkerTools.wideGuard,
TinkerTools.handGuard, TinkerTools.crossbar, TinkerTools.binding, TinkerTools.frypanHead, TinkerTools.signHead, TinkerTools.knifeBlade, TinkerTools.chiselHead, TinkerTools.toughRod,
TinkerTools.toughBinding, TinkerTools.largePlate, TinkerTools.broadAxeHead, TinkerTools.scytheBlade, TinkerTools.excavatorHead, TinkerTools.largeSwordBlade, TinkerTools.hammerHead,
TinkerTools.fullGuard, null, null, TinkerTools.arrowhead, null };
//Moved temporarily to deal with AE2 Quartz
TinkerTools.modFlux = new ModFlux();
ModifyBuilder.registerModifier(TinkerTools.modFlux);
ItemStack lapisItem = new ItemStack(Items.dye, 1, 4);
ItemStack lapisBlock = new ItemStack(Blocks.lapis_block);
TinkerTools.modLapis = new ModLapis(10, new ItemStack[] { lapisItem, lapisBlock }, new int[] { 1, 9 });
ModifyBuilder.registerModifier(TinkerTools.modLapis);
TinkerTools.modAttack = new ModAttack("Quartz", 11, new ItemStack[] { new ItemStack(Items.quartz),
new ItemStack(Blocks.quartz_block, 1, Short.MAX_VALUE) }, new int[] { 1, 4 });
ModifyBuilder.registerModifier(TinkerTools.modAttack);
}
void setupToolTabs ()
{
TConstructRegistry.materialTab.init(new ItemStack(TinkerTools.manualBook, 1, 0));
TConstructRegistry.partTab.init(new ItemStack(TinkerTools.titleIcon, 1, 255));
TConstructRegistry.blockTab.init(new ItemStack(TinkerTools.toolStationWood));
ItemStack tool = new ItemStack(TinkerTools.longsword, 1, 0);
NBTTagCompound compound = new NBTTagCompound();
compound.setTag("InfiTool", new NBTTagCompound());
compound.getCompoundTag("InfiTool").setInteger("RenderHead", 2);
compound.getCompoundTag("InfiTool").setInteger("RenderHandle", 0);
compound.getCompoundTag("InfiTool").setInteger("RenderAccessory", 10);
tool.setTagCompound(compound);
TConstructRegistry.toolTab.init(tool);
}
//@Override
public int getBurnTime (ItemStack fuel)
{
if (fuel.getItem() == TinkerTools.materials && fuel.getItemDamage() == 7)
return 26400;
return 0;
}
@Handler
public void init (FMLInitializationEvent event)
{
addPartMapping();
addRecipesForToolBuilder();
addRecipesForChisel();
craftingTableRecipes();
setupToolTabs();
proxy.initialize();
}
@Handler
public void postInit (FMLPostInitializationEvent evt)
{
vanillaToolRecipes();
modIntegration();
}
private void addPartMapping ()
{
/* Tools */
int[] nonMetals = { 0, 1, 3, 4, 5, 6, 7, 8, 9, 17 };
if (PHConstruct.craftMetalTools)
{
for (int mat = 0; mat < 18; mat++)
{
for (int meta = 0; meta < TinkerTools.patternOutputs.length; meta++)
{
if (TinkerTools.patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(TinkerTools.woodPattern, meta + 1, mat, new ItemStack(TinkerTools.patternOutputs[meta], 1, mat));
}
}
}
else
{
for (int mat = 0; mat < nonMetals.length; mat++)
{
for (int meta = 0; meta < TinkerTools.patternOutputs.length; meta++)
{
if (TinkerTools.patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(TinkerTools.woodPattern, meta + 1, nonMetals[mat], new ItemStack(TinkerTools.patternOutputs[meta], 1, nonMetals[mat]));
}
}
}
registerPatternMaterial("plankWood", 2, "Wood");
registerPatternMaterial("stickWood", 1, "Wood");
registerPatternMaterial("slabWood", 1, "Wood");
registerPatternMaterial("compressedCobblestone1x", 18, "Stone");
}
private void addRecipesForToolBuilder ()
{
ToolBuilder tb = ToolBuilder.instance;
tb.addNormalToolRecipe(TinkerTools.pickaxe, TinkerTools.pickaxeHead, TinkerTools.toolRod, TinkerTools.binding);
tb.addNormalToolRecipe(TinkerTools.broadsword, TinkerTools.swordBlade, TinkerTools.toolRod, TinkerTools.wideGuard);
tb.addNormalToolRecipe(TinkerTools.hatchet, TinkerTools.hatchetHead, TinkerTools.toolRod);
tb.addNormalToolRecipe(TinkerTools.shovel, TinkerTools.shovelHead, TinkerTools.toolRod);
tb.addNormalToolRecipe(TinkerTools.longsword, TinkerTools.swordBlade, TinkerTools.toolRod, TinkerTools.handGuard);
tb.addNormalToolRecipe(TinkerTools.rapier, TinkerTools.swordBlade, TinkerTools.toolRod, TinkerTools.crossbar);
tb.addNormalToolRecipe(TinkerTools.frypan, TinkerTools.frypanHead, TinkerTools.toolRod);
tb.addNormalToolRecipe(TinkerTools.battlesign, TinkerTools.signHead, TinkerTools.toolRod);
tb.addNormalToolRecipe(TinkerTools.mattock, TinkerTools.hatchetHead, TinkerTools.toolRod, TinkerTools.shovelHead);
tb.addNormalToolRecipe(TinkerTools.dagger, TinkerTools.knifeBlade, TinkerTools.toolRod, TinkerTools.crossbar);
tb.addNormalToolRecipe(TinkerTools.cutlass, TinkerTools.swordBlade, TinkerTools.toolRod, TinkerTools.fullGuard);
tb.addNormalToolRecipe(TinkerTools.chisel, TinkerTools.chiselHead, TinkerTools.toolRod);
tb.addNormalToolRecipe(TinkerTools.scythe, TinkerTools.scytheBlade, TinkerTools.toughRod, TinkerTools.toughBinding, TinkerTools.toughRod);
tb.addNormalToolRecipe(TinkerTools.lumberaxe, TinkerTools.broadAxeHead, TinkerTools.toughRod, TinkerTools.largePlate, TinkerTools.toughBinding);
tb.addNormalToolRecipe(TinkerTools.cleaver, TinkerTools.largeSwordBlade, TinkerTools.toughRod, TinkerTools.largePlate, TinkerTools.toughRod);
tb.addNormalToolRecipe(TinkerTools.excavator, TinkerTools.excavatorHead, TinkerTools.toughRod, TinkerTools.largePlate, TinkerTools.toughBinding);
tb.addNormalToolRecipe(TinkerTools.hammer, TinkerTools.hammerHead, TinkerTools.toughRod, TinkerTools.largePlate, TinkerTools.largePlate);
tb.addNormalToolRecipe(TinkerTools.battleaxe, TinkerTools.broadAxeHead, TinkerTools.toughRod, TinkerTools.broadAxeHead, TinkerTools.toughBinding);
BowRecipe recipe = new BowRecipe(TinkerTools.toolRod, TinkerTools.bowstring, TinkerTools.toolRod, TinkerTools.shortbow);
tb.addCustomToolRecipe(recipe);
tb.addNormalToolRecipe(TinkerTools.arrow, TinkerTools.arrowhead, TinkerTools.toolRod, TinkerTools.fletching);
ItemStack diamond = new ItemStack(Items.diamond);
ModifyBuilder.registerModifier(new ModToolRepair());
ModifyBuilder.registerModifier(new ModDurability(new ItemStack[] { diamond }, 0, 500, 0f, 3, "Diamond", "\u00a7b"
+ StatCollector.translateToLocal("modifier.tool.diamond"), "\u00a7b"));
ModifyBuilder.registerModifier(new ModDurability(new ItemStack[] { new ItemStack(Items.emerald) }, 1, 0, 0.5f, 2, "Emerald", "\u00a72"
+ StatCollector.translateToLocal("modifier.tool.emerald"), "\u00a72"));
ItemStack redstoneItem = new ItemStack(Items.redstone);
ItemStack redstoneBlock = new ItemStack(Blocks.redstone_block);
ModifyBuilder.registerModifier(new ModRedstone(2, new ItemStack[] { redstoneItem, redstoneBlock }, new int[] { 1, 9 }));
ModifyBuilder.registerModifier(new ModInteger(new ItemStack[] { new ItemStack(TinkerTools.materials, 1, 6) }, 4, "Moss", 3, "\u00a72", StatCollector
.translateToLocal("modifier.tool.moss")));
ItemStack blazePowder = new ItemStack(Items.blaze_powder);
ModifyBuilder.registerModifier(new ModBlaze(7, new ItemStack[] { blazePowder }, new int[] { 1 }));
ModifyBuilder.registerModifier(new ModAutoSmelt(new ItemStack[] { new ItemStack(TinkerTools.materials, 1, 7) }, 6, "Lava", "\u00a74", StatCollector
.translateToLocal("modifier.tool.lava")));
ModifyBuilder.registerModifier(new ModInteger(new ItemStack[] { new ItemStack(TinkerTools.materials, 1, 8) }, 8, "Necrotic", 1, "\u00a78", StatCollector
.translateToLocal("modifier.tool.necro")));
ModifyBuilder.registerModifier(new ModExtraModifier(new ItemStack[] { diamond, new ItemStack(Blocks.gold_block) }, "Tier1Free"));
ModifyBuilder.registerModifier(new ModExtraModifier(new ItemStack[] { new ItemStack(Blocks.diamond_block), new ItemStack(Items.golden_apple, 1, 1) }, "Tier1.5Free"));
ModifyBuilder.registerModifier(new ModExtraModifier(new ItemStack[] { new ItemStack(Items.nether_star) }, "Tier2Free"));
ModifyBuilder.registerModifier(new ModCreativeToolModifier(new ItemStack[] { new ItemStack(TinkerTools.creativeModifier) }));
ItemStack silkyJewel = new ItemStack(TinkerTools.materials, 1, 26);
ModifyBuilder.registerModifier(new ModButtertouch(new ItemStack[] { silkyJewel }, 12));
ItemStack piston = new ItemStack(Blocks.piston);
ModifyBuilder.registerModifier(new ModPiston(3, new ItemStack[] { piston }, new int[] { 1 }));
ModifyBuilder.registerModifier(new ModInteger(new ItemStack[] { new ItemStack(Blocks.obsidian), new ItemStack(Items.ender_pearl) }, 13, "Beheading", 1,
"\u00a7d", "Beheading"));
ItemStack holySoil = new ItemStack(TinkerTools.craftedSoil, 1, 4);
ModifyBuilder.registerModifier(new ModSmite("Smite", 14, new ItemStack[] { holySoil }, new int[] { 1 }));
ItemStack spidereyeball = new ItemStack(Items.fermented_spider_eye);
ModifyBuilder.registerModifier(new ModAntiSpider("ModAntiSpider", 15, new ItemStack[] { spidereyeball }, new int[] { 1 }));
ItemStack obsidianPlate = new ItemStack(TinkerTools.largePlate, 1, 6);
ModifyBuilder.registerModifier(new ModReinforced(new ItemStack[] { obsidianPlate }, 16, 1));
TConstructRegistry.registerActiveToolMod(new TActiveOmniMod());
}
private void addRecipesForChisel ()
{
/* Detailing */
Detailing chiseling = TConstructRegistry.getChiselDetailing();
chiseling.addDetailing(Blocks.stone, 0, Blocks.stonebrick, 0, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.speedBlock, 0, TinkerSmeltery.speedBlock, 1, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.speedBlock, 2, TinkerSmeltery.speedBlock, 3, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.speedBlock, 3, TinkerSmeltery.speedBlock, 4, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.speedBlock, 4, TinkerSmeltery.speedBlock, 5, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.speedBlock, 5, TinkerSmeltery.speedBlock, 6, TinkerTools.chisel);
chiseling.addDetailing(Blocks.obsidian, 0, TinkerTools.multiBrick, 0, TinkerTools.chisel);
chiseling.addDetailing(Blocks.sandstone, 0, Blocks.sandstone, 2, TinkerTools.chisel);
chiseling.addDetailing(Blocks.sandstone, 2, Blocks.sandstone, 1, TinkerTools.chisel);
chiseling.addDetailing(Blocks.sandstone, 1, TinkerTools.multiBrick, 1, TinkerTools.chisel);
// chiseling.addDetailing(Block.netherrack, 0, TRepo.multiBrick, 2,
// TRepo.chisel);
// chiseling.addDetailing(Block.stone_refined, 0, TRepo.multiBrick, 3,
// TRepo.chisel);
chiseling.addDetailing(Items.iron_ingot, 0, TinkerTools.multiBrick, 4, TinkerTools.chisel);
chiseling.addDetailing(Items.gold_ingot, 0, TinkerTools.multiBrick, 5, TinkerTools.chisel);
chiseling.addDetailing(Items.dye, 4, TinkerTools.multiBrick, 6, TinkerTools.chisel);
chiseling.addDetailing(Items.diamond, 0, TinkerTools.multiBrick, 7, TinkerTools.chisel);
chiseling.addDetailing(Items.redstone, 0, TinkerTools.multiBrick, 8, TinkerTools.chisel);
chiseling.addDetailing(Items.bone, 0, TinkerTools.multiBrick, 9, TinkerTools.chisel);
chiseling.addDetailing(Items.slime_ball, 0, TinkerTools.multiBrick, 10, TinkerTools.chisel);
chiseling.addDetailing(TinkerWorld.strangeFood, 0, TinkerTools.multiBrick, 11, TinkerTools.chisel);
chiseling.addDetailing(Blocks.end_stone, 0, TinkerTools.multiBrick, 12, TinkerTools.chisel);
chiseling.addDetailing(TinkerTools.materials, 18, TinkerTools.multiBrick, 13, TinkerTools.chisel);
// adding multiBrick / multiBrickFanxy meta 0-13 to list
for (int sc = 0; sc < 14; sc++)
{
chiseling.addDetailing(TinkerTools.multiBrick, sc, TinkerTools.multiBrickFancy, sc, TinkerTools.chisel);
}
chiseling.addDetailing(Blocks.stonebrick, 0, TinkerTools.multiBrickFancy, 15, TinkerTools.chisel);
chiseling.addDetailing(TinkerTools.multiBrickFancy, 15, TinkerTools.multiBrickFancy, 14, TinkerTools.chisel);
chiseling.addDetailing(TinkerTools.multiBrickFancy, 14, Blocks.stonebrick, 3, TinkerTools.chisel);
/*
* chiseling.addDetailing(TRepo.multiBrick, 14, TRepo.multiBrickFancy,
* 14, TRepo.chisel); chiseling.addDetailing(TRepo.multiBrick, 15,
* TRepo.multiBrickFancy, 15, TRepo.chisel);
*/
chiseling.addDetailing(TinkerSmeltery.smeltery, 4, TinkerSmeltery.smeltery, 6, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.smeltery, 6, TinkerSmeltery.smeltery, 11, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.smeltery, 11, TinkerSmeltery.smeltery, 2, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.smeltery, 2, TinkerSmeltery.smeltery, 8, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.smeltery, 8, TinkerSmeltery.smeltery, 9, TinkerTools.chisel);
chiseling.addDetailing(TinkerSmeltery.smeltery, 9, TinkerSmeltery.smeltery, 10, TinkerTools.chisel);
}
public void vanillaToolRecipes ()
{
if (PHConstruct.removeVanillaToolRecipes)
{
RecipeRemover.removeAnyRecipe(new ItemStack(Items.wooden_pickaxe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.wooden_axe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.wooden_shovel));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.wooden_hoe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.wooden_sword));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.stone_pickaxe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.stone_axe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.stone_shovel));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.stone_hoe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.stone_sword));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.iron_pickaxe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.iron_axe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.iron_shovel));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.iron_hoe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.iron_sword));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.diamond_pickaxe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.diamond_axe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.diamond_shovel));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.diamond_hoe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.diamond_sword));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.golden_pickaxe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.golden_axe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.golden_shovel));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.golden_hoe));
RecipeRemover.removeAnyRecipe(new ItemStack(Items.golden_sword));
}
if (PHConstruct.labotimizeVanillaTools)
{
Items.wooden_pickaxe.setMaxDamage(1);
Items.wooden_axe.setMaxDamage(1);
Items.wooden_shovel.setMaxDamage(1);
Items.wooden_hoe.setMaxDamage(1);
Items.wooden_sword.setMaxDamage(1);
Items.stone_pickaxe.setMaxDamage(1);
Items.stone_axe.setMaxDamage(1);
Items.stone_shovel.setMaxDamage(1);
Items.stone_hoe.setMaxDamage(1);
Items.stone_sword.setMaxDamage(1);
Items.iron_pickaxe.setMaxDamage(1);
Items.iron_axe.setMaxDamage(1);
Items.iron_shovel.setMaxDamage(1);
Items.iron_hoe.setMaxDamage(1);
Items.iron_sword.setMaxDamage(1);
Items.diamond_pickaxe.setMaxDamage(1);
Items.diamond_axe.setMaxDamage(1);
Items.diamond_shovel.setMaxDamage(1);
Items.diamond_hoe.setMaxDamage(1);
Items.diamond_sword.setMaxDamage(1);
Items.golden_pickaxe.setMaxDamage(1);
Items.golden_axe.setMaxDamage(1);
Items.golden_shovel.setMaxDamage(1);
Items.golden_hoe.setMaxDamage(1);
Items.golden_sword.setMaxDamage(1);
}
}
public static void registerPatternMaterial (String oreName, int value, String materialName)
{
for (ItemStack ore : OreDictionary.getOres(oreName))
{
PatternBuilder.instance.registerMaterial(ore, value, materialName);
}
}
private void craftingTableRecipes()
{
String[] patBlock = { "###", "###", "###" };
String[] patSurround = { "###", "#m#", "###" };
Object[] toolForgeBlocks = { "blockIron", "blockGold", Blocks.diamond_block, Blocks.emerald_block, "blockCobalt", "blockArdite", "blockManyullyn", "blockCopper", "blockBronze", "blockTin",
"blockAluminum", "blockAluminumBrass", "blockAlumite", "blockSteel" };
// ToolForge Recipes (Metal Version)
for (int sc = 0; sc < toolForgeBlocks.length; sc++)
{
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.toolForge, 1, sc), "bbb", "msm", "m m", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 2), 's', new ItemStack(
TinkerTools.toolStationWood, 1, 0), 'm', toolForgeBlocks[sc]));
// adding slab version recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 5), "bbb", "msm", "m m", 'b', new ItemStack(TinkerSmeltery.smeltery, 1, 2), 's', new ItemStack(
TinkerTools.craftingSlabWood, 1, 1), 'm', toolForgeBlocks[sc]));
}
// ToolStation Recipes (Wooden Version)
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', "crafterWood"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', "craftingTableWood"));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w',
new ItemStack(TinkerTools.craftingStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 0), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', new ItemStack(TinkerTools.craftingSlabWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 2), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', new ItemStack(Blocks.log, 1, 1));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 3), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', new ItemStack(Blocks.log, 1, 2));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 4), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', new ItemStack(Blocks.log, 1, 3));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 5), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', Blocks.chest);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 1), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', "logWood"));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', new ItemStack(Blocks.planks, 1, 0));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 11), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', new ItemStack(Blocks.planks, 1, 1));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 12), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', new ItemStack(Blocks.planks, 1, 2));
GameRegistry.addRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 13), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', new ItemStack(Blocks.planks, 1, 3));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.toolStationWood, 1, 10), "p", "w", 'p', new ItemStack(TinkerTools.blankPattern, 1, 0), 'w', "plankWood"));
GameRegistry.addRecipe(new ItemStack(TinkerTools.furnaceSlab, 1, 0), "###", "# #", "###", '#', new ItemStack(Blocks.stone_slab, 1, 3));
// Blank Pattern Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.blankPattern, 4, 0), "ps", "sp", 'p', "plankWood", 's', "stickWood"));
// Manual Book Recipes
GameRegistry.addRecipe(new ItemStack(TinkerTools.manualBook), "wp", 'w', new ItemStack(TinkerTools.blankPattern, 1, 0), 'p', Items.paper);
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.manualBook, 2, 0), new ItemStack(TinkerTools.manualBook, 1, 0), Items.book);
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.manualBook, 1, 1), new ItemStack(TinkerTools.manualBook, 1, 0));
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.manualBook, 2, 1), new ItemStack(TinkerTools.manualBook, 1, 1), Items.book);
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.manualBook, 1, 2), new ItemStack(TinkerTools.manualBook, 1, 1));
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.manualBook, 2, 2), new ItemStack(TinkerTools.manualBook, 1, 2), Items.book);
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.manualBook, 1, 3), new ItemStack(TinkerTools.manualBook, 1, 2));
// alternative Vanilla Book Recipe
GameRegistry.addShapelessRecipe(new ItemStack(Items.book), Items.paper, Items.paper, Items.paper, Items.string, TinkerTools.blankPattern, TinkerTools.blankPattern);
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(Items.name_tag), "P~ ", "~O ", " ~", '~', Items.string, 'P', Items.paper, 'O', "slimeball"));
// Paperstack Recipe
GameRegistry.addRecipe(new ItemStack(TinkerTools.materials, 1, 0), "pp", "pp", 'p', Items.paper);
// Mossball Recipe
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.materials, 1, 6), patBlock, '#', "stoneMossy"));
// LavaCrystal Recipes -Auto-smelt
GameRegistry.addRecipe(new ItemStack(TinkerTools.materials, 1, 7), "xcx", "cbc", "xcx", 'b', Items.lava_bucket, 'c', Items.fire_charge, 'x', Items.blaze_rod);
GameRegistry.addRecipe(new ItemStack(TinkerTools.materials, 1, 7), "xcx", "cbc", "xcx", 'b', Items.lava_bucket, 'x', Items.fire_charge, 'c', Items.blaze_rod);
// Slimy sand Recipes
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.craftedSoil, 1, 0), Items.slime_ball, Items.slime_ball, Items.slime_ball, Items.slime_ball, Blocks.sand, Blocks.dirt);
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.craftedSoil, 1, 2), TinkerWorld.strangeFood, TinkerWorld.strangeFood, TinkerWorld.strangeFood, TinkerWorld.strangeFood, Blocks.sand,
Blocks.dirt);
// Grout Recipes
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.craftedSoil, 2, 1), Items.clay_ball, Blocks.sand, Blocks.gravel);
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.craftedSoil, 8, 1), new ItemStack(Blocks.clay, 1, Short.MAX_VALUE), Blocks.sand, Blocks.sand, Blocks.sand, Blocks.sand,
Blocks.gravel, Blocks.gravel, Blocks.gravel, Blocks.gravel);
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.craftedSoil, 2, 6), Items.nether_wart, Blocks.soul_sand, Blocks.gravel);
// Graveyard Soil Recipes
GameRegistry.addShapelessRecipe(new ItemStack(TinkerTools.craftedSoil, 1, 3), Blocks.dirt, Items.rotten_flesh, new ItemStack(Items.dye, 1, 15));
// Silky Cloth Recipes
GameRegistry.addRecipe(new ItemStack(TinkerTools.materials, 1, 25), patSurround, 'm', new ItemStack(TinkerTools.materials, 1, 24), '#', new ItemStack(Items.string));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.materials, 1, 25), patSurround, 'm', "nuggetGold", '#', new ItemStack(Items.string)));
// Silky Jewel Recipes
GameRegistry.addRecipe(new ItemStack(TinkerTools.materials, 1, 26), " c ", "cec", " c ", 'c', new ItemStack(TinkerTools.materials, 1, 25), 'e', new ItemStack(Items.emerald));
// Advanced WorkBench Recipes
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.craftingStationWood, 1, 0), "b", 'b', "crafterWood"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.craftingStationWood, 1, 0), "b", 'b', "craftingTableWood"));
// Slab crafters
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.craftingSlabWood, 6, 0), "bbb", 'b', "crafterWood"));
GameRegistry.addRecipe(new ShapedOreRecipe(new ItemStack(TinkerTools.craftingSlabWood, 6, 0), "bbb", 'b', "craftingTableWood"));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 0), "b", 'b', new ItemStack(TinkerTools.craftingStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 1), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 0));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 2), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 1));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 2), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 2));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 2), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 3));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 2), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 4));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 4), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 5));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 3), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 10));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 3), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 11));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 3), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 12));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 3), "b", 'b', new ItemStack(TinkerTools.toolStationWood, 1, 13));
GameRegistry.addRecipe(new ItemStack(TinkerTools.craftingSlabWood, 1, 5), "b", 'b', new ItemStack(TinkerTools.toolForge, 1, Short.MAX_VALUE));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(TinkerTools.materials, 1, 41), "dustArdite", "dustCobalt"));
GameRegistry.addRecipe(new ShapelessOreRecipe(new ItemStack(TinkerTools.materials, 4, 42), "dustAluminium", "dustAluminium", "dustAluminium", "dustCopper"));
}
private void modIntegration()
{
/* TE3 Flux */
ItemStack batHardened = GameRegistry.findItemStack("ThermalExpansion", "capacitorHardened", 1);
if (batHardened != null)
{
TinkerTools.modFlux.batteries.add(batHardened);
}
ItemStack basicCell = GameRegistry.findItemStack("ThermalExpansion", "cellBasic", 1);
if (basicCell != null)
{
TinkerTools.modFlux.batteries.add(basicCell);
}
ItemStack ironpick = ToolBuilder.instance.buildTool(new ItemStack(TinkerTools.pickaxeHead, 1, 6), new ItemStack(TinkerTools.toolRod, 1, 2), new ItemStack(TinkerTools.binding, 1, 6), "");
if (batHardened != null)
TConstructClientRegistry.registerManualModifier("fluxmod", ironpick.copy(), (ItemStack) batHardened);
if (basicCell != null)
TConstructClientRegistry.registerManualModifier("fluxmod2", ironpick.copy(), (ItemStack) basicCell);
/* Thaumcraft */
Object obj = ItemHelper.getStaticItem("itemResource", "thaumcraft.common.config.ConfigItems");
if (obj != null)
{
TConstruct.logger.info("Thaumcraft detected. Adding thaumium tools.");
TinkerTools.thaumcraftAvailable = true;
TConstructClientRegistry.addMaterialRenderMapping(31, "tinker", "thaumium", true);
TConstructRegistry.addToolMaterial(31, "Thaumium", 3, 400, 700, 2, 1.3F, 0, 0f, "\u00A75", "materialtraits.thaumic");
PatternBuilder.instance.registerFullMaterial(new ItemStack((Item) obj, 1, 2), 2, StatCollector.translateToLocal("gui.partbuilder.material.thaumium"), new ItemStack(TinkerTools.toolShard,
1, 31), new ItemStack(TinkerTools.toolRod, 1, 31), 31);
for (int meta = 0; meta < TinkerTools.patternOutputs.length; meta++)
{
if (TinkerTools.patternOutputs[meta] != null)
TConstructRegistry.addPartMapping(TinkerTools.woodPattern, meta + 1, 31, new ItemStack(TinkerTools.patternOutputs[meta], 1, 31));
}
TConstructRegistry.addBowstringMaterial(1, 2, new ItemStack((Item) obj, 1, 7), new ItemStack(TinkerTools.bowstring, 1, 1), 1F, 1F, 0.9f);
TConstructRegistry.addBowMaterial(31, 576, 40, 1.2f);
TConstructRegistry.addArrowMaterial(31, 1.8F, 0.5F, 100F);
}
else
{
TConstruct.logger.warn("Thaumcraft not detected.");
}
if (Loader.isModLoaded("Natura"))
{
try
{
Object plantItem = ItemHelper.getStaticItem("plantItem", "mods.natura.common.NContent");
TConstructRegistry.addBowstringMaterial(2, 2, new ItemStack((Item) plantItem, 1, 7), new ItemStack(TinkerTools.bowstring, 1, 2), 1.2F, 0.8F, 1.3f);
}
catch (Exception e)
{
} // No need to handle
}
}
void registerMaterials ()
{
TConstructRegistry.addToolMaterial(0, "Wood", "Wooden ", 1, 97, 350, 0, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(1, "Stone", 1, 131, 400, 1, 0.5F, 0, 1f, "", "materialtraits.stonebound");
TConstructRegistry.addToolMaterial(2, "Iron", 2, 250, 600, 2, 1.3F, 1, 0f, "\u00A7f", "");
TConstructRegistry.addToolMaterial(3, "Flint", 1, 171, 525, 2, 0.7F, 0, 0f, "\u00A78", "");
TConstructRegistry.addToolMaterial(4, "Cactus", 1, 150, 500, 2, 1.0F, 0, -1f, "\u00A72", "materialtraits.jagged");
TConstructRegistry.addToolMaterial(5, "Bone", 1, 200, 400, 1, 1.0F, 0, 0f, "\u00A7e", "");
TConstructRegistry.addToolMaterial(6, "Obsidian", 3, 89, 700, 2, 0.8F, 3, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(7, "Netherrack", 2, 131, 400, 1, 1.2F, 0, 1f, "\u00A74", "materialtraits.stonebound");
TConstructRegistry.addToolMaterial(8, "Slime", 0, 500, 150, 0, 1.5F, 0, 0f, "\u00A7a", "");
TConstructRegistry.addToolMaterial(9, "Paper", 0, 30, 200, 0, 0.3F, 0, 0f, "\u00A7f", "materialtraits.writable");
TConstructRegistry.addToolMaterial(10, "Cobalt", 4, 800, 1400, 3, 1.75F, 2, 0f, "\u00A73", "");
TConstructRegistry.addToolMaterial(11, "Ardite", 4, 500, 800, 3, 2.0F, 0, 2f, "\u00A74", "materialtraits.stonebound");
TConstructRegistry.addToolMaterial(12, "Manyullyn", 5, 1200, 900, 4, 2.5F, 0, 0f, "\u00A75", "");
TConstructRegistry.addToolMaterial(13, "Copper", 1, 180, 500, 2, 1.15F, 0, 0f, "\u00A7c", "");
TConstructRegistry.addToolMaterial(14, "Bronze", 2, 550, 800, 2, 1.3F, 1, 0f, "\u00A76", "");
TConstructRegistry.addToolMaterial(15, "Alumite", 4, 700, 800, 3, 1.3F, 2, 0f, "\u00A7d", "");
TConstructRegistry.addToolMaterial(16, "Steel", 4, 750, 1000, 4, 1.3F, 2, 0f, "", "");
TConstructRegistry.addToolMaterial(17, "BlueSlime", "Slime ", 0, 1200, 150, 0, 2.0F, 0, 0f, "\u00A7b", "");
TConstructRegistry.addToolMaterial(18, "PigIron", "Pig Iron ", 3, 250, 600, 2, 1.3F, 1, 0f, "\u00A7c", "materialtraits.tasty");
TConstructRegistry.addBowMaterial(0, 384, 20, 1.0f); // Wood
TConstructRegistry.addBowMaterial(1, 10, 80, 0.2f); // Stone
TConstructRegistry.addBowMaterial(2, 576, 30, 1.2f); // Iron
TConstructRegistry.addBowMaterial(3, 10, 80, 0.2f); // Flint
TConstructRegistry.addBowMaterial(4, 384, 20, 1.0f); // Cactus
TConstructRegistry.addBowMaterial(5, 192, 30, 1.0f); // Bone
TConstructRegistry.addBowMaterial(6, 10, 80, 0.2f); // Obsidian
TConstructRegistry.addBowMaterial(7, 10, 80, 0.2f); // Netherrack
TConstructRegistry.addBowMaterial(8, 1536, 30, 1.2f); // Slime
TConstructRegistry.addBowMaterial(9, 48, 25, 0.5f); // Paper
TConstructRegistry.addBowMaterial(10, 1152, 30, 1.2f); // Cobalt
TConstructRegistry.addBowMaterial(11, 960, 30, 1.2f); // Ardite
TConstructRegistry.addBowMaterial(12, 1536, 30, 1.2f); // Manyullyn
TConstructRegistry.addBowMaterial(13, 384, 30, 1.2f); // Copper
TConstructRegistry.addBowMaterial(14, 576, 30, 1.2f); // Bronze
TConstructRegistry.addBowMaterial(15, 768, 30, 1.2f); // Alumite
TConstructRegistry.addBowMaterial(16, 768, 30, 1.2f); // Steel
TConstructRegistry.addBowMaterial(17, 576, 20, 1.2f); // Blue Slime
TConstructRegistry.addBowMaterial(18, 384, 20, 1.2f); // Slime
// Material ID, mass, fragility
TConstructRegistry.addArrowMaterial(0, 0.69F, 1.0F, 100F); //Wood
TConstructRegistry.addArrowMaterial(1, 2.05F, 5.0F, 100F); //Stone
TConstructRegistry.addArrowMaterial(2, 3.6F, 0.5F, 100F); //Iron
TConstructRegistry.addArrowMaterial(3, 1.325F, 1.0F, 100F); //Flint
TConstructRegistry.addArrowMaterial(4, 0.76F, 1.0F, 100F); //Cactus
TConstructRegistry.addArrowMaterial(5, 0.69F, 1.0F, 100); //Bone
TConstructRegistry.addArrowMaterial(6, 2.4F, 1.0F, 100F); //Obsidian
TConstructRegistry.addArrowMaterial(7, 1.5F, 1.0F, 100F); //Netherrack
TConstructRegistry.addArrowMaterial(8, 0.22F, 0.0F, 100F); //Slime
TConstructRegistry.addArrowMaterial(9, 0.69F, 3.0F, 90F); //Paper
TConstructRegistry.addArrowMaterial(10, 3.0F, 0.25F, 100F); //Cobalt
TConstructRegistry.addArrowMaterial(11, 1.25F, 0.25F, 100F); //Ardite
TConstructRegistry.addArrowMaterial(12, 2.25F, 0.1F, 100F); //Manyullyn
TConstructRegistry.addArrowMaterial(13, 2.7F, 0.5F, 100F); //Copper
TConstructRegistry.addArrowMaterial(14, 3.6F, 0.25F, 100F); //Bronze
TConstructRegistry.addArrowMaterial(15, 1.1F, 0.25F, 100F); //Alumite
TConstructRegistry.addArrowMaterial(16, 3.6F, 0.25F, 100F); //Steel
TConstructRegistry.addArrowMaterial(17, 0.22F, 0.0F, 100F); //Blue Slime
TConstructRegistry.addArrowMaterial(18, 3.6F, 0.5F, 100F); //Pigiron
TConstructRegistry.addBowstringMaterial(0, 2, new ItemStack(Items.string), new ItemStack(TinkerTools.bowstring, 1, 0), 1F, 1F, 1f); // String
TConstructRegistry.addFletchingMaterial(0, 2, new ItemStack(Items.feather), new ItemStack(TinkerTools.fletching, 1, 0), 100F, 0F, 0.05F); // Feather
for (int i = 0; i < 4; i++)
TConstructRegistry.addFletchingMaterial(1, 2, new ItemStack(Blocks.leaves, 1, i), new ItemStack(TinkerTools.fletching, 1, 1), 75F, 0F, 0.2F); // All four vanialla Leaves
TConstructRegistry.addFletchingMaterial(2, 2, new ItemStack(TinkerTools.materials, 1, 1), new ItemStack(TinkerTools.fletching, 1, 2), 100F, 0F, 0.12F); // Slime
TConstructRegistry.addFletchingMaterial(3, 2, new ItemStack(TinkerTools.materials, 1, 17), new ItemStack(TinkerTools.fletching, 1, 3), 100F, 0F, 0.12F); // BlueSlime
PatternBuilder pb = PatternBuilder.instance;
if (PHConstruct.enableTWood)
pb.registerFullMaterial(Blocks.planks, 2, "Wood", new ItemStack(Items.stick), new ItemStack(Items.stick), 0);
else
pb.registerMaterialSet("Wood", new ItemStack(Items.stick, 2), new ItemStack(Items.stick), 0);
if (PHConstruct.enableTStone)
{
pb.registerFullMaterial(Blocks.stone, 2, "Stone", new ItemStack(TinkerTools.toolShard, 1, 1), new ItemStack(TinkerTools.toolRod, 1, 1), 1);
pb.registerMaterial(Blocks.cobblestone, 2, "Stone");
}
else
pb.registerMaterialSet("Stone", new ItemStack(TinkerTools.toolShard, 1, 1), new ItemStack(TinkerTools.toolRod, 1, 1), 0);
pb.registerFullMaterial(Items.iron_ingot, 2, "Iron", new ItemStack(TinkerTools.toolShard, 1, 2), new ItemStack(TinkerTools.toolRod, 1, 2), 2);
if (PHConstruct.enableTFlint)
pb.registerFullMaterial(Items.flint, 2, "Flint", new ItemStack(TinkerTools.toolShard, 1, 3), new ItemStack(TinkerTools.toolRod, 1, 3), 3);
else
pb.registerMaterialSet("Flint", new ItemStack(TinkerTools.toolShard, 1, 3), new ItemStack(TinkerTools.toolRod, 1, 3), 3);
if (PHConstruct.enableTCactus)
pb.registerFullMaterial(Blocks.cactus, 2, "Cactus", new ItemStack(TinkerTools.toolShard, 1, 4), new ItemStack(TinkerTools.toolRod, 1, 4), 4);
else
pb.registerMaterialSet("Cactus", new ItemStack(TinkerTools.toolShard, 1, 4), new ItemStack(TinkerTools.toolRod, 1, 4), 4);
if (PHConstruct.enableTBone)
pb.registerFullMaterial(Items.bone, 2, "Bone", new ItemStack(Items.dye, 1, 15), new ItemStack(Items.bone), 5);
else
pb.registerMaterialSet("Bone", new ItemStack(Items.dye, 1, 15), new ItemStack(Items.bone), 5);
pb.registerFullMaterial(Blocks.obsidian, 2, "Obsidian", new ItemStack(TinkerTools.toolShard, 1, 6), new ItemStack(TinkerTools.toolRod, 1, 6), 6);
pb.registerMaterial(new ItemStack(materials, 1, 18), 2, "Obsidian");
if (PHConstruct.enableTNetherrack)
pb.registerFullMaterial(Blocks.netherrack, 2, "Netherrack", new ItemStack(TinkerTools.toolShard, 1, 7), new ItemStack(TinkerTools.toolRod, 1, 7), 7);
else
pb.registerMaterialSet("Netherrack", new ItemStack(TinkerTools.toolShard, 1, 7), new ItemStack(TinkerTools.toolRod, 1, 7), 7);
if (PHConstruct.enableTSlime)
pb.registerFullMaterial(new ItemStack(materials, 1, 1), 2, "Slime", new ItemStack(toolShard, 1, 8), new ItemStack(toolRod, 1, 8), 8);
else
pb.registerMaterialSet("Slime", new ItemStack(TinkerTools.toolShard, 1, 8), new ItemStack(TinkerTools.toolRod, 1, 17), 8);
if (PHConstruct.enableTPaper)
pb.registerFullMaterial(new ItemStack(materials, 1, 0), 2, "Paper", new ItemStack(Items.paper, 2), new ItemStack(toolRod, 1, 9), 9);
else
pb.registerMaterialSet("BlueSlime", new ItemStack(Items.paper, 2), new ItemStack(TinkerTools.toolRod, 1, 9), 9);
pb.registerMaterialSet("Cobalt", new ItemStack(toolShard, 1, 10), new ItemStack(toolRod, 1, 10), 10);
pb.registerMaterialSet("Ardite", new ItemStack(toolShard, 1, 11), new ItemStack(toolRod, 1, 11), 11);
pb.registerMaterialSet("Manyullyn", new ItemStack(toolShard, 1, 12), new ItemStack(toolRod, 1, 12), 12);
pb.registerMaterialSet("Copper", new ItemStack(toolShard, 1, 13), new ItemStack(toolRod, 1, 13), 13);
pb.registerMaterialSet("Bronze", new ItemStack(toolShard, 1, 14), new ItemStack(toolRod, 1, 14), 14);
pb.registerMaterialSet("Alumite", new ItemStack(toolShard, 1, 15), new ItemStack(toolRod, 1, 15), 15);
pb.registerMaterialSet("Steel", new ItemStack(toolShard, 1, 16), new ItemStack(toolRod, 1, 16), 16);
if (PHConstruct.enableTBlueSlime)
pb.registerFullMaterial(new ItemStack(materials, 1, 17), 2, "BlueSlime", new ItemStack(toolShard, 1, 17), new ItemStack(toolRod, 1, 17), 17);
else
pb.registerMaterialSet("BlueSlime", new ItemStack(TinkerTools.toolShard, 1, 17), new ItemStack(TinkerTools.toolRod, 1, 17), 17);
pb.registerFullMaterial(new ItemStack(materials, 1, 34), 2, "PigIron", new ItemStack(toolShard, 1, 18), new ItemStack(toolRod, 1, 18), 18);
pb.addToolPattern((IPattern) TinkerTools.woodPattern);
}
private void registerStencils()
{
StencilBuilder.registerBlankStencil(new ItemStack(TinkerTools.blankPattern));
// we register this manually because we want that specific order
StencilBuilder.registerStencil(TinkerTools.woodPattern, 1); // tool rod
StencilBuilder.registerStencil(TinkerTools.woodPattern, 9); // binding
StencilBuilder.registerStencil(TinkerTools.woodPattern, 14); // large tool rod
StencilBuilder.registerStencil(TinkerTools.woodPattern, 15); // large binding
StencilBuilder.registerStencil(TinkerTools.woodPattern, 2); // pickaxe head
StencilBuilder.registerStencil(TinkerTools.woodPattern, 3); // shovel head
StencilBuilder.registerStencil(TinkerTools.woodPattern, 4); // hatchet head
StencilBuilder.registerStencil(TinkerTools.woodPattern, 18); // scythe
StencilBuilder.registerStencil(TinkerTools.woodPattern, 21); // hammer head
StencilBuilder.registerStencil(TinkerTools.woodPattern, 19); // excavator head
StencilBuilder.registerStencil(TinkerTools.woodPattern, 17); // lumberaxe head
StencilBuilder.registerStencil(TinkerTools.woodPattern, 16); // large plate
StencilBuilder.registerStencil(TinkerTools.woodPattern, 10); // frying pan
StencilBuilder.registerStencil(TinkerTools.woodPattern, 11); // battlesign
StencilBuilder.registerStencil(TinkerTools.woodPattern, 13); // chisel
StencilBuilder.registerStencil(TinkerTools.woodPattern, 12); // knifeblade
StencilBuilder.registerStencil(TinkerTools.woodPattern, 5); // swordblade
StencilBuilder.registerStencil(TinkerTools.woodPattern, 20); // cleaver blade
StencilBuilder.registerStencil(TinkerTools.woodPattern, 8); // crossbar
StencilBuilder.registerStencil(TinkerTools.woodPattern, 7); // small guard
StencilBuilder.registerStencil(TinkerTools.woodPattern, 6); // wide guard
StencilBuilder.registerStencil(TinkerTools.woodPattern, 25); // arrow head
StencilBuilder.registerStencil(TinkerTools.woodPattern, 24); // fletchling
StencilBuilder.registerStencil(TinkerTools.woodPattern, 23); // bowstring
}
}
| true | true | public void preInit (FMLPreInitializationEvent event)
{
MinecraftForge.EVENT_BUS.register(new TinkerToolEvents());
//Blocks
TinkerTools.toolStationWood = new ToolStationBlock(Material.wood).setBlockName("ToolStation");
TinkerTools.toolForge = new ToolForgeBlock(Material.iron).setBlockName("ToolForge");
TinkerTools.craftingStationWood = new CraftingStationBlock(Material.wood).setBlockName("CraftingStation");
TinkerTools.craftingSlabWood = new CraftingSlab(Material.wood).setBlockName("CraftingSlab");
TinkerTools.furnaceSlab = new FurnaceSlab(Material.rock).setBlockName("FurnaceSlab");
TinkerTools.heldItemBlock = new EquipBlock(Material.wood).setBlockName("Frypan");
/* battlesignBlock = new BattlesignBlock(PHConstruct.battlesignBlock).setUnlocalizedName("Battlesign");
GameRegistry.registerBlock(battlesignBlock, "BattlesignBlock");
ameRegistry.registerTileEntity(BattlesignLogic.class, "BattlesignLogic");*/
TinkerTools.craftedSoil = new SoilBlock().setLightOpacity(0).setBlockName("TConstruct.Soil");
TinkerTools.craftedSoil.stepSound = Block.soundTypeGravel;
GameRegistry.registerBlock(TinkerTools.toolStationWood, ToolStationItemBlock.class, "ToolStationBlock");
GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation");
GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter");
GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder");
GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper");
GameRegistry.registerBlock(TinkerTools.toolForge, MetadataItemBlock.class, "ToolForgeBlock");
GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge");
GameRegistry.registerBlock(TinkerTools.craftingStationWood, "CraftingStation");
GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation");
GameRegistry.registerBlock(TinkerTools.craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab");
GameRegistry.registerBlock(TinkerTools.furnaceSlab, "FurnaceSlab");
GameRegistry.registerTileEntity(FurnaceLogic.class, "TConstruct.Furnace");
GameRegistry.registerBlock(TinkerTools.heldItemBlock, "HeldItemBlock");
GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic");
GameRegistry.registerBlock(TinkerTools.craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil");
//Items
TinkerTools.titleIcon = new TitleIcon().setUnlocalizedName("tconstruct.titleicon");
GameRegistry.registerItem(TinkerTools.titleIcon, "titleIcon");
String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" };
TinkerTools.blankPattern = new CraftingItem(blanks, blanks, "materials/", "tinker", TConstructRegistry.materialTab).setUnlocalizedName("tconstruct.Pattern");
GameRegistry.registerItem(TinkerTools.blankPattern, "blankPattern");
TinkerTools.materials = new MaterialItem().setUnlocalizedName("tconstruct.Materials");
TinkerTools.toolRod = new ToolPart("_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod");
TinkerTools.toolShard = new ToolShard("_chunk").setUnlocalizedName("tconstruct.ToolShard");
TinkerTools.woodPattern = new Pattern("pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern");
GameRegistry.registerItem(TinkerTools.materials, "materials");
GameRegistry.registerItem(TinkerTools.woodPattern, "woodPattern");
TConstructRegistry.addItemToDirectory("blankPattern", TinkerTools.blankPattern);
TConstructRegistry.addItemToDirectory("woodPattern", TinkerTools.woodPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 1; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(TinkerTools.woodPattern, 1, i));
}
TinkerTools.manualBook = new Manual();
GameRegistry.registerItem(TinkerTools.manualBook, "manualBook");
TinkerTools.pickaxe = new Pickaxe();
TinkerTools.shovel = new Shovel();
TinkerTools.hatchet = new Hatchet();
TinkerTools.broadsword = new Broadsword();
TinkerTools.longsword = new Longsword();
TinkerTools.rapier = new Rapier();
TinkerTools.dagger = new Dagger();
TinkerTools.cutlass = new Cutlass();
TinkerTools.frypan = new FryingPan();
TinkerTools.battlesign = new BattleSign();
TinkerTools.mattock = new Mattock();
TinkerTools.chisel = new Chisel();
TinkerTools.lumberaxe = new LumberAxe();
TinkerTools.cleaver = new Cleaver();
TinkerTools.scythe = new Scythe();
TinkerTools.excavator = new Excavator();
TinkerTools.hammer = new Hammer();
TinkerTools.battleaxe = new Battleaxe();
TinkerTools.shortbow = new Shortbow();
TinkerTools.arrow = new Arrow();
Item[] tools = { TinkerTools.pickaxe, TinkerTools.shovel, TinkerTools.hatchet, TinkerTools.broadsword, TinkerTools.longsword, TinkerTools.rapier, TinkerTools.dagger, TinkerTools.cutlass, TinkerTools.frypan, TinkerTools.battlesign, TinkerTools.mattock,
TinkerTools.chisel, TinkerTools.lumberaxe, TinkerTools.cleaver, TinkerTools.scythe, TinkerTools.excavator, TinkerTools.hammer, TinkerTools.battleaxe, TinkerTools.shortbow, TinkerTools.arrow };
String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "dagger", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver",
"scythe", "excavator", "hammer", "battleaxe", "shortbow", "arrow" };
for (int i = 0; i < tools.length; i++)
{
GameRegistry.registerItem(tools[i], toolStrings[i]); // 1.7 compat
TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]);
}
TinkerTools.potionLauncher = new PotionLauncher().setUnlocalizedName("tconstruct.PotionLauncher");
GameRegistry.registerItem(TinkerTools.potionLauncher, "potionLauncher");
TinkerTools.pickaxeHead = new ToolPart("_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead");
TinkerTools.shovelHead = new ToolPart("_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead");
TinkerTools.hatchetHead = new ToolPart("_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead");
TinkerTools.binding = new ToolPart("_binding", "Binding").setUnlocalizedName("tconstruct.Binding");
TinkerTools.toughBinding = new ToolPart("_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding");
TinkerTools.toughRod = new ToolPart("_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod");
TinkerTools.largePlate = new ToolPart("_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate");
TinkerTools.swordBlade = new ToolPart("_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade");
TinkerTools.wideGuard = new ToolPart("_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard");
TinkerTools.handGuard = new ToolPart("_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard");
TinkerTools.crossbar = new ToolPart("_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar");
TinkerTools.knifeBlade = new ToolPart("_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade");
TinkerTools.fullGuard = new ToolPartHidden("_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard");
TinkerTools.frypanHead = new ToolPart("_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead");
TinkerTools.signHead = new ToolPart("_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead");
TinkerTools.chiselHead = new ToolPart("_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead");
TinkerTools.scytheBlade = new ToolPart("_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade");
TinkerTools.broadAxeHead = new ToolPart("_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead");
TinkerTools.excavatorHead = new ToolPart("_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead");
TinkerTools.largeSwordBlade = new ToolPart("_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade");
TinkerTools.hammerHead = new ToolPart("_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead");
TinkerTools.bowstring = new Bowstring().setUnlocalizedName("tconstruct.Bowstring");
TinkerTools.arrowhead = new ToolPart("_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead");
TinkerTools.fletching = new Fletching().setUnlocalizedName("tconstruct.Fletching");
Item[] toolParts = { TinkerTools.toolRod, TinkerTools.toolShard, TinkerTools.pickaxeHead, TinkerTools.shovelHead, TinkerTools.hatchetHead, TinkerTools.binding, TinkerTools.toughBinding, TinkerTools.toughRod, TinkerTools.largePlate,
TinkerTools.swordBlade, TinkerTools.wideGuard, TinkerTools.handGuard, TinkerTools.crossbar, TinkerTools.knifeBlade, TinkerTools.fullGuard, TinkerTools.frypanHead, TinkerTools.signHead, TinkerTools.chiselHead, TinkerTools.scytheBlade,
TinkerTools.broadAxeHead, TinkerTools.excavatorHead, TinkerTools.largeSwordBlade, TinkerTools.hammerHead, TinkerTools.bowstring, TinkerTools.fletching, TinkerTools.arrowhead };
String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard",
"crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring",
"fletching", "arrowhead" };
for (int i = 0; i < toolParts.length; i++)
{
GameRegistry.registerItem(toolParts[i], toolPartStrings[i]); // 1.7
// compat
TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]);
}
goldHead = new GoldenHead(4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead");
GameRegistry.registerItem(TinkerTools.goldHead, "goldHead");
TinkerTools.creativeModifier = new CreativeModifier().setUnlocalizedName("tconstruct.modifier.creative");
GameRegistry.registerItem(TinkerTools.creativeModifier, "creativeModifier");
String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper",
"ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper",
"nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze",
"nuggetAlumite", "nuggetSteel", "ingotPigIron", "nuggetPigIron", "glueball" };
for (int i = 0; i < materialStrings.length; i++)
{
TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(TinkerTools.materials, 1, i));
}
registerMaterials();
registerStencils();
//TODO: Redesign stencil table to be a sensible block
TinkerTools.patternOutputs = new Item[] { TinkerTools.toolRod, TinkerTools.pickaxeHead, TinkerTools.shovelHead, TinkerTools.hatchetHead, TinkerTools.swordBlade, TinkerTools.wideGuard,
TinkerTools.handGuard, TinkerTools.crossbar, TinkerTools.binding, TinkerTools.frypanHead, TinkerTools.signHead, TinkerTools.knifeBlade, TinkerTools.chiselHead, TinkerTools.toughRod,
TinkerTools.toughBinding, TinkerTools.largePlate, TinkerTools.broadAxeHead, TinkerTools.scytheBlade, TinkerTools.excavatorHead, TinkerTools.largeSwordBlade, TinkerTools.hammerHead,
TinkerTools.fullGuard, null, null, TinkerTools.arrowhead, null };
//Moved temporarily to deal with AE2 Quartz
TinkerTools.modFlux = new ModFlux();
ModifyBuilder.registerModifier(TinkerTools.modFlux);
ItemStack lapisItem = new ItemStack(Items.dye, 1, 4);
ItemStack lapisBlock = new ItemStack(Blocks.lapis_block);
TinkerTools.modLapis = new ModLapis(10, new ItemStack[] { lapisItem, lapisBlock }, new int[] { 1, 9 });
ModifyBuilder.registerModifier(TinkerTools.modLapis);
TinkerTools.modAttack = new ModAttack("Quartz", 11, new ItemStack[] { new ItemStack(Items.quartz),
new ItemStack(Blocks.quartz_block, 1, Short.MAX_VALUE) }, new int[] { 1, 4 });
ModifyBuilder.registerModifier(TinkerTools.modAttack);
}
| public void preInit (FMLPreInitializationEvent event)
{
MinecraftForge.EVENT_BUS.register(new TinkerToolEvents());
//Blocks
TinkerTools.toolStationWood = new ToolStationBlock(Material.wood).setBlockName("ToolStation");
TinkerTools.toolForge = new ToolForgeBlock(Material.iron).setBlockName("ToolForge");
TinkerTools.craftingStationWood = new CraftingStationBlock(Material.wood).setBlockName("CraftingStation");
TinkerTools.craftingSlabWood = new CraftingSlab(Material.wood).setBlockName("CraftingSlab");
TinkerTools.furnaceSlab = new FurnaceSlab(Material.rock).setBlockName("FurnaceSlab");
TinkerTools.heldItemBlock = new EquipBlock(Material.wood).setBlockName("Frypan");
/* battlesignBlock = new BattlesignBlock(PHConstruct.battlesignBlock).setUnlocalizedName("Battlesign");
GameRegistry.registerBlock(battlesignBlock, "BattlesignBlock");
ameRegistry.registerTileEntity(BattlesignLogic.class, "BattlesignLogic");*/
TinkerTools.craftedSoil = new SoilBlock().setLightOpacity(0).setBlockName("TConstruct.Soil");
TinkerTools.craftedSoil.stepSound = Block.soundTypeGravel;
GameRegistry.registerBlock(TinkerTools.toolStationWood, ToolStationItemBlock.class, "ToolStationBlock");
GameRegistry.registerTileEntity(ToolStationLogic.class, "ToolStation");
GameRegistry.registerTileEntity(PartBuilderLogic.class, "PartCrafter");
GameRegistry.registerTileEntity(PatternChestLogic.class, "PatternHolder");
GameRegistry.registerTileEntity(StencilTableLogic.class, "PatternShaper");
GameRegistry.registerBlock(TinkerTools.toolForge, MetadataItemBlock.class, "ToolForgeBlock");
GameRegistry.registerTileEntity(ToolForgeLogic.class, "ToolForge");
GameRegistry.registerBlock(TinkerTools.craftingStationWood, "CraftingStation");
GameRegistry.registerTileEntity(CraftingStationLogic.class, "CraftingStation");
GameRegistry.registerBlock(TinkerTools.craftingSlabWood, CraftingSlabItemBlock.class, "CraftingSlab");
GameRegistry.registerBlock(TinkerTools.furnaceSlab, "FurnaceSlab");
GameRegistry.registerTileEntity(FurnaceLogic.class, "TConstruct.Furnace");
GameRegistry.registerBlock(TinkerTools.heldItemBlock, "HeldItemBlock");
GameRegistry.registerTileEntity(FrypanLogic.class, "FrypanLogic");
GameRegistry.registerBlock(TinkerTools.craftedSoil, CraftedSoilItemBlock.class, "CraftedSoil");
//Items
TinkerTools.titleIcon = new TitleIcon().setUnlocalizedName("tconstruct.titleicon");
GameRegistry.registerItem(TinkerTools.titleIcon, "titleIcon");
String[] blanks = new String[] { "blank_pattern", "blank_cast", "blank_cast" };
TinkerTools.blankPattern = new CraftingItem(blanks, blanks, "materials/", "tinker", TConstructRegistry.materialTab).setUnlocalizedName("tconstruct.Pattern");
GameRegistry.registerItem(TinkerTools.blankPattern, "blankPattern");
TinkerTools.materials = new MaterialItem().setUnlocalizedName("tconstruct.Materials");
TinkerTools.toolRod = new ToolPart("_rod", "ToolRod").setUnlocalizedName("tconstruct.ToolRod");
TinkerTools.toolShard = new ToolShard("_chunk").setUnlocalizedName("tconstruct.ToolShard");
TinkerTools.woodPattern = new Pattern("pattern_", "materials/").setUnlocalizedName("tconstruct.Pattern");
GameRegistry.registerItem(TinkerTools.materials, "materials");
GameRegistry.registerItem(TinkerTools.woodPattern, "woodPattern");
TConstructRegistry.addItemToDirectory("blankPattern", TinkerTools.blankPattern);
TConstructRegistry.addItemToDirectory("woodPattern", TinkerTools.woodPattern);
String[] patternTypes = { "ingot", "toolRod", "pickaxeHead", "shovelHead", "hatchetHead", "swordBlade", "wideGuard", "handGuard", "crossbar", "binding", "frypanHead", "signHead",
"knifeBlade", "chiselHead", "toughRod", "toughBinding", "largePlate", "broadAxeHead", "scytheHead", "excavatorHead", "largeBlade", "hammerHead", "fullGuard" };
for (int i = 1; i < patternTypes.length; i++)
{
TConstructRegistry.addItemStackToDirectory(patternTypes[i] + "Pattern", new ItemStack(TinkerTools.woodPattern, 1, i));
}
TinkerTools.manualBook = new Manual();
GameRegistry.registerItem(TinkerTools.manualBook, "manualBook");
TinkerTools.pickaxe = new Pickaxe();
TinkerTools.shovel = new Shovel();
TinkerTools.hatchet = new Hatchet();
TinkerTools.broadsword = new Broadsword();
TinkerTools.longsword = new Longsword();
TinkerTools.rapier = new Rapier();
TinkerTools.dagger = new Dagger();
TinkerTools.cutlass = new Cutlass();
TinkerTools.frypan = new FryingPan();
TinkerTools.battlesign = new BattleSign();
TinkerTools.mattock = new Mattock();
TinkerTools.chisel = new Chisel();
TinkerTools.lumberaxe = new LumberAxe();
TinkerTools.cleaver = new Cleaver();
TinkerTools.scythe = new Scythe();
TinkerTools.excavator = new Excavator();
TinkerTools.hammer = new Hammer();
TinkerTools.battleaxe = new Battleaxe();
TinkerTools.shortbow = new Shortbow();
TinkerTools.arrow = new Arrow();
Item[] tools = { TinkerTools.pickaxe, TinkerTools.shovel, TinkerTools.hatchet, TinkerTools.broadsword, TinkerTools.longsword, TinkerTools.rapier, TinkerTools.dagger, TinkerTools.cutlass, TinkerTools.frypan, TinkerTools.battlesign, TinkerTools.mattock,
TinkerTools.chisel, TinkerTools.lumberaxe, TinkerTools.cleaver, TinkerTools.scythe, TinkerTools.excavator, TinkerTools.hammer, TinkerTools.battleaxe, TinkerTools.shortbow, TinkerTools.arrow };
String[] toolStrings = { "pickaxe", "shovel", "hatchet", "broadsword", "longsword", "rapier", "dagger", "cutlass", "frypan", "battlesign", "mattock", "chisel", "lumberaxe", "cleaver",
"scythe", "excavator", "hammer", "battleaxe", "shortbow", "arrow" };
for (int i = 0; i < tools.length; i++)
{
GameRegistry.registerItem(tools[i], toolStrings[i]); // 1.7 compat
TConstructRegistry.addItemToDirectory(toolStrings[i], tools[i]);
}
TinkerTools.potionLauncher = new PotionLauncher().setUnlocalizedName("tconstruct.PotionLauncher");
GameRegistry.registerItem(TinkerTools.potionLauncher, "potionLauncher");
TinkerTools.pickaxeHead = new ToolPart("_pickaxe_head", "PickHead").setUnlocalizedName("tconstruct.PickaxeHead");
TinkerTools.shovelHead = new ToolPart("_shovel_head", "ShovelHead").setUnlocalizedName("tconstruct.ShovelHead");
TinkerTools.hatchetHead = new ToolPart("_axe_head", "AxeHead").setUnlocalizedName("tconstruct.AxeHead");
TinkerTools.binding = new ToolPart("_binding", "Binding").setUnlocalizedName("tconstruct.Binding");
TinkerTools.toughBinding = new ToolPart("_toughbind", "ToughBind").setUnlocalizedName("tconstruct.ThickBinding");
TinkerTools.toughRod = new ToolPart("_toughrod", "ToughRod").setUnlocalizedName("tconstruct.ThickRod");
TinkerTools.largePlate = new ToolPart("_largeplate", "LargePlate").setUnlocalizedName("tconstruct.LargePlate");
TinkerTools.swordBlade = new ToolPart("_sword_blade", "SwordBlade").setUnlocalizedName("tconstruct.SwordBlade");
TinkerTools.wideGuard = new ToolPart("_large_guard", "LargeGuard").setUnlocalizedName("tconstruct.LargeGuard");
TinkerTools.handGuard = new ToolPart("_medium_guard", "MediumGuard").setUnlocalizedName("tconstruct.MediumGuard");
TinkerTools.crossbar = new ToolPart("_crossbar", "Crossbar").setUnlocalizedName("tconstruct.Crossbar");
TinkerTools.knifeBlade = new ToolPart("_knife_blade", "KnifeBlade").setUnlocalizedName("tconstruct.KnifeBlade");
TinkerTools.fullGuard = new ToolPartHidden("_full_guard", "FullGuard").setUnlocalizedName("tconstruct.FullGuard");
TinkerTools.frypanHead = new ToolPart("_frypan_head", "FrypanHead").setUnlocalizedName("tconstruct.FrypanHead");
TinkerTools.signHead = new ToolPart("_battlesign_head", "SignHead").setUnlocalizedName("tconstruct.SignHead");
TinkerTools.chiselHead = new ToolPart("_chisel_head", "ChiselHead").setUnlocalizedName("tconstruct.ChiselHead");
TinkerTools.scytheBlade = new ToolPart("_scythe_head", "ScytheHead").setUnlocalizedName("tconstruct.ScytheBlade");
TinkerTools.broadAxeHead = new ToolPart("_lumberaxe_head", "LumberHead").setUnlocalizedName("tconstruct.LumberHead");
TinkerTools.excavatorHead = new ToolPart("_excavator_head", "ExcavatorHead").setUnlocalizedName("tconstruct.ExcavatorHead");
TinkerTools.largeSwordBlade = new ToolPart("_large_sword_blade", "LargeSwordBlade").setUnlocalizedName("tconstruct.LargeSwordBlade");
TinkerTools.hammerHead = new ToolPart("_hammer_head", "HammerHead").setUnlocalizedName("tconstruct.HammerHead");
TinkerTools.bowstring = new Bowstring().setUnlocalizedName("tconstruct.Bowstring");
TinkerTools.arrowhead = new ToolPart("_arrowhead", "ArrowHead").setUnlocalizedName("tconstruct.Arrowhead");
TinkerTools.fletching = new Fletching().setUnlocalizedName("tconstruct.Fletching");
Item[] toolParts = { TinkerTools.toolRod, TinkerTools.toolShard, TinkerTools.pickaxeHead, TinkerTools.shovelHead, TinkerTools.hatchetHead, TinkerTools.binding, TinkerTools.toughBinding, TinkerTools.toughRod, TinkerTools.largePlate,
TinkerTools.swordBlade, TinkerTools.wideGuard, TinkerTools.handGuard, TinkerTools.crossbar, TinkerTools.knifeBlade, TinkerTools.fullGuard, TinkerTools.frypanHead, TinkerTools.signHead, TinkerTools.chiselHead, TinkerTools.scytheBlade,
TinkerTools.broadAxeHead, TinkerTools.excavatorHead, TinkerTools.largeSwordBlade, TinkerTools.hammerHead, TinkerTools.bowstring, TinkerTools.fletching, TinkerTools.arrowhead };
String[] toolPartStrings = { "toolRod", "toolShard", "pickaxeHead", "shovelHead", "hatchetHead", "binding", "toughBinding", "toughRod", "heavyPlate", "swordBlade", "wideGuard", "handGuard",
"crossbar", "knifeBlade", "fullGuard", "frypanHead", "signHead", "chiselHead", "scytheBlade", "broadAxeHead", "excavatorHead", "largeSwordBlade", "hammerHead", "bowstring",
"fletching", "arrowhead" };
for (int i = 0; i < toolParts.length; i++)
{
GameRegistry.registerItem(toolParts[i], toolPartStrings[i]); // 1.7
// compat
TConstructRegistry.addItemToDirectory(toolPartStrings[i], toolParts[i]);
}
goldHead = new GoldenHead(4, 1.2F, false).setAlwaysEdible().setPotionEffect(Potion.regeneration.id, 10, 0, 1.0F).setUnlocalizedName("goldenhead");
GameRegistry.registerItem(TinkerTools.goldHead, "goldHead");
TinkerTools.creativeModifier = new CreativeModifier().setUnlocalizedName("tconstruct.modifier.creative");
GameRegistry.registerItem(TinkerTools.creativeModifier, "creativeModifier");
String[] materialStrings = { "paperStack", "greenSlimeCrystal", "searedBrick", "ingotCobalt", "ingotArdite", "ingotManyullyn", "mossBall", "lavaCrystal", "necroticBone", "ingotCopper",
"ingotTin", "ingotAluminum", "rawAluminum", "ingotBronze", "ingotAluminumBrass", "ingotAlumite", "ingotSteel", "blueSlimeCrystal", "ingotObsidian", "nuggetIron", "nuggetCopper",
"nuggetTin", "nuggetAluminum", "nuggetSilver", "nuggetAluminumBrass", "silkyCloth", "silkyJewel", "nuggetObsidian", "nuggetCobalt", "nuggetArdite", "nuggetManyullyn", "nuggetBronze",
"nuggetAlumite", "nuggetSteel", "ingotPigIron", "nuggetPigIron", "glueball" };
for (int i = 0; i < materialStrings.length; i++)
{
TConstructRegistry.addItemStackToDirectory(materialStrings[i], new ItemStack(TinkerTools.materials, 1, i));
}
registerMaterials();
registerStencils();
// this array is only used to register the remaining pattern-part-interactions
TinkerTools.patternOutputs = new Item[] { TinkerTools.toolRod, TinkerTools.pickaxeHead, TinkerTools.shovelHead, TinkerTools.hatchetHead, TinkerTools.swordBlade, TinkerTools.wideGuard,
TinkerTools.handGuard, TinkerTools.crossbar, TinkerTools.binding, TinkerTools.frypanHead, TinkerTools.signHead, TinkerTools.knifeBlade, TinkerTools.chiselHead, TinkerTools.toughRod,
TinkerTools.toughBinding, TinkerTools.largePlate, TinkerTools.broadAxeHead, TinkerTools.scytheBlade, TinkerTools.excavatorHead, TinkerTools.largeSwordBlade, TinkerTools.hammerHead,
TinkerTools.fullGuard, null, null, TinkerTools.arrowhead, null };
//Moved temporarily to deal with AE2 Quartz
TinkerTools.modFlux = new ModFlux();
ModifyBuilder.registerModifier(TinkerTools.modFlux);
ItemStack lapisItem = new ItemStack(Items.dye, 1, 4);
ItemStack lapisBlock = new ItemStack(Blocks.lapis_block);
TinkerTools.modLapis = new ModLapis(10, new ItemStack[] { lapisItem, lapisBlock }, new int[] { 1, 9 });
ModifyBuilder.registerModifier(TinkerTools.modLapis);
TinkerTools.modAttack = new ModAttack("Quartz", 11, new ItemStack[] { new ItemStack(Items.quartz),
new ItemStack(Blocks.quartz_block, 1, Short.MAX_VALUE) }, new int[] { 1, 4 });
ModifyBuilder.registerModifier(TinkerTools.modAttack);
}
|
diff --git a/src/edu/sc/seis/sod/subsetter/waveformArm/LocalSeismogramArm.java b/src/edu/sc/seis/sod/subsetter/waveformArm/LocalSeismogramArm.java
index 22cffe0c8..fa2bf1296 100644
--- a/src/edu/sc/seis/sod/subsetter/waveformArm/LocalSeismogramArm.java
+++ b/src/edu/sc/seis/sod/subsetter/waveformArm/LocalSeismogramArm.java
@@ -1,436 +1,436 @@
package edu.sc.seis.sod.subsetter.waveFormArm;
import edu.sc.seis.sod.*;
import edu.sc.seis.sod.database.*;
import edu.sc.seis.sod.subsetter.*;
import edu.iris.Fissures.IfEvent.*;
import edu.iris.Fissures.event.*;
import edu.iris.Fissures.model.*;
import edu.iris.Fissures.IfNetwork.*;
import edu.iris.Fissures.network.*;
import edu.iris.Fissures.IfSeismogramDC.*;
import org.w3c.dom.*;
import org.apache.log4j.*;
import java.util.*;
/**
* sample xml
*<pre>
*<localSeismogramArm>
* <phaseRequest>
* <beginPhase>ttp</beginPhase>
* <beginOffset>
* <unit>SECOND</unit>
* <value>-120</value>
* </beginOffset>
* <endPhase>tts</endPhase>
* <endOffset>
* <unit>SECOND</unit>
* <value>600</value>
* </endOffset>
* </phaseRequest>
*
* <availableDataAND>
* <nogaps/>
* <fullCoverage/>
* </availableDataAND>
*
* <sacFileProcessor>
* <dataDirectory>SceppEvents</dataDirectory>
* </sacFileProcessor>
*</localSeismogramArm>
*</pre>
*/
public class LocalSeismogramArm implements Subsetter{
public LocalSeismogramArm (Element config) throws ConfigurationException{
if ( ! config.getTagName().equals("localSeismogramArm")) {
throw new IllegalArgumentException("Configuration element must be a localSeismogramArm tag");
}
processConfig(config);
}
/**
* Describe <code>processConfig</code> method here.
*
* @param config an <code>Element</code> value
* @exception ConfigurationException if an error occurs
*/
protected void processConfig(Element config)
throws ConfigurationException {
NodeList children = config.getChildNodes();
Node node;
for (int i=0; i<children.getLength(); i++) {
node = children.item(i);
if (node instanceof Element) {
if (((Element)node).getTagName().equals("description")) {
// skip description element
continue;
}
Object sodElement = SodUtil.load((Element)node,"edu.sc.seis.sod.subsetter.waveFormArm");
if(sodElement instanceof EventChannelSubsetter) eventChannelSubsetter = (EventChannelSubsetter)sodElement;
else if(sodElement instanceof RequestGenerator) requestGeneratorSubsetter = (RequestGenerator)sodElement;
else if(sodElement instanceof AvailableDataSubsetter) availableDataSubsetter = (AvailableDataSubsetter)sodElement;
else if(sodElement instanceof LocalSeismogramSubsetter) localSeismogramSubsetter = (LocalSeismogramSubsetter)sodElement;
else if(sodElement instanceof LocalSeismogramProcess) {
localSeisProcessList.add(sodElement);
} else {
logger.warn("Unknown tag in LocalSeismogramArm config. "
+sodElement);
} // end of else
} // end of if (node instanceof Element)
} // end of for (int i=0; i<children.getSize(); i++)
}
/**
* Starts the processing of the localSeismogramArm.
*/
public void processLocalSeismogramArm(EventDbObject eventDbObject,
NetworkDbObject networkDbObject,
ChannelDbObject channelDbObject,
DataCenter dataCenter,
WaveFormArm waveformArm) throws Exception{
EventAccessOperations eventAccess = eventDbObject.getEventAccess();
NetworkAccess networkAccess = networkDbObject.getNetworkAccess();
Channel channel = channelDbObject.getChannel();
MicroSecondDate chanBegin = new MicroSecondDate(channel.effective_time.start_time);
MicroSecondDate chanEnd;
if(channel.effective_time.end_time != null) {
chanEnd = new MicroSecondDate(channel.effective_time.end_time);
} else {
chanEnd = TimeUtils.future;
}
if(chanEnd.before(chanBegin)) {
chanEnd = TimeUtils.future;
}
MicroSecondDate originTime = new MicroSecondDate(eventAccess.get_preferred_origin().origin_time);
TimeInterval day = new TimeInterval(1, UnitImpl.DAY);
logger.info("channelbeginTime is "+chanBegin);
logger.info("channelendTime is "+chanEnd);
logger.info("originTime is "+originTime);
logger.info("originTime incr is "+ originTime.add(day));
if (chanBegin.after(originTime.add(day))
|| chanEnd.before(originTime)) {
// channel doesn't overlap origin
logger.info("fail "+ChannelIdUtil.toString(channel.get_id())+" doesn't everlap originTime="+originTime+" endTime="+chanEnd+" begin="+chanBegin);
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_REJECT,
"channel EffectiveTime doesnot overlap event");
return;
}
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.PROCESSING,
"completedEffectiveTimeOverlaps");
processEventChannelSubsetter(eventDbObject,
networkDbObject,
channelDbObject,
dataCenter,
waveformArm);
}
/**
* handles eventChannelSubsetter
*
* @exception Exception if an error occurs
*/
public void processEventChannelSubsetter(EventDbObject eventDbObject,
NetworkDbObject networkDbObject,
ChannelDbObject channelDbObject,
DataCenter dataCenter,
WaveFormArm waveformArm) throws Exception{
boolean b;
EventAccessOperations eventAccess = eventDbObject.getEventAccess();
NetworkAccess networkAccess = networkDbObject.getNetworkAccess();
Channel channel = channelDbObject.getChannel();
synchronized (eventChannelSubsetter) {
b = eventChannelSubsetter.accept(eventAccess,
networkAccess,
channel,
null);
}
if( b ) {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.PROCESSING,
"EventChannelSubsetterSucceeded");
processRequestGeneratorSubsetter(eventDbObject,
networkDbObject,
channelDbObject,
dataCenter,
waveformArm
);
} else {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_REJECT,
"EventChannelSubsetterfailed");
}
}
/**
* handles requestGenerator Subsetter.
*
*/
public void processRequestGeneratorSubsetter(EventDbObject eventDbObject,
NetworkDbObject networkDbObject,
ChannelDbObject channelDbObject,
DataCenter dataCenter,
WaveFormArm waveformArm)
throws Exception
{
RequestFilter[] infilters;
EventAccessOperations eventAccess = eventDbObject.getEventAccess();
NetworkAccess networkAccess = networkDbObject.getNetworkAccess();
Channel channel = channelDbObject.getChannel();
synchronized (requestGeneratorSubsetter) {
infilters =
requestGeneratorSubsetter.generateRequest(eventAccess,
networkAccess,
channel,
null);
}
logger.debug("BEFORE getting seismograms "+infilters.length);
for (int i=0; i<infilters.length; i++) {
logger.debug("Getting seismograms "
+ChannelIdUtil.toString(infilters[i].channel_id)
+" from "
+infilters[i].start_time.date_time
+" to "
+infilters[i].end_time.date_time);
} // end of for (int i=0; i<outFilters.length; i++)
RequestFilter[] outfilters = dataCenter.available_data(infilters);
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.PROCESSING,
"requestgeneratorSubsettterCompleted");
processAvailableDataSubsetter(eventDbObject,
networkDbObject,
channelDbObject,
dataCenter,
infilters,
outfilters,
waveformArm);
}
/**
* handles availableDataSubsetter
*
*/
public void processAvailableDataSubsetter(EventDbObject eventDbObject,
NetworkDbObject networkDbObject,
ChannelDbObject channelDbObject,
DataCenter dataCenter,
RequestFilter[] infilters,
RequestFilter[] outfilters,
WaveFormArm waveformArm)
throws Exception
{
boolean b;
EventAccessOperations eventAccess = eventDbObject.getEventAccess();
NetworkAccess networkAccess = networkDbObject.getNetworkAccess();
Channel channel = channelDbObject.getChannel();
synchronized (availableDataSubsetter) {
b = availableDataSubsetter.accept(eventAccess,
networkAccess,
channel,
infilters,
outfilters,
null);
}
if( b ) {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.PROCESSING,
"availableDataSubsetterCompleted");
logger.debug("Using infilters, fix this when DMC fixes server");
MicroSecondDate before = new MicroSecondDate();
LocalSeismogram[] localSeismograms;
if (outfilters.length != 0) {
- // localSeismograms = dataCenter.retrieve_seismograms(infilters);
- localSeismograms = new LocalSeismogram[0];
+ localSeismograms = dataCenter.retrieve_seismograms(infilters);
+ //localSeismograms = new LocalSeismogram[0];
} else {
localSeismograms = new LocalSeismogram[0];
} // end of else
MicroSecondDate after = new MicroSecondDate();
logger.debug("After getting seismograms "+after.subtract(before));
logger.debug("Using infilters, fix this when DMC fixes server");
for (int i=0; i<localSeismograms.length; i++) {
if (localSeismograms[i] == null) {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_REJECT,
"rejected as the seismogram array Contained NULL entried");
logger.error("Got null in seismogram array "+ChannelIdUtil.toString(channel.get_id()));
return;
}
if ( ! ChannelIdUtil.areEqual(localSeismograms[i].channel_id, channel.get_id())) {
// must be server error
logger.debug("Channel id in returned seismogram doesn not match channelid in request. req="
+ChannelIdUtil.toString(channel.get_id())
+" seis="
+ChannelIdUtil.toString(localSeismograms[i].channel_id));
// fix seis with original id
localSeismograms[i].channel_id = channel.get_id();
} // end of if ()
} // end of for (int i=0; i<localSeismograms.length; i++)
processLocalSeismogramSubsetter(eventDbObject,
networkDbObject,
channelDbObject,
infilters,
outfilters,
localSeismograms,
waveformArm);
} else {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_REJECT,
"AvailableDataSubsetterFailed");
}
}
/**
* handles LocalSeismogramSubsetter.
*/
public void processLocalSeismogramSubsetter (EventDbObject eventDbObject,
NetworkDbObject networkDbObject,
ChannelDbObject channelDbObject,
RequestFilter[] infilters,
RequestFilter[] outfilters,
LocalSeismogram[] localSeismograms,
WaveFormArm waveformArm) throws Exception {
logger.debug("Using infilters, fix this when DMC fixes server");
boolean b;
EventAccessOperations eventAccess = eventDbObject.getEventAccess();
NetworkAccess networkAccess = networkDbObject.getNetworkAccess();
Channel channel= channelDbObject.getChannel();
synchronized (localSeismogramSubsetter) {
b = localSeismogramSubsetter.accept(eventAccess,
networkAccess,
channel,
infilters,
outfilters,
localSeismograms,
null);
}
if( b ) {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.PROCESSING,
"localSeismogramSubsetterAccepted");
processSeismograms(eventDbObject,
networkDbObject,
channelDbObject,
infilters,
outfilters,
localSeismograms,
waveformArm);
} else {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_REJECT,
"LocalSeismogramSubsetterFailed");
}
}
/**
* processes the seismograms obtained from the seismogram server.
*/
public void processSeismograms(EventDbObject eventDbObject,
NetworkDbObject networkDbObject,
ChannelDbObject channelDbObject,
RequestFilter[] infilters,
RequestFilter[] outfilters,
LocalSeismogram[] localSeismograms,
WaveFormArm waveformArm)
throws Exception
{
EventAccessOperations eventAccess = eventDbObject.getEventAccess();
NetworkAccess networkAccess = networkDbObject.getNetworkAccess();
Channel channel = channelDbObject.getChannel();
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.PROCESSING,
"before waveformArm Processing");
LocalSeismogramProcess processor;
Iterator it = localSeisProcessList.iterator();
while (it.hasNext()) {
processor = (LocalSeismogramProcess)it.next();
synchronized (processor) {
localSeismograms =
processor.process(eventAccess,
networkAccess,
channel,
infilters,
outfilters,
localSeismograms,
null);
}
} // end of while (it.hasNext())
logger.debug("finished with "+
ChannelIdUtil.toStringNoDates(channel.get_id()));
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_SUCCESS,
"successful");
}
private EventChannelSubsetter eventChannelSubsetter =
new NullEventChannelSubsetter();
private RequestGenerator requestGeneratorSubsetter =
new NullRequestGenerator();
private AvailableDataSubsetter availableDataSubsetter =
new NullAvailableDataSubsetter();
private LocalSeismogramSubsetter localSeismogramSubsetter =
new NullLocalSeismogramSubsetter();
private LinkedList localSeisProcessList =
new LinkedList();
static Category logger =
Category.getInstance(LocalSeismogramArm.class.getName());
}// LocalSeismogramArm
| true | true | public void processAvailableDataSubsetter(EventDbObject eventDbObject,
NetworkDbObject networkDbObject,
ChannelDbObject channelDbObject,
DataCenter dataCenter,
RequestFilter[] infilters,
RequestFilter[] outfilters,
WaveFormArm waveformArm)
throws Exception
{
boolean b;
EventAccessOperations eventAccess = eventDbObject.getEventAccess();
NetworkAccess networkAccess = networkDbObject.getNetworkAccess();
Channel channel = channelDbObject.getChannel();
synchronized (availableDataSubsetter) {
b = availableDataSubsetter.accept(eventAccess,
networkAccess,
channel,
infilters,
outfilters,
null);
}
if( b ) {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.PROCESSING,
"availableDataSubsetterCompleted");
logger.debug("Using infilters, fix this when DMC fixes server");
MicroSecondDate before = new MicroSecondDate();
LocalSeismogram[] localSeismograms;
if (outfilters.length != 0) {
// localSeismograms = dataCenter.retrieve_seismograms(infilters);
localSeismograms = new LocalSeismogram[0];
} else {
localSeismograms = new LocalSeismogram[0];
} // end of else
MicroSecondDate after = new MicroSecondDate();
logger.debug("After getting seismograms "+after.subtract(before));
logger.debug("Using infilters, fix this when DMC fixes server");
for (int i=0; i<localSeismograms.length; i++) {
if (localSeismograms[i] == null) {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_REJECT,
"rejected as the seismogram array Contained NULL entried");
logger.error("Got null in seismogram array "+ChannelIdUtil.toString(channel.get_id()));
return;
}
if ( ! ChannelIdUtil.areEqual(localSeismograms[i].channel_id, channel.get_id())) {
// must be server error
logger.debug("Channel id in returned seismogram doesn not match channelid in request. req="
+ChannelIdUtil.toString(channel.get_id())
+" seis="
+ChannelIdUtil.toString(localSeismograms[i].channel_id));
// fix seis with original id
localSeismograms[i].channel_id = channel.get_id();
} // end of if ()
} // end of for (int i=0; i<localSeismograms.length; i++)
processLocalSeismogramSubsetter(eventDbObject,
networkDbObject,
channelDbObject,
infilters,
outfilters,
localSeismograms,
waveformArm);
} else {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_REJECT,
"AvailableDataSubsetterFailed");
}
}
| public void processAvailableDataSubsetter(EventDbObject eventDbObject,
NetworkDbObject networkDbObject,
ChannelDbObject channelDbObject,
DataCenter dataCenter,
RequestFilter[] infilters,
RequestFilter[] outfilters,
WaveFormArm waveformArm)
throws Exception
{
boolean b;
EventAccessOperations eventAccess = eventDbObject.getEventAccess();
NetworkAccess networkAccess = networkDbObject.getNetworkAccess();
Channel channel = channelDbObject.getChannel();
synchronized (availableDataSubsetter) {
b = availableDataSubsetter.accept(eventAccess,
networkAccess,
channel,
infilters,
outfilters,
null);
}
if( b ) {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.PROCESSING,
"availableDataSubsetterCompleted");
logger.debug("Using infilters, fix this when DMC fixes server");
MicroSecondDate before = new MicroSecondDate();
LocalSeismogram[] localSeismograms;
if (outfilters.length != 0) {
localSeismograms = dataCenter.retrieve_seismograms(infilters);
//localSeismograms = new LocalSeismogram[0];
} else {
localSeismograms = new LocalSeismogram[0];
} // end of else
MicroSecondDate after = new MicroSecondDate();
logger.debug("After getting seismograms "+after.subtract(before));
logger.debug("Using infilters, fix this when DMC fixes server");
for (int i=0; i<localSeismograms.length; i++) {
if (localSeismograms[i] == null) {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_REJECT,
"rejected as the seismogram array Contained NULL entried");
logger.error("Got null in seismogram array "+ChannelIdUtil.toString(channel.get_id()));
return;
}
if ( ! ChannelIdUtil.areEqual(localSeismograms[i].channel_id, channel.get_id())) {
// must be server error
logger.debug("Channel id in returned seismogram doesn not match channelid in request. req="
+ChannelIdUtil.toString(channel.get_id())
+" seis="
+ChannelIdUtil.toString(localSeismograms[i].channel_id));
// fix seis with original id
localSeismograms[i].channel_id = channel.get_id();
} // end of if ()
} // end of for (int i=0; i<localSeismograms.length; i++)
processLocalSeismogramSubsetter(eventDbObject,
networkDbObject,
channelDbObject,
infilters,
outfilters,
localSeismograms,
waveformArm);
} else {
waveformArm.setFinalStatus(eventDbObject,
channelDbObject,
Status.COMPLETE_REJECT,
"AvailableDataSubsetterFailed");
}
}
|
diff --git a/src/main/java/com/gmail/ikeike443/PlayAutoTestBuilder.java b/src/main/java/com/gmail/ikeike443/PlayAutoTestBuilder.java
index 4703767..77bd1bb 100644
--- a/src/main/java/com/gmail/ikeike443/PlayAutoTestBuilder.java
+++ b/src/main/java/com/gmail/ikeike443/PlayAutoTestBuilder.java
@@ -1,256 +1,256 @@
package com.gmail.ikeike443;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Proc;
import hudson.model.BuildListener;
import hudson.model.ParameterValue;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.ParametersAction;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.FormValidation;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
/**
* @author ikeike443
*/
public class PlayAutoTestBuilder extends Builder{
private final String play_cmd;
private final String play_cmd2;
private final String play_cmd3;
private final String play_cmd4;
private final String play_cmd5;
private final List<String> play_cmds;
private final String play_path;
@SuppressWarnings("serial")
@DataBoundConstructor
public PlayAutoTestBuilder(
final String play_cmd,
final String play_cmd2,
final String play_cmd3,
final String play_cmd4,
final String play_cmd5,
final String play_path) {
System.out.println("Creating play auto test builder");
this.play_cmd = ensureCommandString(play_cmd);
this.play_cmd2 = ensureCommandString(play_cmd2);
this.play_cmd3 = ensureCommandString(play_cmd3);
this.play_cmd4 = ensureCommandString(play_cmd4);
this.play_cmd5 = ensureCommandString(play_cmd5);
this.play_cmds = new ArrayList<String>(){{
add(ensureCommandString(play_cmd));
add(ensureCommandString(play_cmd2));
add(ensureCommandString(play_cmd3));
add(ensureCommandString(play_cmd4));
add(ensureCommandString(play_cmd5));
}};
System.out.println("Commands: " + play_cmds);
this.play_path = play_path;
}
String ensureCommandString(String command){
return (command!=null && command.trim().length()>0)? command:"";
}
/**
* We'll use this from the <tt>config.jelly</tt>.
*/
public String getPlay_cmd() {
return play_cmd;
}
public String getPlay_cmd2() {
return play_cmd2;
}
public String getPlay_cmd3() {
return play_cmd3;
}
public String getPlay_cmd4() {
return play_cmd4;
}
public String getPlay_cmd5() {
return play_cmd5;
}
public String getPlay_path() {
return play_path;
}
@SuppressWarnings("deprecation")
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
//clean up
try {
FilePath[] files = build.getProject().getWorkspace().list("test-result/*");
for (FilePath filePath : files) {
filePath.delete();
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
// This maps stored the executed commands and the results
Map<String,String> exitcodes = new HashMap<String, String>();
//build playpath
String playpath = null;
if(play_path != null && play_path.length() > 0) {
playpath = play_path;
} else if(getDescriptor().path()!= null){
playpath = getDescriptor().path();
}else{
listener.getLogger().println("play path is null");
return false;
}
listener.getLogger().println("play path is "+playpath);
FilePath workDir = build.getWorkspace();
String application_path = ((PlayAutoTestJobProperty)build.getProject().getProperty(PlayAutoTestJobProperty.class)).getApplication_path();
if (application_path!= null && application_path.length() > 0) {
workDir = build.getWorkspace().child(application_path);
}
try {
for(String play_cmd : this.play_cmds){
if(play_cmd!=null && play_cmd.length()==0) continue;
// Substitute parameters
listener.getLogger().println("Substituting job parameters from " + play_cmd);
ParametersAction param = build.getAction(hudson.model.ParametersAction.class);
List<ParameterValue> values = param.getParameters();
if (values != null) {
for (ParameterValue value : values) {
String v = value.createVariableResolver(build).resolve(value.getName());
play_cmd = play_cmd.replace("${" + value.getName() + "}", v);
}
}
String[] cmds= play_cmd.split(" ",2);
- String cmd = playpath + " " + cmds[0] +" "+workDir.toString()+" "+(cmds.length>=2? cmds[1]:"");
+ String cmd = playpath + " " + cmds[0] +" \""+workDir.toString()+"\" "+(cmds.length>=2? cmds[1]:"");
listener.getLogger().println("Executing " + cmd);
Proc proc = launcher.launch(cmd, new String[0],listener.getLogger(),workDir);
int exitcode = proc.join();
exitcodes.put(play_cmd, (exitcode==0? "Done":"Fail"));
if(exitcode!=0) {
listener.getLogger().println("****************************************************");
listener.getLogger().println("* ERROR!!! while executing "+play_cmd);
listener.getLogger().println("****************************************************");
return false;
}
if("auto-test".equalsIgnoreCase(play_cmd)){
//check test-result
if(! new File(workDir.toString()+"/test-result/result.passed").exists()){
build.setResult(Result.UNSTABLE);
}
}
}
listener.getLogger().println("Each commands' results:");
for(Map.Entry<String, String> rec : exitcodes.entrySet()){
listener.getLogger().println(" "+rec.getKey()+": "+rec.getValue());
}
return exitcodes.containsValue("Fail")? false : true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
/**
* Descriptor for {@link PlayAutoTestBuilder}. Used as a singleton.
* The class is marked as public so that it can be accessed from views.
*
* <p>
* See <tt>views/hudson/plugins/hello_world/HelloWorldBuilder/*.jelly</tt>
* for the actual HTML fragment for the configuration screen.
*/
@Extension // this marker indicates Hudson that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
public DescriptorImpl(){
super();
load();
}
/**
* To persist global configuration information,
* simply store it in a field and call save().
*
* <p>
* If you don't want fields to be persisted, use <tt>transient</tt>.
*/
private String path;
/**
* Performs on-the-fly validation of the form field 'name'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
*/
public FormValidation doCheckName(@QueryParameter String value) throws IOException, ServletException {
if(value.length()==0)
return FormValidation.error("Please set path to play");
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Play!";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
path = formData.getString("play_path");
save();
return super.configure(req,formData);
}
/**
* This method returns true if the global configuration says we should speak French.
*/
public String path() {
return path;
}
}
}
| true | true | public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
//clean up
try {
FilePath[] files = build.getProject().getWorkspace().list("test-result/*");
for (FilePath filePath : files) {
filePath.delete();
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
// This maps stored the executed commands and the results
Map<String,String> exitcodes = new HashMap<String, String>();
//build playpath
String playpath = null;
if(play_path != null && play_path.length() > 0) {
playpath = play_path;
} else if(getDescriptor().path()!= null){
playpath = getDescriptor().path();
}else{
listener.getLogger().println("play path is null");
return false;
}
listener.getLogger().println("play path is "+playpath);
FilePath workDir = build.getWorkspace();
String application_path = ((PlayAutoTestJobProperty)build.getProject().getProperty(PlayAutoTestJobProperty.class)).getApplication_path();
if (application_path!= null && application_path.length() > 0) {
workDir = build.getWorkspace().child(application_path);
}
try {
for(String play_cmd : this.play_cmds){
if(play_cmd!=null && play_cmd.length()==0) continue;
// Substitute parameters
listener.getLogger().println("Substituting job parameters from " + play_cmd);
ParametersAction param = build.getAction(hudson.model.ParametersAction.class);
List<ParameterValue> values = param.getParameters();
if (values != null) {
for (ParameterValue value : values) {
String v = value.createVariableResolver(build).resolve(value.getName());
play_cmd = play_cmd.replace("${" + value.getName() + "}", v);
}
}
String[] cmds= play_cmd.split(" ",2);
String cmd = playpath + " " + cmds[0] +" "+workDir.toString()+" "+(cmds.length>=2? cmds[1]:"");
listener.getLogger().println("Executing " + cmd);
Proc proc = launcher.launch(cmd, new String[0],listener.getLogger(),workDir);
int exitcode = proc.join();
exitcodes.put(play_cmd, (exitcode==0? "Done":"Fail"));
if(exitcode!=0) {
listener.getLogger().println("****************************************************");
listener.getLogger().println("* ERROR!!! while executing "+play_cmd);
listener.getLogger().println("****************************************************");
return false;
}
if("auto-test".equalsIgnoreCase(play_cmd)){
//check test-result
if(! new File(workDir.toString()+"/test-result/result.passed").exists()){
build.setResult(Result.UNSTABLE);
}
}
}
listener.getLogger().println("Each commands' results:");
for(Map.Entry<String, String> rec : exitcodes.entrySet()){
listener.getLogger().println(" "+rec.getKey()+": "+rec.getValue());
}
return exitcodes.containsValue("Fail")? false : true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
| public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
//clean up
try {
FilePath[] files = build.getProject().getWorkspace().list("test-result/*");
for (FilePath filePath : files) {
filePath.delete();
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
// This maps stored the executed commands and the results
Map<String,String> exitcodes = new HashMap<String, String>();
//build playpath
String playpath = null;
if(play_path != null && play_path.length() > 0) {
playpath = play_path;
} else if(getDescriptor().path()!= null){
playpath = getDescriptor().path();
}else{
listener.getLogger().println("play path is null");
return false;
}
listener.getLogger().println("play path is "+playpath);
FilePath workDir = build.getWorkspace();
String application_path = ((PlayAutoTestJobProperty)build.getProject().getProperty(PlayAutoTestJobProperty.class)).getApplication_path();
if (application_path!= null && application_path.length() > 0) {
workDir = build.getWorkspace().child(application_path);
}
try {
for(String play_cmd : this.play_cmds){
if(play_cmd!=null && play_cmd.length()==0) continue;
// Substitute parameters
listener.getLogger().println("Substituting job parameters from " + play_cmd);
ParametersAction param = build.getAction(hudson.model.ParametersAction.class);
List<ParameterValue> values = param.getParameters();
if (values != null) {
for (ParameterValue value : values) {
String v = value.createVariableResolver(build).resolve(value.getName());
play_cmd = play_cmd.replace("${" + value.getName() + "}", v);
}
}
String[] cmds= play_cmd.split(" ",2);
String cmd = playpath + " " + cmds[0] +" \""+workDir.toString()+"\" "+(cmds.length>=2? cmds[1]:"");
listener.getLogger().println("Executing " + cmd);
Proc proc = launcher.launch(cmd, new String[0],listener.getLogger(),workDir);
int exitcode = proc.join();
exitcodes.put(play_cmd, (exitcode==0? "Done":"Fail"));
if(exitcode!=0) {
listener.getLogger().println("****************************************************");
listener.getLogger().println("* ERROR!!! while executing "+play_cmd);
listener.getLogger().println("****************************************************");
return false;
}
if("auto-test".equalsIgnoreCase(play_cmd)){
//check test-result
if(! new File(workDir.toString()+"/test-result/result.passed").exists()){
build.setResult(Result.UNSTABLE);
}
}
}
listener.getLogger().println("Each commands' results:");
for(Map.Entry<String, String> rec : exitcodes.entrySet()){
listener.getLogger().println(" "+rec.getKey()+": "+rec.getValue());
}
return exitcodes.containsValue("Fail")? false : true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
|
diff --git a/src/com/atlauncher/gui/PackDisplay.java b/src/com/atlauncher/gui/PackDisplay.java
index 1c460f41..277c32c3 100644
--- a/src/com/atlauncher/gui/PackDisplay.java
+++ b/src/com/atlauncher/gui/PackDisplay.java
@@ -1,174 +1,174 @@
/**
* Copyright 2013 by ATLauncher and Contributors
*
* This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/.
*/
package com.atlauncher.gui;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import com.atlauncher.App;
import com.atlauncher.data.Pack;
import com.atlauncher.data.SemiPublicPack;
/**
* Class for displaying packs in the Pack Tab
*
* @author Ryan
*
*/
public class PackDisplay extends CollapsiblePanel {
private JPanel leftPanel; // Left panel with image
private JPanel rightPanel; // Right panel with description and actions
private JSplitPane splitPane; // The split pane
private JLabel packImage; // The image for the pack
private JTextArea packDescription; // Description of the pack
private JSplitPane packActions; // All the actions that can be performed on the pack
private JPanel packActionsTop; // All the actions that can be performed on the pack
private JPanel packActionsBottom; // All the actions that can be performed on the pack
private JButton newInstance; // New Instance button
private JButton createServer; // Create Server button
private JButton removePack; // Remove Pack button
private JButton support; // Support button
private JButton website; // Website button
public PackDisplay(final Pack pack) {
super(pack);
JPanel panel = super.getContentPane();
panel.setLayout(new BorderLayout());
leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
rightPanel = new JPanel();
rightPanel.setLayout(new BorderLayout());
splitPane = new JSplitPane();
splitPane.setLeftComponent(leftPanel);
splitPane.setRightComponent(rightPanel);
splitPane.setEnabled(false);
packImage = new JLabel(pack.getImage());
packDescription = new JTextArea();
packDescription.setBorder(BorderFactory.createEmptyBorder());
packDescription.setEditable(false);
packDescription.setHighlighter(null);
packDescription.setLineWrap(true);
packDescription.setWrapStyleWord(true);
packDescription.setText(pack.getDescription());
packActions = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
packActions.setEnabled(false);
packActions.setDividerSize(0);
packActionsTop = new JPanel();
packActionsTop.setLayout(new FlowLayout());
packActionsBottom = new JPanel();
packActionsBottom.setLayout(new FlowLayout());
packActions.setLeftComponent(packActionsTop);
packActions.setRightComponent(packActionsBottom);
newInstance = new JButton(App.settings.getLocalizedString("common.newinstance"));
newInstance.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (App.settings.isInOfflineMode()) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("pack.offlinenewinstance"),
App.settings.getLocalizedString("common.offline"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options,
options[0]);
} else {
if (App.settings.getAccount() == null) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("instance.cannotcreate"),
App.settings.getLocalizedString("instance.noaccountselected"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null,
options, options[0]);
} else {
new InstanceInstallerDialog(pack);
}
}
}
});
createServer = new JButton(App.settings.getLocalizedString("common.createserver"));
createServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (App.settings.isInOfflineMode()) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("pack.offlinecreateserver"),
App.settings.getLocalizedString("common.offline"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options,
options[0]);
} else {
if (App.settings.getAccount() == null) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("instance.cannotcreate"),
App.settings.getLocalizedString("instance.noaccountselected"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null,
options, options[0]);
} else {
new InstanceInstallerDialog(pack, true);
}
}
}
});
support = new JButton(App.settings.getLocalizedString("common.support"));
support.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Utils.openBrowser(pack.getSupportURL());
}
});
website = new JButton(App.settings.getLocalizedString("common.website"));
website.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Utils.openBrowser(pack.getWebsiteURL());
}
});
if (!pack.canCreateServer()) {
createServer.setVisible(false);
}
packActionsTop.add(newInstance);
packActionsTop.add(createServer);
- if (pack instanceof SemiPublicPack) {
+ if (pack instanceof SemiPublicPack && !pack.isTester()) {
removePack = new JButton("Remove Pack");
removePack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
App.settings.removePack(((SemiPublicPack)pack).getCode());
App.settings.reloadPacksPanel();
}
});
packActionsTop.add(removePack);
}
packActionsBottom.add(support);
packActionsBottom.add(website);
leftPanel.add(packImage, BorderLayout.CENTER);
rightPanel.add(packDescription, BorderLayout.CENTER);
rightPanel.add(packActions, BorderLayout.SOUTH);
panel.add(splitPane, BorderLayout.CENTER);
}
}
| true | true | public PackDisplay(final Pack pack) {
super(pack);
JPanel panel = super.getContentPane();
panel.setLayout(new BorderLayout());
leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
rightPanel = new JPanel();
rightPanel.setLayout(new BorderLayout());
splitPane = new JSplitPane();
splitPane.setLeftComponent(leftPanel);
splitPane.setRightComponent(rightPanel);
splitPane.setEnabled(false);
packImage = new JLabel(pack.getImage());
packDescription = new JTextArea();
packDescription.setBorder(BorderFactory.createEmptyBorder());
packDescription.setEditable(false);
packDescription.setHighlighter(null);
packDescription.setLineWrap(true);
packDescription.setWrapStyleWord(true);
packDescription.setText(pack.getDescription());
packActions = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
packActions.setEnabled(false);
packActions.setDividerSize(0);
packActionsTop = new JPanel();
packActionsTop.setLayout(new FlowLayout());
packActionsBottom = new JPanel();
packActionsBottom.setLayout(new FlowLayout());
packActions.setLeftComponent(packActionsTop);
packActions.setRightComponent(packActionsBottom);
newInstance = new JButton(App.settings.getLocalizedString("common.newinstance"));
newInstance.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (App.settings.isInOfflineMode()) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("pack.offlinenewinstance"),
App.settings.getLocalizedString("common.offline"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options,
options[0]);
} else {
if (App.settings.getAccount() == null) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("instance.cannotcreate"),
App.settings.getLocalizedString("instance.noaccountselected"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null,
options, options[0]);
} else {
new InstanceInstallerDialog(pack);
}
}
}
});
createServer = new JButton(App.settings.getLocalizedString("common.createserver"));
createServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (App.settings.isInOfflineMode()) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("pack.offlinecreateserver"),
App.settings.getLocalizedString("common.offline"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options,
options[0]);
} else {
if (App.settings.getAccount() == null) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("instance.cannotcreate"),
App.settings.getLocalizedString("instance.noaccountselected"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null,
options, options[0]);
} else {
new InstanceInstallerDialog(pack, true);
}
}
}
});
support = new JButton(App.settings.getLocalizedString("common.support"));
support.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Utils.openBrowser(pack.getSupportURL());
}
});
website = new JButton(App.settings.getLocalizedString("common.website"));
website.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Utils.openBrowser(pack.getWebsiteURL());
}
});
if (!pack.canCreateServer()) {
createServer.setVisible(false);
}
packActionsTop.add(newInstance);
packActionsTop.add(createServer);
if (pack instanceof SemiPublicPack) {
removePack = new JButton("Remove Pack");
removePack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
App.settings.removePack(((SemiPublicPack)pack).getCode());
App.settings.reloadPacksPanel();
}
});
packActionsTop.add(removePack);
}
packActionsBottom.add(support);
packActionsBottom.add(website);
leftPanel.add(packImage, BorderLayout.CENTER);
rightPanel.add(packDescription, BorderLayout.CENTER);
rightPanel.add(packActions, BorderLayout.SOUTH);
panel.add(splitPane, BorderLayout.CENTER);
}
| public PackDisplay(final Pack pack) {
super(pack);
JPanel panel = super.getContentPane();
panel.setLayout(new BorderLayout());
leftPanel = new JPanel();
leftPanel.setLayout(new BorderLayout());
rightPanel = new JPanel();
rightPanel.setLayout(new BorderLayout());
splitPane = new JSplitPane();
splitPane.setLeftComponent(leftPanel);
splitPane.setRightComponent(rightPanel);
splitPane.setEnabled(false);
packImage = new JLabel(pack.getImage());
packDescription = new JTextArea();
packDescription.setBorder(BorderFactory.createEmptyBorder());
packDescription.setEditable(false);
packDescription.setHighlighter(null);
packDescription.setLineWrap(true);
packDescription.setWrapStyleWord(true);
packDescription.setText(pack.getDescription());
packActions = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
packActions.setEnabled(false);
packActions.setDividerSize(0);
packActionsTop = new JPanel();
packActionsTop.setLayout(new FlowLayout());
packActionsBottom = new JPanel();
packActionsBottom.setLayout(new FlowLayout());
packActions.setLeftComponent(packActionsTop);
packActions.setRightComponent(packActionsBottom);
newInstance = new JButton(App.settings.getLocalizedString("common.newinstance"));
newInstance.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (App.settings.isInOfflineMode()) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("pack.offlinenewinstance"),
App.settings.getLocalizedString("common.offline"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options,
options[0]);
} else {
if (App.settings.getAccount() == null) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("instance.cannotcreate"),
App.settings.getLocalizedString("instance.noaccountselected"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null,
options, options[0]);
} else {
new InstanceInstallerDialog(pack);
}
}
}
});
createServer = new JButton(App.settings.getLocalizedString("common.createserver"));
createServer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (App.settings.isInOfflineMode()) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("pack.offlinecreateserver"),
App.settings.getLocalizedString("common.offline"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null, options,
options[0]);
} else {
if (App.settings.getAccount() == null) {
String[] options = { App.settings.getLocalizedString("common.ok") };
JOptionPane.showOptionDialog(App.settings.getParent(),
App.settings.getLocalizedString("instance.cannotcreate"),
App.settings.getLocalizedString("instance.noaccountselected"),
JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null,
options, options[0]);
} else {
new InstanceInstallerDialog(pack, true);
}
}
}
});
support = new JButton(App.settings.getLocalizedString("common.support"));
support.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Utils.openBrowser(pack.getSupportURL());
}
});
website = new JButton(App.settings.getLocalizedString("common.website"));
website.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Utils.openBrowser(pack.getWebsiteURL());
}
});
if (!pack.canCreateServer()) {
createServer.setVisible(false);
}
packActionsTop.add(newInstance);
packActionsTop.add(createServer);
if (pack instanceof SemiPublicPack && !pack.isTester()) {
removePack = new JButton("Remove Pack");
removePack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
App.settings.removePack(((SemiPublicPack)pack).getCode());
App.settings.reloadPacksPanel();
}
});
packActionsTop.add(removePack);
}
packActionsBottom.add(support);
packActionsBottom.add(website);
leftPanel.add(packImage, BorderLayout.CENTER);
rightPanel.add(packDescription, BorderLayout.CENTER);
rightPanel.add(packActions, BorderLayout.SOUTH);
panel.add(splitPane, BorderLayout.CENTER);
}
|
diff --git a/test/java/org/jskat/ai/nn/util/NetworkTester.java b/test/java/org/jskat/ai/nn/util/NetworkTester.java
index b1975ffd..2b5dd443 100644
--- a/test/java/org/jskat/ai/nn/util/NetworkTester.java
+++ b/test/java/org/jskat/ai/nn/util/NetworkTester.java
@@ -1,256 +1,256 @@
/**
* JSkat - A skat program written in Java
* by Jan Schäfer and Markus J. Luzius
*
* Version: 0.10.0-SNAPSHOT
* Build date: 2011-10-09
*
* 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
* 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 org.jskat.ai.nn.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
// FIXME (jansch 20.06.2011) re-implement it as JUnit-Test
/**
* Test class for NeuralNetwork
*/
public class NetworkTester {
private static Log log = LogFactory.getLog(NetworkTester.class);
/**
* @param args
*/
public static void main(String[] args) {
PropertyConfigurator.configure(ClassLoader
.getSystemResource("org/jskat/config/log4j.properties")); //$NON-NLS-1$
// testBooleanFunction();
testSkat();
}
private static void testSkat() {
List<Double> opponent1 = new ArrayList<Double>();
List<Double> opponent2 = new ArrayList<Double>();
List<Double> opponent3 = new ArrayList<Double>();
opponent1.add(0.5); // A --> first opponent
opponent1.add(0.5); // K
opponent1.add(0.5); // Q
opponent1.add(0.0); // J
opponent1.add(0.5); // T
opponent1.add(-1.0); // 9
opponent1.add(0.0); // 8
opponent1.add(0.0); // 7
opponent1.add(0.5); // A --> second opponent
opponent1.add(0.5); // K
opponent1.add(0.5); // Q
opponent1.add(0.0); // J
opponent1.add(0.5); // T
opponent1.add(0.0); // 9
opponent1.add(-1.0); // 8
opponent1.add(0.0); // 7
opponent1.add(0.0); // A --> me
opponent1.add(0.0); // K
opponent1.add(0.0); // Q
opponent1.add(0.5); // J
opponent1.add(0.0); // T
opponent1.add(0.0); // 9
opponent1.add(0.0); // 8
opponent1.add(-1.0); // 7
opponent2.add(0.5); // A --> first opponent
opponent2.add(0.5); // K
opponent2.add(0.5); // Q
opponent2.add(0.0); // J
opponent2.add(0.5); // T
opponent2.add(-1.0); // 9
opponent2.add(0.0); // 8
opponent2.add(0.0); // 7
opponent2.add(0.5); // A --> second opponent
opponent2.add(0.5); // K
opponent2.add(0.5); // Q
opponent2.add(0.0); // J
opponent2.add(0.5); // T
opponent2.add(0.0); // 9
opponent2.add(-1.0); // 8
opponent2.add(0.0); // 7
opponent2.add(0.0); // A --> me
opponent2.add(0.0); // K
opponent2.add(0.0); // Q
opponent2.add(-0.5); // J
opponent2.add(0.0); // T
opponent2.add(0.0); // 9
opponent2.add(0.0); // 8
opponent2.add(0.5); // 7
opponent3.add(0.5); // A --> first opponent
opponent3.add(0.5); // K
opponent3.add(0.5); // Q
opponent3.add(0.0); // J
opponent3.add(-0.5); // T
opponent3.add(-1.0); // 9
opponent3.add(0.0); // 8
opponent3.add(0.0); // 7
opponent3.add(0.5); // A --> second opponent
opponent3.add(0.5); // K
opponent3.add(0.5); // Q
opponent3.add(0.0); // J
opponent3.add(0.0); // T
opponent3.add(0.0); // 9
opponent3.add(-1.0); // 8
opponent3.add(0.0); // 7
opponent3.add(0.0); // A --> me
opponent3.add(0.0); // K
opponent3.add(0.0); // Q
opponent3.add(-1.0); // J
opponent3.add(0.0); // T
opponent3.add(0.0); // 9
opponent3.add(0.0); // 8
opponent3.add(0.5); // 7
double input[][] = new double[3][opponent1.size()];
for (int i = 0; i < opponent1.size(); i++) {
input[0][i] = opponent1.get(i);
input[1][i] = opponent2.get(i);
input[2][i] = opponent3.get(i);
}
double output[][] = { { 1.0 }, { -1.0 }, { 1.0 } };
int[] hiddenNeurons = { 2 };
NetworkTopology topo = new NetworkTopology(input[0].length,
output[0].length, 1, hiddenNeurons);
NeuralNetwork net = new NeuralNetwork(topo);
log.debug(net);
int goodGuess = 0;
int i = 0;
while (goodGuess < input.length) {
net.adjustWeights(input[i % input.length], output[i % input.length]);
if (Math.abs(net.getAvgDiff()) < 0.1) {
goodGuess++;
} else {
goodGuess = 0;
}
if (i % 1000 == 0) {
log.debug(i + " iterations " + goodGuess + " good guesses...");
}
i++;
}
log.debug("Learned pattern after " + i + " iterations.");
// log.debug(net);
//
for (i = 0; i < input.length; i++) {
double predOutput = net
.getPredictedOutcome(input[i % input.length]);
log.debug(input[i % input.length]);
log.debug(predOutput);
}
- net.saveNetwork("asdf.net");
+ net.saveNetwork(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "asdf.net"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
log.debug("Re-loading network");
NeuralNetwork net2 = new NeuralNetwork();
// net2.loadNetwork("asdf.net");
goodGuess = 0;
i = 0;
while (goodGuess < input.length) {
net.adjustWeights(input[i % input.length], output[i % input.length]);
if (Math.abs(net.getAvgDiff()) < 0.1) {
goodGuess++;
} else {
goodGuess = 0;
}
if (i % 1000 == 0) {
log.debug(i + " iterations " + goodGuess + " good guesses...");
}
i++;
}
log.debug("Learned pattern after " + i + " iterations.");
for (i = 0; i < input.length; i++) {
double predOutput = net.getPredictedOutcome(input[i]);
log.debug(input[i]);
log.debug(predOutput);
}
}
private static void testBooleanFunction() {
NeuralNetwork net = new NeuralNetwork();
log.debug(net);
// double[][] input = {{1.0, 1.0},
// {1.0, 0.0},
// {0.0, 1.0},
// {0.0, 0.0}};
// double[][] output = {{0.0},
// {1.0},
// {1.0},
// {0.0}};
double[][] input = { { 1.0, 1.0, 1.0 }, { 1.0, 1.0, 0.0 },
{ 1.0, 0.0, 1.0 }, { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 1.0 },
{ 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 }, { 0.0, 0.0, 0.0 } };
double[][] output = { { 1.0 }, // A and B or C
{ 1.0 }, { 1.0 }, { 0.0 }, { 1.0 }, { 0.0 }, { 1.0 }, { 0.0 } };
int goodGuess = 0;
for (int i = 0; i < 10000; i++) {
net.adjustWeights(input[i % input.length], output[i % input.length]);
if (net.getAvgDiff() < 0.1) {
goodGuess++;
} else {
goodGuess = 0;
}
if (goodGuess > input.length) {
log.debug("Learned pattern after " + i + " iterations.");
break;
}
}
// log.debug(net);
//
for (int i = 0; i < input.length; i++) {
double predOutput = net.getPredictedOutcome(input[i]);
log.debug(input[i]);
log.debug(predOutput);
}
}
}
| true | true | private static void testSkat() {
List<Double> opponent1 = new ArrayList<Double>();
List<Double> opponent2 = new ArrayList<Double>();
List<Double> opponent3 = new ArrayList<Double>();
opponent1.add(0.5); // A --> first opponent
opponent1.add(0.5); // K
opponent1.add(0.5); // Q
opponent1.add(0.0); // J
opponent1.add(0.5); // T
opponent1.add(-1.0); // 9
opponent1.add(0.0); // 8
opponent1.add(0.0); // 7
opponent1.add(0.5); // A --> second opponent
opponent1.add(0.5); // K
opponent1.add(0.5); // Q
opponent1.add(0.0); // J
opponent1.add(0.5); // T
opponent1.add(0.0); // 9
opponent1.add(-1.0); // 8
opponent1.add(0.0); // 7
opponent1.add(0.0); // A --> me
opponent1.add(0.0); // K
opponent1.add(0.0); // Q
opponent1.add(0.5); // J
opponent1.add(0.0); // T
opponent1.add(0.0); // 9
opponent1.add(0.0); // 8
opponent1.add(-1.0); // 7
opponent2.add(0.5); // A --> first opponent
opponent2.add(0.5); // K
opponent2.add(0.5); // Q
opponent2.add(0.0); // J
opponent2.add(0.5); // T
opponent2.add(-1.0); // 9
opponent2.add(0.0); // 8
opponent2.add(0.0); // 7
opponent2.add(0.5); // A --> second opponent
opponent2.add(0.5); // K
opponent2.add(0.5); // Q
opponent2.add(0.0); // J
opponent2.add(0.5); // T
opponent2.add(0.0); // 9
opponent2.add(-1.0); // 8
opponent2.add(0.0); // 7
opponent2.add(0.0); // A --> me
opponent2.add(0.0); // K
opponent2.add(0.0); // Q
opponent2.add(-0.5); // J
opponent2.add(0.0); // T
opponent2.add(0.0); // 9
opponent2.add(0.0); // 8
opponent2.add(0.5); // 7
opponent3.add(0.5); // A --> first opponent
opponent3.add(0.5); // K
opponent3.add(0.5); // Q
opponent3.add(0.0); // J
opponent3.add(-0.5); // T
opponent3.add(-1.0); // 9
opponent3.add(0.0); // 8
opponent3.add(0.0); // 7
opponent3.add(0.5); // A --> second opponent
opponent3.add(0.5); // K
opponent3.add(0.5); // Q
opponent3.add(0.0); // J
opponent3.add(0.0); // T
opponent3.add(0.0); // 9
opponent3.add(-1.0); // 8
opponent3.add(0.0); // 7
opponent3.add(0.0); // A --> me
opponent3.add(0.0); // K
opponent3.add(0.0); // Q
opponent3.add(-1.0); // J
opponent3.add(0.0); // T
opponent3.add(0.0); // 9
opponent3.add(0.0); // 8
opponent3.add(0.5); // 7
double input[][] = new double[3][opponent1.size()];
for (int i = 0; i < opponent1.size(); i++) {
input[0][i] = opponent1.get(i);
input[1][i] = opponent2.get(i);
input[2][i] = opponent3.get(i);
}
double output[][] = { { 1.0 }, { -1.0 }, { 1.0 } };
int[] hiddenNeurons = { 2 };
NetworkTopology topo = new NetworkTopology(input[0].length,
output[0].length, 1, hiddenNeurons);
NeuralNetwork net = new NeuralNetwork(topo);
log.debug(net);
int goodGuess = 0;
int i = 0;
while (goodGuess < input.length) {
net.adjustWeights(input[i % input.length], output[i % input.length]);
if (Math.abs(net.getAvgDiff()) < 0.1) {
goodGuess++;
} else {
goodGuess = 0;
}
if (i % 1000 == 0) {
log.debug(i + " iterations " + goodGuess + " good guesses...");
}
i++;
}
log.debug("Learned pattern after " + i + " iterations.");
// log.debug(net);
//
for (i = 0; i < input.length; i++) {
double predOutput = net
.getPredictedOutcome(input[i % input.length]);
log.debug(input[i % input.length]);
log.debug(predOutput);
}
net.saveNetwork("asdf.net");
log.debug("Re-loading network");
NeuralNetwork net2 = new NeuralNetwork();
// net2.loadNetwork("asdf.net");
goodGuess = 0;
i = 0;
while (goodGuess < input.length) {
net.adjustWeights(input[i % input.length], output[i % input.length]);
if (Math.abs(net.getAvgDiff()) < 0.1) {
goodGuess++;
} else {
goodGuess = 0;
}
if (i % 1000 == 0) {
log.debug(i + " iterations " + goodGuess + " good guesses...");
}
i++;
}
log.debug("Learned pattern after " + i + " iterations.");
for (i = 0; i < input.length; i++) {
double predOutput = net.getPredictedOutcome(input[i]);
log.debug(input[i]);
log.debug(predOutput);
}
}
| private static void testSkat() {
List<Double> opponent1 = new ArrayList<Double>();
List<Double> opponent2 = new ArrayList<Double>();
List<Double> opponent3 = new ArrayList<Double>();
opponent1.add(0.5); // A --> first opponent
opponent1.add(0.5); // K
opponent1.add(0.5); // Q
opponent1.add(0.0); // J
opponent1.add(0.5); // T
opponent1.add(-1.0); // 9
opponent1.add(0.0); // 8
opponent1.add(0.0); // 7
opponent1.add(0.5); // A --> second opponent
opponent1.add(0.5); // K
opponent1.add(0.5); // Q
opponent1.add(0.0); // J
opponent1.add(0.5); // T
opponent1.add(0.0); // 9
opponent1.add(-1.0); // 8
opponent1.add(0.0); // 7
opponent1.add(0.0); // A --> me
opponent1.add(0.0); // K
opponent1.add(0.0); // Q
opponent1.add(0.5); // J
opponent1.add(0.0); // T
opponent1.add(0.0); // 9
opponent1.add(0.0); // 8
opponent1.add(-1.0); // 7
opponent2.add(0.5); // A --> first opponent
opponent2.add(0.5); // K
opponent2.add(0.5); // Q
opponent2.add(0.0); // J
opponent2.add(0.5); // T
opponent2.add(-1.0); // 9
opponent2.add(0.0); // 8
opponent2.add(0.0); // 7
opponent2.add(0.5); // A --> second opponent
opponent2.add(0.5); // K
opponent2.add(0.5); // Q
opponent2.add(0.0); // J
opponent2.add(0.5); // T
opponent2.add(0.0); // 9
opponent2.add(-1.0); // 8
opponent2.add(0.0); // 7
opponent2.add(0.0); // A --> me
opponent2.add(0.0); // K
opponent2.add(0.0); // Q
opponent2.add(-0.5); // J
opponent2.add(0.0); // T
opponent2.add(0.0); // 9
opponent2.add(0.0); // 8
opponent2.add(0.5); // 7
opponent3.add(0.5); // A --> first opponent
opponent3.add(0.5); // K
opponent3.add(0.5); // Q
opponent3.add(0.0); // J
opponent3.add(-0.5); // T
opponent3.add(-1.0); // 9
opponent3.add(0.0); // 8
opponent3.add(0.0); // 7
opponent3.add(0.5); // A --> second opponent
opponent3.add(0.5); // K
opponent3.add(0.5); // Q
opponent3.add(0.0); // J
opponent3.add(0.0); // T
opponent3.add(0.0); // 9
opponent3.add(-1.0); // 8
opponent3.add(0.0); // 7
opponent3.add(0.0); // A --> me
opponent3.add(0.0); // K
opponent3.add(0.0); // Q
opponent3.add(-1.0); // J
opponent3.add(0.0); // T
opponent3.add(0.0); // 9
opponent3.add(0.0); // 8
opponent3.add(0.5); // 7
double input[][] = new double[3][opponent1.size()];
for (int i = 0; i < opponent1.size(); i++) {
input[0][i] = opponent1.get(i);
input[1][i] = opponent2.get(i);
input[2][i] = opponent3.get(i);
}
double output[][] = { { 1.0 }, { -1.0 }, { 1.0 } };
int[] hiddenNeurons = { 2 };
NetworkTopology topo = new NetworkTopology(input[0].length,
output[0].length, 1, hiddenNeurons);
NeuralNetwork net = new NeuralNetwork(topo);
log.debug(net);
int goodGuess = 0;
int i = 0;
while (goodGuess < input.length) {
net.adjustWeights(input[i % input.length], output[i % input.length]);
if (Math.abs(net.getAvgDiff()) < 0.1) {
goodGuess++;
} else {
goodGuess = 0;
}
if (i % 1000 == 0) {
log.debug(i + " iterations " + goodGuess + " good guesses...");
}
i++;
}
log.debug("Learned pattern after " + i + " iterations.");
// log.debug(net);
//
for (i = 0; i < input.length; i++) {
double predOutput = net
.getPredictedOutcome(input[i % input.length]);
log.debug(input[i % input.length]);
log.debug(predOutput);
}
net.saveNetwork(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "asdf.net"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
log.debug("Re-loading network");
NeuralNetwork net2 = new NeuralNetwork();
// net2.loadNetwork("asdf.net");
goodGuess = 0;
i = 0;
while (goodGuess < input.length) {
net.adjustWeights(input[i % input.length], output[i % input.length]);
if (Math.abs(net.getAvgDiff()) < 0.1) {
goodGuess++;
} else {
goodGuess = 0;
}
if (i % 1000 == 0) {
log.debug(i + " iterations " + goodGuess + " good guesses...");
}
i++;
}
log.debug("Learned pattern after " + i + " iterations.");
for (i = 0; i < input.length; i++) {
double predOutput = net.getPredictedOutcome(input[i]);
log.debug(input[i]);
log.debug(predOutput);
}
}
|
diff --git a/code/src/com/kpro/main/Gio.java b/code/src/com/kpro/main/Gio.java
index d4bc08f..9215dae 100644
--- a/code/src/com/kpro/main/Gio.java
+++ b/code/src/com/kpro/main/Gio.java
@@ -1,638 +1,638 @@
package com.kpro.main;
import java.io.File; //for configuration file functionality
import java.io.FileInputStream; //for configuration file functionality and reading serialized objects
import java.io.FileOutputStream; //for writing the new weights config file
import java.io.IOException; //for configuration file functionality
import java.io.InputStream; //for configuration file functionality
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Properties; //for configuration file functionality
import java.util.logging.*; //for logger functionality
import org.apache.commons.cli.*; //for command line options
import com.kpro.algorithm.CBR;
import com.kpro.parser.P3PParser;
import com.kpro.dataobjects.*;
import com.kpro.datastorage.*;
import com.kpro.ui.*;
/* to load a new database from a folder, but not use cbr on a new object. overwrites old db (-n option)
* ./PrivacyAdvisor -b -f -n ./new_policy_history [-c config_file_location][-w weight_config_file_loc][-d db_file_location]
* to compare policy stored in p.txt, assuming config in default location is valid and used
* ./PrivacyAdvisor -T p.txt
*/
/* Thinking:
*
* user init > commandline > config file
*
* so assume config at general location (load with loadgen(defaultloc))
* check to see if commandline config (load with loadgen(newloc))
* handle other commandline options
* handle userinit
*
*/
public class Gio {
private static Logger logger = Logger.getLogger(""); /**create logger object*/
private FileHandler fh = null; /**creates filehandler for logging*/
private Properties genProps = new Properties(); /**holds all the property values*/
private Properties origWeights = null; /**the loaded weights file.*/
private Properties newWeights = null; /**the revised weights, following LearnAlgorithm.
written to disk by shutdown().
also used in loading weights during init()*/
private UserIO userInterface = null; /**means of interacting with the user*/
private PolicyDatabase pdb; /**Policy database object*/
private NetworkR nr; /** Network Resource (community advice database)*/
/**
* Constructor fo gio class. There should only be one. Consider this a singleton instance to call I/O messages on.
* Constructs and parses command line arguements as well.
*
* @throws Exception Mostly from loadWeights, but should also happen for loadFromConfig
*/
public Gio(String[] args) throws Exception
{
this(args,null);
}
/**
* A constructor permitting a user interface class to launch everything and be in control.
*
* @param args any commandline arguements
* @param ui the known UserIO object
* @throws Exception Mostly from loadWeights, but should also happen for loadFromConfig
*/
public Gio(String[] args, UserIO ui) throws Exception
{
userInterface = ui;
genProps = loadFromConfig("./PrivacyAdviser.cfg");
loadCLO(args);
//TODO add method to check validity of genProps (after each file load, clo load, and ui load).
if((genProps.getProperty("genConfig")!=null) &&(genProps.getProperty("genConfig")!="./PrivacyAdvisor.cfg"))
{
System.err.println("clo config call");
genProps = loadFromConfig(genProps.getProperty("genConfig")); //TODO merge, not override
loadCLO(args);
}
//start the logger
logger = startLogger(genProps.getProperty("loglocation","./LOG.txt"),genProps.getProperty("loglevel","INFO"));
if(userInterface ==null)
{
selectUI(genProps.getProperty("UserIO"));
}
if(Boolean.parseBoolean(genProps.getProperty("userInit","false")) && !(userInterface==null))
{
genProps = userInterface.user_init(genProps);
}
selectPDB(genProps.getProperty("policyDB"));
//load the weights configuration file
origWeights = new Properties();
origWeights = loadWeights();
if(Boolean.parseBoolean(genProps.getProperty("useNet","false")))
{
startNetwork();
}
else
{
nr = null;
}
}
/**
* accepts the direct commandline options, then parses & implements them.
*
* @param args
*/
//TODO add exception for invalid options
private void loadCLO(String[] args)
{
Options options = new Options();
String[][] clolist=
{
//{"variable/optionname", "description"},
{"genConfig","general configuration file location"},
{"inWeightsLoc", "input weights configuration file location"},
{"inDBLoc", "input database file location"},
{"outWeightsLoc", "output weights configuration file location"},
{"outDBLoc", "output database file location"},
- {"P3PLocation", "adding to DB: single policy file location"},
- {"P3PDirLocation", "adding to DB: multiple policy directory location"},
+ {"p3pLocation", "adding to DB: single policy file location"},
+ {"p3pDirLocation", "adding to DB: multiple policy directory location"},
{"newDB", "create new database in place of old one (doesn't check for existence of old one"},
{"newPolicyLoc", "the policy object to process"},
{"userResponse","response to specified policy"},
{"userIO","user interface"},
{"userInit","initialization via user interface"},
{"policyDB","PolicyDatabase backend"},
{"cbrV","CBR to use"},
{"blanketAccept","automatically accept the user suggestion"},
{"loglevel","level of things save to the log- see java logging details"},
{"policyDB","PolicyDatabase backend"},
{"networkRType","Network Resource type"},
{"networkROptions","Network Resource options"},
{"confidenceLevel","Confidence threshold for consulting a networked resource"},
{"useNet","use networking options"},
{"loglocation","where to save the log file"},
{"loglevel","the java logging level to use. See online documentation for enums."}
};
for(String[] i : clolist)
{
options.addOption(i[0],true,i[1]);
}
CommandLineParser parser = new PosixParser();
CommandLine cmd = null;
try
{
cmd = parser.parse( options, args);
}
catch (ParseException e)
{
- System.err.println("Error parsing commandline arguements.");
+ System.err.println("Error parsing commandline arguments.");
e.printStackTrace();
System.exit(3);
}
// for(String i : args)
// {
// System.err.println(i);
// }
for(String[] i : clolist)
{
if(cmd.hasOption(i[0]))
{
// System.err.println("found option i: "+i);
genProps.setProperty(i[0],cmd.getOptionValue(i[0]));
}
}
// System.err.println(genProps);
}
/**
* converts a string into a valid CBR
*
* @param string the string to parse
* @return the CBR to use
* @throws Exception
*/
private CBR parseCBR(String string) throws Exception {
try {
return (string == null)?(null):(new CBR(this)).parse(string);
} catch (Exception e) {
System.err.println("error parsing CBR, exiting.");
e.printStackTrace();
System.exit(5);
return null;
}
}
/**
* Should parse a string to select, initialize, and return one of the policy databases coded
*
* @param optionValue the string to parse
* @return the policy database being used
*/
private void selectPDB(String optionValue) {
// TODO Add other PolicyDatabase classes, when other classes are made
pdb = PDatabase.getInstance(genProps.getProperty("inDBLoc"), genProps.getProperty("outDBLoc",genProps.getProperty("inDBLoc")));
if(pdb==null)
{
System.err.println("pdb null in selectPDB");
}
}
/**
* Should parse a string to select, initialize, and return the user interface selected
*
* @param optionValue the string to parse
* @return the user interface to use
*/
private void selectUI(String optionValue) {
// TODO Add other UserIO classes, when other classes are made
userInterface = new UserIO_Simple();
}
/**
* Should parse a string to select, initialize, and return one of the actions (result of checking an object) coded.
*
* @param optionValue the string to parse
* @return the action to apply to the new policy
*/
private Action parseAct(String optionValue) {
// TODO remove this later
return (optionValue == null)?(null):(new Action().parse(optionValue));
}
/**
* Loads the general configuration file, either from provided string, or default location (./PrivacyAdviser.cfg)
*
* @param location of configuration file
* @return properties object corresponding to given configuration file
*/
//TODO add exception for invalid options
public Properties loadFromConfig(String fileLoc)
{
Properties configFile = new Properties();
try {
File localConfig = new File(fileLoc);
InputStream is = null;
if(localConfig.exists())
{
is = new FileInputStream(localConfig);
}
else
{
System.err.println("No configuration file at "+fileLoc+ ". Please place one in the working directory.");
System.exit(3);
}
configFile.load(is);
}
catch (IOException e)
{
e.printStackTrace();
System.err.println("IOException reading first configuration file. Exiting...\n");
System.exit(1);
}
return configFile;
}
/**
* Loads the weights configuration file, from the provided location
*
* @param location of configuration file <---- ????
* @return properties object corresponding to given configuration file
* @throws Exception if there's an issue reading the file (if it doesn't exist, or has an IO error)
*/
public Properties loadWeights() throws Exception
{
try
{
if(genProps.getProperty("inWeightsLoc") == null)
{
System.err.println("inWeightsLoc in Gio/LoadWeights is null");
}
File localConfig = new File(genProps.getProperty("inWeightsLoc"));
// System.out.println(genProps.getProperty("inWeightsLoc"));
InputStream is = null;
if(localConfig.exists())
{
is = new FileInputStream(localConfig);
}
else
{
System.err.println("No weights file is available at "+genProps.getProperty("inWeightsLoc")+
" . Please place one in the working directory.");
throw new Exception("In class Gio.java:loadWeights(), file "+genProps.getProperty("inWeightsLoc")+" doesn't exist.");
}
origWeights = new Properties();
origWeights.load(is);
}
catch (IOException e)
{
e.printStackTrace();
System.err.println("IOException reading the weights configuration file....\n");
throw new Exception("In class Gio.java:loadWeights(), IOException loading the weights from file "+genProps.getProperty("inWeightsLoc")+" .");
}
return origWeights;
}
/**
* startLogger initializes and returns a file at logLoc with the results of logging at level logLevel.
*
* @param logLoc location of the output log file- a string
* @param logLevel logging level (is parsed by level.parse())
* @return Logger object to log to.
*/
public Logger startLogger(String logLoc, String logLevel)
{
try
{
fh = new FileHandler(logLoc); //sets output log file at logLoc
}
catch (SecurityException e)
{
e.printStackTrace();
System.err.println("SecurityException establishing logger. Exiting...\n");
System.exit(1);
}
catch (IOException e)
{
e.printStackTrace();
System.err.println("IOException establishing logger. Exiting...\n");
System.exit(1);
}
fh.setFormatter(new SimpleFormatter()); //format of log is 'human-readable' simpleformat
logger.addHandler(fh); //attach formatter to logger
logger.setLevel(Level.parse(logLevel)); //set log level
return logger;
}
/**
* Loads the case history into cache.
* This is where the background database chosen.
*
* @param dLoc the location of the database
*
*/
public void loadDB()
{
if(!Boolean.parseBoolean(genProps.getProperty("newDB")))
{
pdb.loadDB();
}
loadCLPolicies();
}
/**
* loads [additional] policies from commandline (either -p or -f)
*
*/
private void loadCLPolicies() {
//we already checked to make sure we have one of the options avaliable
File pLoc = null;
PolicyObject p = null;
if(genProps.getProperty("p3pLocation",null) != null)
{
pLoc = new File(genProps.getProperty("p3pLocation"));
if(!pLoc.exists()){
System.err.println("no file found at p3p policy location specified by the -p3p option: "+
genProps.getProperty("p3pLocation"));
System.err.println("current location is "+System.getProperty("user.dir"));
System.exit(1);
}
try
{
p = (new P3PParser()).parse(pLoc.getAbsolutePath());
if(p.getContext().getDomain()==null)
{
if(p.getContext().getDomain()==null)
{
p.setContext(new Context(new Date(System.currentTimeMillis()),new Date(System.currentTimeMillis()),genProps.getProperty("p3pLocation")));
}
pdb.addPolicy(p);
}
}
catch(Exception e)
{
System.err.println("Einar needs to fix a parsing error.");
e.printStackTrace();
//System.exit(5);
}
}
if(genProps.getProperty("p3pDirLocation",null) != null)
{
pLoc = new File(genProps.getProperty("p3pDirLocation"));
File[] pfiles = pLoc.listFiles();
//System.err.println("pfiles for p3pDirLocation: "+pfiles);
for(int i=0;i<pfiles.length;i++)
{
pLoc = (pfiles[i]);
if(!pLoc.exists()){
System.err.println("no file found at p3p policy location specified by the -p3pDirLocation option, "+
genProps.getProperty("p3pDirLocation"));
System.exit(1);
}
try
{
p = (new P3PParser()).parse(pLoc.getAbsolutePath());
if(p.getContext().getDomain()==null)
{
p.setContext(new Context(new Date(System.currentTimeMillis()),new Date(System.currentTimeMillis()),pfiles[i].getAbsolutePath()));
}
pdb.addPolicy(p);
}
catch(Exception e)
{
System.err.println("Einar needs to fix this parsing error.");
e.printStackTrace();
}
}
}
}
/**
* returns the only policy database
*
* @return the policy database
*/
public PolicyDatabase getPDB()
{
return pdb;
}
/**
* closes resources and write everything to file
*
*/
public void shutdown() {
pdb.closeDB(); //save the db
if(newWeights == null)
{
newWeights = origWeights;
}
writePropertyFile(newWeights,genProps.getProperty("outWeightsLoc",genProps.getProperty("inWeightsLoc")));
userInterface.closeResources();
System.out.println("preferences saved and closed without error.");
}
/**
* writes a property file to disk
*
* @param wprops the property file to write
* @param wloc where to write to
*/
private void writePropertyFile(Properties wprops, String wloc)
{
if(wprops==null)
System.out.println("wrops null in gio/writepropertyfile");
if(wloc ==null)
System.out.println("wloc null in gio/writepropertyfile");
try
{
wprops.store(new FileOutputStream(wloc), null);
}
catch (IOException e)
{
System.err.println("Error writing weights to file.");
e.printStackTrace();
System.exit(3);
}
}
/**
* Generates handles response. This is were we would pass stuff to cli or gui, etc
*
* @param n the processed policy object
* @return the policyObjected as accepted by user (potentially modified
*/
public PolicyObject userResponse(PolicyObject n) {
if((parseAct(genProps.getProperty("userResponse",null)) == null) &&
!Boolean.parseBoolean(genProps.getProperty("blanketAccept")))
{
return userInterface.userResponse(n);
}
else
{
if(Boolean.parseBoolean(genProps.getProperty("blanketAccept")))
{
return n.setAction(n.getAction().setOverride(true));
}
else
{
return n.setAction(parseAct(genProps.getProperty("userResponse",null)));
}
}
}
/**
* returns the policy object from the policyObject option
*
* @return the policy object to be processed
*/
public PolicyObject getPO() {
PolicyObject p = null;
if(genProps.getProperty("newPolicyLoc",null) == null)
System.err.println("newPolLoc == null in gio:getPO");
File pLoc = new File(genProps.getProperty("newPolicyLoc",null));
if(!pLoc.exists()){
System.err.println("no file found at p3p policy location specified by the new policy option");
System.exit(1);
}
p = (new P3PParser()).parse(pLoc.getAbsolutePath());
//TODO make sure that the context is parsed if avaliable
if(p.getContext().getDomain()==null)
{
p.setContext(new Context(new Date(System.currentTimeMillis()),new Date(System.currentTimeMillis()),genProps.getProperty("newPolicyLoc")));
}
return p;
}
/**
* returns the -b option if present- whether or not to solely build a database, or build and call CBR.run()
*
* @return true if a CBR should NOT be run
*/
public boolean isBuilding() {
return (genProps.getProperty("newPolicyLoc",null)==null);
}
/**
* saves the new weights to a buffer variable before writing in the shutdown call
*
* @param newWeightP the new weights file to save
*/
public void setWeights(Properties newWeightP) {
newWeights = newWeightP;
}
/**
* returns the CBR to use
*
* @return the cbr to use
* @throws Exception
*/
public CBR getCBR() throws Exception {
return parseCBR(genProps.getProperty("cbrV",null));
}
public Properties getWeights() {
return origWeights;
}
public void showDatabase() {
userInterface.showDatabase(pdb);
}
/**
* GUI classes should use this to ensure the user passes valid files to load.
*
* @param filepath path of the file to check
* @return true if the file exists, else false
*/
public boolean fileExists(String filepath)
{
return (new File(filepath)).exists();
}
/**
* Starts the NetworkR specificied by the configuration settings.
*
* @throws ClassNotFoundException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws SecurityException
* @throws IllegalArgumentException
*/
private void startNetwork() throws ClassNotFoundException, IllegalArgumentException, SecurityException, InstantiationException, IllegalAccessException, InvocationTargetException {
//System.err.println("startnetwork called");
Class<?> cls = Class.forName("com.kpro.datastorage."+genProps.getProperty("NetworkRType"));
if(cls == null)
{
System.err.println("NetworkRType incorrect- null in Gio.startNetwork()");
}
nr = (NetworkR) cls.getDeclaredConstructors()[0].newInstance(genProps.getProperty("NetworkROptions"));
//System.err.println("nr in startNetwork="+nr);
}
public NetworkR getNR()
{
return nr;
}
public double getConfLevel() {
return Double.parseDouble(genProps.getProperty("confidenceLevel","1.0"));
}
}
| false | true | private void loadCLO(String[] args)
{
Options options = new Options();
String[][] clolist=
{
//{"variable/optionname", "description"},
{"genConfig","general configuration file location"},
{"inWeightsLoc", "input weights configuration file location"},
{"inDBLoc", "input database file location"},
{"outWeightsLoc", "output weights configuration file location"},
{"outDBLoc", "output database file location"},
{"P3PLocation", "adding to DB: single policy file location"},
{"P3PDirLocation", "adding to DB: multiple policy directory location"},
{"newDB", "create new database in place of old one (doesn't check for existence of old one"},
{"newPolicyLoc", "the policy object to process"},
{"userResponse","response to specified policy"},
{"userIO","user interface"},
{"userInit","initialization via user interface"},
{"policyDB","PolicyDatabase backend"},
{"cbrV","CBR to use"},
{"blanketAccept","automatically accept the user suggestion"},
{"loglevel","level of things save to the log- see java logging details"},
{"policyDB","PolicyDatabase backend"},
{"networkRType","Network Resource type"},
{"networkROptions","Network Resource options"},
{"confidenceLevel","Confidence threshold for consulting a networked resource"},
{"useNet","use networking options"},
{"loglocation","where to save the log file"},
{"loglevel","the java logging level to use. See online documentation for enums."}
};
for(String[] i : clolist)
{
options.addOption(i[0],true,i[1]);
}
CommandLineParser parser = new PosixParser();
CommandLine cmd = null;
try
{
cmd = parser.parse( options, args);
}
catch (ParseException e)
{
System.err.println("Error parsing commandline arguements.");
e.printStackTrace();
System.exit(3);
}
// for(String i : args)
// {
// System.err.println(i);
// }
for(String[] i : clolist)
{
if(cmd.hasOption(i[0]))
{
// System.err.println("found option i: "+i);
genProps.setProperty(i[0],cmd.getOptionValue(i[0]));
}
}
// System.err.println(genProps);
}
| private void loadCLO(String[] args)
{
Options options = new Options();
String[][] clolist=
{
//{"variable/optionname", "description"},
{"genConfig","general configuration file location"},
{"inWeightsLoc", "input weights configuration file location"},
{"inDBLoc", "input database file location"},
{"outWeightsLoc", "output weights configuration file location"},
{"outDBLoc", "output database file location"},
{"p3pLocation", "adding to DB: single policy file location"},
{"p3pDirLocation", "adding to DB: multiple policy directory location"},
{"newDB", "create new database in place of old one (doesn't check for existence of old one"},
{"newPolicyLoc", "the policy object to process"},
{"userResponse","response to specified policy"},
{"userIO","user interface"},
{"userInit","initialization via user interface"},
{"policyDB","PolicyDatabase backend"},
{"cbrV","CBR to use"},
{"blanketAccept","automatically accept the user suggestion"},
{"loglevel","level of things save to the log- see java logging details"},
{"policyDB","PolicyDatabase backend"},
{"networkRType","Network Resource type"},
{"networkROptions","Network Resource options"},
{"confidenceLevel","Confidence threshold for consulting a networked resource"},
{"useNet","use networking options"},
{"loglocation","where to save the log file"},
{"loglevel","the java logging level to use. See online documentation for enums."}
};
for(String[] i : clolist)
{
options.addOption(i[0],true,i[1]);
}
CommandLineParser parser = new PosixParser();
CommandLine cmd = null;
try
{
cmd = parser.parse( options, args);
}
catch (ParseException e)
{
System.err.println("Error parsing commandline arguments.");
e.printStackTrace();
System.exit(3);
}
// for(String i : args)
// {
// System.err.println(i);
// }
for(String[] i : clolist)
{
if(cmd.hasOption(i[0]))
{
// System.err.println("found option i: "+i);
genProps.setProperty(i[0],cmd.getOptionValue(i[0]));
}
}
// System.err.println(genProps);
}
|
diff --git a/services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/nuxeo/AcquisitionDocumentModelHandler.java b/services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/nuxeo/AcquisitionDocumentModelHandler.java
index a643066c0..ce32851fc 100644
--- a/services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/nuxeo/AcquisitionDocumentModelHandler.java
+++ b/services/acquisition/service/src/main/java/org/collectionspace/services/acquisition/nuxeo/AcquisitionDocumentModelHandler.java
@@ -1,194 +1,194 @@
/**
* This document is a part of the source code and related artifacts
* for CollectionSpace, an open source collections management system
* for museums and related institutions:
* http://www.collectionspace.org
* http://wiki.collectionspace.org
* Copyright 2009 University of California at Berkeley
* Licensed under the Educational Community License (ECL), Version 2.0.
* You may not use this file except in compliance with this License.
* You may obtain a copy of the ECL 2.0 License at
* https://source.collectionspace.org/collection-space/LICENSE.txt
* 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.collectionspace.services.acquisition.nuxeo;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.collectionspace.services.AcquisitionListItemJAXBSchema;
import org.collectionspace.services.common.document.DocumentWrapper;
import org.collectionspace.services.acquisition.AcquisitionsCommon;
import org.collectionspace.services.acquisition.AcquisitionsCommonList;
import org.collectionspace.services.acquisition.AcquisitionsCommonList.AcquisitionListItem;
import org.collectionspace.services.acquisition.AcquisitionSourceList;
import org.collectionspace.services.acquisition.OwnerList;
import org.collectionspace.services.common.document.DocumentHandler.Action;
import org.collectionspace.services.jaxb.AbstractCommonList;
import org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl;
import org.collectionspace.services.nuxeo.util.NuxeoUtils;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* AcquisitionDocumentModelHandler
*
* $LastChangedRevision: $
* $LastChangedDate: $
*/
public class AcquisitionDocumentModelHandler
extends RemoteDocumentModelHandlerImpl<AcquisitionsCommon, AcquisitionsCommonList> {
private final Logger logger = LoggerFactory.getLogger(AcquisitionDocumentModelHandler.class);
/**
* acquisition is used to stash JAXB object to use when handle is called
* for Action.CREATE, Action.UPDATE or Action.GET
*/
private AcquisitionsCommon acquisition;
/**
* acquisitionList is stashed when handle is called
* for ACTION.GET_ALL
*/
private AcquisitionsCommonList acquisitionList;
/**
* getCommonPart get associated acquisition
* @return
*/
@Override
public AcquisitionsCommon getCommonPart() {
return acquisition;
}
/**
* setCommonPart set associated acquisition
* @param acquisition
*/
@Override
public void setCommonPart(AcquisitionsCommon acquisition) {
this.acquisition = acquisition;
}
/**
* getAcquisitionList get associated acquisition (for index/GET_ALL)
* @return
*/
@Override
public AcquisitionsCommonList getCommonPartList() {
return acquisitionList;
}
@Override
public void setCommonPartList(AcquisitionsCommonList acquisitionList) {
this.acquisitionList = acquisitionList;
}
@Override
public AcquisitionsCommon extractCommonPart(DocumentWrapper<DocumentModel> wrapDoc)
throws Exception {
throw new UnsupportedOperationException();
}
@Override
public void fillCommonPart(AcquisitionsCommon acquisitionObject, DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
throw new UnsupportedOperationException();
}
@Override
public AcquisitionsCommonList extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
AcquisitionsCommonList coList = this.extractPagingInfo(new AcquisitionsCommonList(), wrapDoc);
AbstractCommonList commonList = (AbstractCommonList) coList;
commonList.setFieldsReturned("acquisitionReferenceNumber|acquisitionSources|owners|uri|csid");
List<AcquisitionsCommonList.AcquisitionListItem> list = coList.getAcquisitionListItem();
Iterator<DocumentModel> iter = wrapDoc.getWrappedObject().iterator();
String label = getServiceContext().getCommonPartLabel();
while (iter.hasNext()) {
DocumentModel docModel = iter.next();
AcquisitionListItem listItem = new AcquisitionListItem();
listItem.setAcquisitionReferenceNumber((String) docModel.getProperty(label,
AcquisitionListItemJAXBSchema.ACQUISITION_REFERENCE_NUMBER));
// docModel.getProperty returns an ArrayList here.
List<String> acquisitionSources =
(List<String>) docModel.getProperty(label,
AcquisitionListItemJAXBSchema.ACQUISITION_SOURCES);
AcquisitionSourceList acquisitionSourceList = new AcquisitionSourceList();
for (String acquisitionSource : acquisitionSources) {
acquisitionSourceList.getAcquisitionSource().add(acquisitionSource);
}
listItem.setAcquisitionSources(acquisitionSourceList);
// and here ...
List<String> owners =
(List<String>) docModel.getProperty(label,
AcquisitionListItemJAXBSchema.OWNERS);
OwnerList ownerList = new OwnerList();
for (String owner : owners) {
- acquisitionSourceList.getAcquisitionSource().add(owner);
+ ownerList.getOwner().add(owner);
}
listItem.setOwners(ownerList);
//need fully qualified context for URI
String id = NuxeoUtils.extractId(docModel.getPathAsString());
listItem.setUri(getServiceContextPath() + id);
listItem.setCsid(id);
list.add(listItem);
}
return coList;
}
@Override
public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
super.fillAllParts(wrapDoc, action);
fillDublinCoreObject(wrapDoc); //dublincore might not be needed in future
}
private void fillDublinCoreObject(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
DocumentModel docModel = wrapDoc.getWrappedObject();
//FIXME property setter should be dynamically set using schema inspection
//so it does not require hard coding
// a default title for the Dublin Core schema
docModel.setPropertyValue("dublincore:title", AcquisitionConstants.NUXEO_DC_TITLE);
}
/**
* getQProperty converts the given property to qualified schema property
* @param prop
* @return
*/
@Override
public String getQProperty(String prop) {
return AcquisitionConstants.NUXEO_SCHEMA_NAME + ":" + prop;
}
// The following are all private in DocumentUtils;
// might be moved to a common class.
private static String NAME_VALUE_SEPARATOR = "|";
private static class NameValue {
NameValue() {
// default scoped constructor to remove "synthetic accessor" warning
}
String name;
String value;
};
}
| true | true | public AcquisitionsCommonList extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
AcquisitionsCommonList coList = this.extractPagingInfo(new AcquisitionsCommonList(), wrapDoc);
AbstractCommonList commonList = (AbstractCommonList) coList;
commonList.setFieldsReturned("acquisitionReferenceNumber|acquisitionSources|owners|uri|csid");
List<AcquisitionsCommonList.AcquisitionListItem> list = coList.getAcquisitionListItem();
Iterator<DocumentModel> iter = wrapDoc.getWrappedObject().iterator();
String label = getServiceContext().getCommonPartLabel();
while (iter.hasNext()) {
DocumentModel docModel = iter.next();
AcquisitionListItem listItem = new AcquisitionListItem();
listItem.setAcquisitionReferenceNumber((String) docModel.getProperty(label,
AcquisitionListItemJAXBSchema.ACQUISITION_REFERENCE_NUMBER));
// docModel.getProperty returns an ArrayList here.
List<String> acquisitionSources =
(List<String>) docModel.getProperty(label,
AcquisitionListItemJAXBSchema.ACQUISITION_SOURCES);
AcquisitionSourceList acquisitionSourceList = new AcquisitionSourceList();
for (String acquisitionSource : acquisitionSources) {
acquisitionSourceList.getAcquisitionSource().add(acquisitionSource);
}
listItem.setAcquisitionSources(acquisitionSourceList);
// and here ...
List<String> owners =
(List<String>) docModel.getProperty(label,
AcquisitionListItemJAXBSchema.OWNERS);
OwnerList ownerList = new OwnerList();
for (String owner : owners) {
acquisitionSourceList.getAcquisitionSource().add(owner);
}
listItem.setOwners(ownerList);
//need fully qualified context for URI
String id = NuxeoUtils.extractId(docModel.getPathAsString());
listItem.setUri(getServiceContextPath() + id);
listItem.setCsid(id);
list.add(listItem);
}
return coList;
}
| public AcquisitionsCommonList extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
AcquisitionsCommonList coList = this.extractPagingInfo(new AcquisitionsCommonList(), wrapDoc);
AbstractCommonList commonList = (AbstractCommonList) coList;
commonList.setFieldsReturned("acquisitionReferenceNumber|acquisitionSources|owners|uri|csid");
List<AcquisitionsCommonList.AcquisitionListItem> list = coList.getAcquisitionListItem();
Iterator<DocumentModel> iter = wrapDoc.getWrappedObject().iterator();
String label = getServiceContext().getCommonPartLabel();
while (iter.hasNext()) {
DocumentModel docModel = iter.next();
AcquisitionListItem listItem = new AcquisitionListItem();
listItem.setAcquisitionReferenceNumber((String) docModel.getProperty(label,
AcquisitionListItemJAXBSchema.ACQUISITION_REFERENCE_NUMBER));
// docModel.getProperty returns an ArrayList here.
List<String> acquisitionSources =
(List<String>) docModel.getProperty(label,
AcquisitionListItemJAXBSchema.ACQUISITION_SOURCES);
AcquisitionSourceList acquisitionSourceList = new AcquisitionSourceList();
for (String acquisitionSource : acquisitionSources) {
acquisitionSourceList.getAcquisitionSource().add(acquisitionSource);
}
listItem.setAcquisitionSources(acquisitionSourceList);
// and here ...
List<String> owners =
(List<String>) docModel.getProperty(label,
AcquisitionListItemJAXBSchema.OWNERS);
OwnerList ownerList = new OwnerList();
for (String owner : owners) {
ownerList.getOwner().add(owner);
}
listItem.setOwners(ownerList);
//need fully qualified context for URI
String id = NuxeoUtils.extractId(docModel.getPathAsString());
listItem.setUri(getServiceContextPath() + id);
listItem.setCsid(id);
list.add(listItem);
}
return coList;
}
|
diff --git a/srcj/com/sun/electric/tool/user/MenuCommands.java b/srcj/com/sun/electric/tool/user/MenuCommands.java
index 52126d88b..f8da16f99 100755
--- a/srcj/com/sun/electric/tool/user/MenuCommands.java
+++ b/srcj/com/sun/electric/tool/user/MenuCommands.java
@@ -1,4673 +1,4673 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: MenuCommands.java
*
* Copyright (c) 2003 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user;
import com.sun.electric.database.change.Undo;
import com.sun.electric.database.geometry.Geometric;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.geometry.EMath;
import com.sun.electric.database.geometry.PolyMerge;
import com.sun.electric.database.geometry.PolyQTree;
import com.sun.electric.database.hierarchy.*;
import com.sun.electric.database.network.JNetwork;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.ArcProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.topology.Connection;
import com.sun.electric.database.variable.ElectricObject;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.EvalJavaBsh;
import com.sun.electric.database.variable.FlagSet;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.technology.technologies.Artwork;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitiveArc;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.Tool;
import com.sun.electric.tool.drc.DRC;
import com.sun.electric.tool.erc.ERCWellCheck;
import com.sun.electric.tool.erc.ERCAntenna;
import com.sun.electric.tool.generator.PadGenerator;
import com.sun.electric.tool.generator.layout.GateLayoutGenerator;
import com.sun.electric.tool.io.input.Input;
import com.sun.electric.tool.io.input.Simulate;
import com.sun.electric.tool.io.output.Output;
import com.sun.electric.tool.io.output.PostScript;
import com.sun.electric.tool.io.output.Spice;
import com.sun.electric.tool.io.output.Verilog;
import com.sun.electric.tool.logicaleffort.LENetlister;
import com.sun.electric.tool.logicaleffort.LETool;
import com.sun.electric.tool.routing.Routing;
import com.sun.electric.tool.routing.AutoStitch;
import com.sun.electric.tool.routing.MimicStitch;
import com.sun.electric.tool.simulation.IRSIMTool;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.dialogs.*;
import com.sun.electric.tool.user.help.HelpViewer;
import com.sun.electric.tool.user.ui.MenuBar;
import com.sun.electric.tool.user.ui.MenuBar.Menu;
import com.sun.electric.tool.user.ui.MenuBar.MenuItem;
import com.sun.electric.tool.user.ui.EditWindow;
import com.sun.electric.tool.user.ui.WindowFrame;
import com.sun.electric.tool.user.ui.TopLevel;
import com.sun.electric.tool.user.ui.PixelDrawing;
import com.sun.electric.tool.user.ui.MessagesWindow;
import com.sun.electric.tool.user.ui.PaletteFrame;
import com.sun.electric.tool.user.ui.ToolBar;
import com.sun.electric.tool.user.ui.ClickZoomWireListener;
import com.sun.electric.tool.user.ui.SizeListener;
import com.sun.electric.tool.user.ui.TextWindow;
import com.sun.electric.tool.user.ui.WaveformWindow;
import com.sun.electric.tool.user.ui.WindowContent;
import com.sun.electric.tool.user.ui.ZoomAndPanListener;
import com.sun.electric.Main;
import java.awt.Toolkit;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Graphics;
import java.awt.geom.AffineTransform;
import java.awt.Image;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.KeyEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.Area;
import java.awt.print.PrinterJob;
import java.awt.print.Printable;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.io.File;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.net.URL;
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import javax.print.PrintServiceLookup;
import javax.print.PrintService;
import javax.swing.ButtonGroup;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import javax.swing.JOptionPane;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.text.DecimalFormat;
/**
* This class has all of the pulldown menu commands in Electric.
* <p>
* For SDI mode Swing requires that each window have it's own menu.
* This means for consistency across windows that a change of state on
* a menu item in one window's menu must occur in all other window's
* menus as well (such as checking a check box).
*/
public final class MenuCommands
{
// It is never useful for anyone to create an instance of this class
private MenuCommands() {}
/**
* Method to create the pulldown menus.
*/
public static MenuBar createMenuBar()
{
// create the menu bar
MenuBar menuBar = new MenuBar();
MenuItem m;
int buckyBit = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/****************************** THE FILE MENU ******************************/
Menu fileMenu = new Menu("File", 'F');
menuBar.add(fileMenu);
fileMenu.addMenuItem("New Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newLibraryCommand(); } });
fileMenu.addMenuItem("Open Library", KeyStroke.getKeyStroke('O', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { openLibraryCommand(); } });
Menu importSubMenu = new Menu("Import");
fileMenu.add(importSubMenu);
importSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { importLibraryCommand(); } });
fileMenu.addMenuItem("I/O Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { IOOptions.ioOptionsCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Close Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { closeLibraryCommand(Library.getCurrent()); } });
fileMenu.addMenuItem("Save Library", KeyStroke.getKeyStroke('S', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.ELIB); } });
fileMenu.addMenuItem("Save Library as...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAsLibraryCommand(); } });
fileMenu.addMenuItem("Save All Libraries",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAllLibrariesCommand(); } });
Menu exportSubMenu = new Menu("Export");
fileMenu.add(exportSubMenu);
exportSubMenu.addMenuItem("CIF (Caltech Intermediate Format)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CIF, false); } });
exportSubMenu.addMenuItem("GDS II (Stream)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.GDS, false); } });
exportSubMenu.addMenuItem("PostScript", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.POSTSCRIPT, false); } });
exportSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.READABLEDUMP); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Change Current Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.changeCurrentLibraryCommand(); } });
fileMenu.addMenuItem("List Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.listLibrariesCommand(); } });
fileMenu.addMenuItem("Rename Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.renameLibraryCommand(); } });
fileMenu.addMenuItem("Mark All Libraries for Saving", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.markAllLibrariesForSavingCommand(); } });
fileMenu.addMenuItem("Repair Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.checkAndRepairCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Print...", KeyStroke.getKeyStroke('P', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { printCommand(); } });
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
fileMenu.addSeparator();
fileMenu.addMenuItem("Quit", KeyStroke.getKeyStroke('Q', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { quitCommand(); } });
}
/****************************** THE EDIT MENU ******************************/
Menu editMenu = new Menu("Edit", 'E');
menuBar.add(editMenu);
editMenu.addMenuItem("Cut", KeyStroke.getKeyStroke('X', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.cut(); } });
editMenu.addMenuItem("Copy", KeyStroke.getKeyStroke('C', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.copy(); } });
editMenu.addMenuItem("Paste", KeyStroke.getKeyStroke('V', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.paste(); } });
editMenu.addMenuItem("Duplicate", KeyStroke.getKeyStroke('M', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.duplicate(); } });
editMenu.addSeparator();
Menu arcSubMenu = new Menu("Arc", 'A');
editMenu.add(arcSubMenu);
arcSubMenu.addMenuItem("Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcRigidCommand(); }});
arcSubMenu.addMenuItem("Not Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotRigidCommand(); }});
arcSubMenu.addMenuItem("Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcFixedAngleCommand(); }});
arcSubMenu.addMenuItem("Not Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotFixedAngleCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Toggle Directionality", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcDirectionalCommand(); }});
arcSubMenu.addMenuItem("Toggle Ends Extension", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcEndsExtendCommand(); }});
arcSubMenu.addMenuItem("Reverse", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcReverseCommand(); }});
arcSubMenu.addMenuItem("Toggle Head-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipHeadCommand(); }});
arcSubMenu.addMenuItem("Toggle Tail-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipTailCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Rip Bus", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.ripBus(); }});
editMenu.addSeparator();
editMenu.addMenuItem("Undo", KeyStroke.getKeyStroke('Z', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { undoCommand(); } });
editMenu.addMenuItem("Redo", KeyStroke.getKeyStroke('Y', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { redoCommand(); } });
editMenu.addSeparator();
Menu rotateSubMenu = new Menu("Rotate", 'R');
editMenu.add(rotateSubMenu);
rotateSubMenu.addMenuItem("90 Degrees Clockwise", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(2700); }});
rotateSubMenu.addMenuItem("90 Degrees Counterclockwise", KeyStroke.getKeyStroke('J', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(900); }});
rotateSubMenu.addMenuItem("180 Degrees", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(1800); }});
rotateSubMenu.addMenuItem("Other...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(0); }});
Menu mirrorSubMenu = new Menu("Mirror", 'M');
editMenu.add(mirrorSubMenu);
mirrorSubMenu.addMenuItem("Horizontally (flip over X-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(true); }});
mirrorSubMenu.addMenuItem("Vertically (flip over Y-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(false); }});
Menu sizeSubMenu = new Menu("Size", 'S');
editMenu.add(sizeSubMenu);
sizeSubMenu.addMenuItem("Interactively", KeyStroke.getKeyStroke('B', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeObjects(); } });
sizeSubMenu.addMenuItem("All Selected Nodes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllNodes(); }});
sizeSubMenu.addMenuItem("All Selected Arcs...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllArcs(); }});
Menu moveSubMenu = new Menu("Move", 'V');
editMenu.add(moveSubMenu);
moveSubMenu.addMenuItem("Spread...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Spread.showSpreadDialog(); }});
moveSubMenu.addMenuItem("Move Objects By...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { MoveBy.showMoveByDialog(); }});
moveSubMenu.addMenuItem("Align to Grid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignToGrid(); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Horizontally to Left", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 0); }});
moveSubMenu.addMenuItem("Align Horizontally to Right", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 1); }});
moveSubMenu.addMenuItem("Align Horizontally to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 2); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Vertically to Top", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 0); }});
moveSubMenu.addMenuItem("Align Vertically to Bottom", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 1); }});
moveSubMenu.addMenuItem("Align Vertically to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 2); }});
editMenu.addMenuItem("Toggle Port Negation", KeyStroke.getKeyStroke('T', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.toggleNegatedCommand(); }});
editMenu.addSeparator();
m=editMenu.addMenuItem("Erase", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelected(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), null);
editMenu.addMenuItem("Erase Geometry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelectedGeometry(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Edit Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { EditOptions.editOptionsCommand(); } });
editMenu.addMenuItem("Key Bindings...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { keyBindingsCommand(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Get Info...", KeyStroke.getKeyStroke('I', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { getInfoCommand(); } });
Menu editInfoSubMenu = new Menu("Info", 'V');
editMenu.add(editInfoSubMenu);
editInfoSubMenu.addMenuItem("Attributes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Attributes.showDialog(); } });
editInfoSubMenu.addMenuItem("See All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { seeAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Hide All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { hideAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Default Parameter Visibility", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultParamVisibilityCommand(); } });
editInfoSubMenu.addSeparator();
editInfoSubMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(false); } });
editMenu.addSeparator();
Menu modeSubMenu = new Menu("Modes");
editMenu.add(modeSubMenu);
Menu modeSubMenuEdit = new Menu("Edit");
modeSubMenu.add(modeSubMenuEdit);
ButtonGroup editGroup = new ButtonGroup();
JMenuItem cursorClickZoomWire, cursorSelect, cursorWiring, cursorPan, cursorZoom, cursorOutline, cursorMeasure;
cursorClickZoomWire = modeSubMenuEdit.addRadioButton(ToolBar.cursorClickZoomWireName, true, editGroup, KeyStroke.getKeyStroke('S', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.clickZoomWireCommand(); } });
ToolBar.CursorMode cm = ToolBar.getCursorMode();
if (cm == ToolBar.CursorMode.CLICKZOOMWIRE) cursorClickZoomWire.setSelected(true);
if (ToolBar.secondaryInputModes) {
cursorSelect = modeSubMenuEdit.addRadioButton(ToolBar.cursorSelectName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectCommand(); } });
cursorWiring = modeSubMenuEdit.addRadioButton(ToolBar.cursorWiringName, false, editGroup, KeyStroke.getKeyStroke('W', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.wiringCommand(); } });
if (cm == ToolBar.CursorMode.SELECT) cursorSelect.setSelected(true);
if (cm == ToolBar.CursorMode.WIRE) cursorWiring.setSelected(true);
}
cursorPan = modeSubMenuEdit.addRadioButton(ToolBar.cursorPanName, false, editGroup, KeyStroke.getKeyStroke('P', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.panCommand(); } });
cursorZoom = modeSubMenuEdit.addRadioButton(ToolBar.cursorZoomName, false, editGroup, KeyStroke.getKeyStroke('Z', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.zoomCommand(); } });
cursorOutline = modeSubMenuEdit.addRadioButton(ToolBar.cursorOutlineName, false, editGroup, KeyStroke.getKeyStroke('Y', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.outlineEditCommand(); } });
cursorMeasure = modeSubMenuEdit.addRadioButton(ToolBar.cursorMeasureName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.measureCommand(); } });
if (cm == ToolBar.CursorMode.PAN) cursorPan.setSelected(true);
if (cm == ToolBar.CursorMode.ZOOM) cursorZoom.setSelected(true);
if (cm == ToolBar.CursorMode.OUTLINE) cursorOutline.setSelected(true);
if (cm == ToolBar.CursorMode.MEASURE) cursorMeasure.setSelected(true);
Menu modeSubMenuMovement = new Menu("Movement");
modeSubMenu.add(modeSubMenuMovement);
ButtonGroup movementGroup = new ButtonGroup();
JMenuItem moveFull, moveHalf, moveQuarter;
moveFull = modeSubMenuMovement.addRadioButton(ToolBar.moveFullName, true, movementGroup, KeyStroke.getKeyStroke('F', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.fullArrowDistanceCommand(); } });
moveHalf = modeSubMenuMovement.addRadioButton(ToolBar.moveHalfName, false, movementGroup, KeyStroke.getKeyStroke('H', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.halfArrowDistanceCommand(); } });
moveQuarter = modeSubMenuMovement.addRadioButton(ToolBar.moveQuarterName, false, movementGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.quarterArrowDistanceCommand(); } });
double ad = ToolBar.getArrowDistance();
if (ad == 1.0) moveFull.setSelected(true); else
if (ad == 0.5) moveHalf.setSelected(true); else
moveQuarter.setSelected(true);
Menu modeSubMenuSelect = new Menu("Select");
modeSubMenu.add(modeSubMenuSelect);
ButtonGroup selectGroup = new ButtonGroup();
JMenuItem selectArea, selectObjects;
selectArea = modeSubMenuSelect.addRadioButton(ToolBar.selectAreaName, true, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectAreaCommand(); } });
selectObjects = modeSubMenuSelect.addRadioButton(ToolBar.selectObjectsName, false, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectObjectsCommand(); } });
ToolBar.SelectMode sm = ToolBar.getSelectMode();
if (sm == ToolBar.SelectMode.AREA) selectArea.setSelected(true); else
selectObjects.setSelected(true);
modeSubMenuSelect.addCheckBox(ToolBar.specialSelectName, false, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.toggleSelectSpecialCommand(e); } });
editMenu.addMenuItem("Array...", KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Array.showArrayDialog(); } });
editMenu.addMenuItem("Insert Jog In Arc", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { insertJogInArcCommand(); } });
editMenu.addMenuItem("Change...", KeyStroke.getKeyStroke('C', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Change.showChangeDialog(); } });
Menu textSubMenu = new Menu("Text");
editMenu.add(textSubMenu);
textSubMenu.addMenuItem("Find Text...", KeyStroke.getKeyStroke('L', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { FindText.findTextDialog(); }});
textSubMenu.addMenuItem("Change Text Size...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ChangeText.changeTextDialog(); }});
textSubMenu.addMenuItem("Read Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.readTextCell(); }});
textSubMenu.addMenuItem("Save Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.writeTextCell(); }});
Menu cleanupSubMenu = new Menu("Cleanup Cell");
editMenu.add(cleanupSubMenu);
cleanupSubMenu.addMenuItem("Cleanup Pins", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(false); }});
cleanupSubMenu.addMenuItem("Cleanup Pins Everywhere", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(true); }});
cleanupSubMenu.addMenuItem("Show Nonmanhattan", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showNonmanhattanCommand(); }});
cleanupSubMenu.addMenuItem("Shorten Selected Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.shortenArcsCommand(); }});
Menu specialSubMenu = new Menu("Special Function");
editMenu.add(specialSubMenu);
specialSubMenu.addMenuItem("Show Undo List", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); } });
m = specialSubMenu.addMenuItem("Show Cursor Coordinates", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
m = specialSubMenu.addMenuItem("Artwork Appearance...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
Menu selListSubMenu = new Menu("Selection");
editMenu.add(selListSubMenu);
selListSubMenu.addMenuItem("Select All", KeyStroke.getKeyStroke('A', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllCommand(); }});
selListSubMenu.addMenuItem("Select All Like This", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLikeThisCommand(); }});
selListSubMenu.addMenuItem("Select Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEasyCommand(); }});
selListSubMenu.addMenuItem("Select Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectHardCommand(); }});
selListSubMenu.addMenuItem("Select Nothing", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectNothingCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Select Object...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SelectObject.selectObjectDialog(); }});
selListSubMenu.addMenuItem("Deselect All Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deselectAllArcsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Make Selected Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
selListSubMenu.addMenuItem("Make Selected Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeHardCommand(); }});
selListSubMenu.addSeparator();
m = selListSubMenu.addMenuItem("Push Selection", KeyStroke.getKeyStroke('1', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
m = selListSubMenu.addMenuItem("Pop Selection", KeyStroke.getKeyStroke('3', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Enclosed Objects", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEnclosedObjectsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Show Next Error", KeyStroke.getKeyStroke('>'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNextErrorCommand(); }});
selListSubMenu.addMenuItem("Show Previous Error", KeyStroke.getKeyStroke('<'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showPrevErrorCommand(); }});
/****************************** THE CELL MENU ******************************/
Menu cellMenu = new Menu("Cell", 'C');
menuBar.add(cellMenu);
cellMenu.addMenuItem("Edit Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.editCell); }});
cellMenu.addMenuItem("Place Cell Instance...", KeyStroke.getKeyStroke('N', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.newInstance); }});
cellMenu.addMenuItem("New Cell...", KeyStroke.getKeyStroke('N', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellCommand(); } });
cellMenu.addMenuItem("Rename Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.renameCell); }});
cellMenu.addMenuItem("Duplicate Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.duplicateCell); }});
cellMenu.addMenuItem("Delete Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.deleteCell); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("Delete Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteCellCommand(); } });
cellMenu.addMenuItem("Cell Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellControlCommand(); }});
cellMenu.addMenuItem("Cross-Library Copy...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { crossLibraryCopyCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Down Hierarchy", KeyStroke.getKeyStroke('D', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m = cellMenu.addMenuItem("Down Hierarchy In Place", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m.setEnabled(false);
cellMenu.addMenuItem("Up Hierarchy", KeyStroke.getKeyStroke('U', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { upHierCommand(); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("New Version of Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellVersionCommand(); } });
cellMenu.addMenuItem("Duplicate Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { duplicateCellCommand(); } });
cellMenu.addMenuItem("Delete Unused Old Versions", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteOldCellVersionsCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Describe this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.describeThisCellCommand(); } });
cellMenu.addMenuItem("General Cell Lists...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.generalCellListsCommand(); } });
Menu specListSubMenu = new Menu("Special Cell Lists");
cellMenu.add(specListSubMenu);
specListSubMenu.addMenuItem("List Nodes in this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listNodesInCellCommand(); }});
specListSubMenu.addMenuItem("List Cell Instances", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellInstancesCommand(); }});
specListSubMenu.addMenuItem("List Cell Usage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellUsageCommand(); }});
cellMenu.addMenuItem("Cell Parameters...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellParametersCommand(); } });
cellMenu.addSeparator();
Menu expandListSubMenu = new Menu("Expand Cell Instances");
cellMenu.add(expandListSubMenu);
expandListSubMenu.addMenuItem("One Level Down", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandOneLevelDownCommand(); }});
expandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandFullCommand(); }});
expandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandSpecificCommand(); }});
Menu unExpandListSubMenu = new Menu("Unexpand Cell Instances");
cellMenu.add(unExpandListSubMenu);
unExpandListSubMenu.addMenuItem("One Level Up", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandOneLevelUpCommand(); }});
unExpandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandFullCommand(); }});
unExpandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m = cellMenu.addMenuItem("Look Inside Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m.setEnabled(false);
cellMenu.addSeparator();
cellMenu.addMenuItem("Package Into Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.packageIntoCell(); } });
cellMenu.addMenuItem("Extract Cell Instance", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.extractCells(); } });
/****************************** THE EXPORT MENU ******************************/
Menu exportMenu = new Menu("Export", 'X');
menuBar.add(exportMenu);
exportMenu.addMenuItem("Create Export...", KeyStroke.getKeyStroke('E', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.newExportCommand(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Re-Export Everything", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportAll(); } });
exportMenu.addMenuItem("Re-Export Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportHighlighted(); } });
exportMenu.addMenuItem("Re-Export Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportPowerAndGround(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Delete Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExport(); } });
exportMenu.addMenuItem("Delete All Exports on Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsOnHighlighted(); } });
exportMenu.addMenuItem("Delete Exports in Area", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsInArea(); } });
exportMenu.addMenuItem("Move Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.moveExport(); } });
exportMenu.addMenuItem("Rename Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.renameExport(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Summarize Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(true); } });
exportMenu.addMenuItem("List Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(false); } });
exportMenu.addMenuItem("Show Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showExports(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Show Ports on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showPorts(); } });
/****************************** THE VIEW MENU ******************************/
Menu viewMenu = new Menu("View", 'V');
menuBar.add(viewMenu);
viewMenu.addMenuItem("View Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { viewControlCommand(); } });
viewMenu.addMenuItem("Change Cell's View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { changeViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Edit Layout View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editLayoutViewCommand(); } });
viewMenu.addMenuItem("Edit Schematic View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editMultiPageSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editIconViewCommand(); } });
viewMenu.addMenuItem("Edit VHDL View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editVHDLViewCommand(); } });
viewMenu.addMenuItem("Edit Documentation View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editDocViewCommand(); } });
viewMenu.addMenuItem("Edit Skeleton View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSkeletonViewCommand(); } });
viewMenu.addMenuItem("Edit Other View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editOtherViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Make Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeIconViewCommand(); } });
viewMenu.addMenuItem("Make Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeMultiPageSchematicViewCommand(); } });
/****************************** THE WINDOW MENU ******************************/
Menu windowMenu = new Menu("Window", 'W');
menuBar.add(windowMenu);
m = windowMenu.addMenuItem("Fill Display", KeyStroke.getKeyStroke('9', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { fullDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD9, buckyBit), null);
m = windowMenu.addMenuItem("Redisplay Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.redrawDisplay(); } });
m = windowMenu.addMenuItem("Zoom Out", KeyStroke.getKeyStroke('0', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomOutDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, buckyBit), null);
m = windowMenu.addMenuItem("Zoom In", KeyStroke.getKeyStroke('7', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomInDisplay(); } });
+ menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD7, buckyBit), null);
Menu specialZoomSubMenu = new Menu("Special Zoom");
windowMenu.add(specialZoomSubMenu);
m = specialZoomSubMenu.addMenuItem("Focus on Highlighted", KeyStroke.getKeyStroke('F', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { focusOnHighlighted(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD5, buckyBit), null);
m = specialZoomSubMenu.addMenuItem("Zoom Box", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomBoxCommand(); }});
- menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD7, buckyBit), null);
specialZoomSubMenu.addMenuItem("Make Grid Just Visible", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeGridJustVisibleCommand(); }});
specialZoomSubMenu.addMenuItem("Match Other Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { matchOtherWindowCommand(); }});
windowMenu.addSeparator();
m = windowMenu.addMenuItem("Pan Left", KeyStroke.getKeyStroke('4', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD4, buckyBit), null);
m = windowMenu.addMenuItem("Pan Right", KeyStroke.getKeyStroke('6', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD6, buckyBit), null);
m = windowMenu.addMenuItem("Pan Up", KeyStroke.getKeyStroke('8', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD8, buckyBit), null);
m = windowMenu.addMenuItem("Pan Down", KeyStroke.getKeyStroke('2', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD2, buckyBit), null);
Menu panningDistanceSubMenu = new Menu("Panning Distance");
windowMenu.add(panningDistanceSubMenu);
ButtonGroup windowPanGroup = new ButtonGroup();
JMenuItem panSmall, panMedium, panLarge;
panSmall = panningDistanceSubMenu.addRadioButton("Small", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.15); } });
panMedium = panningDistanceSubMenu.addRadioButton("Medium", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.3); } });
panLarge = panningDistanceSubMenu.addRadioButton("Large", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.6); } });
panLarge.setSelected(true);
windowMenu.addSeparator();
windowMenu.addMenuItem("Toggle Grid", KeyStroke.getKeyStroke('G', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { toggleGridCommand(); } });
windowMenu.addSeparator();
Menu windowPartitionSubMenu = new Menu("Adjust Position");
windowMenu.add(windowPartitionSubMenu);
windowPartitionSubMenu.addMenuItem("Tile Horizontally", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { tileHorizontallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Tile Vertically", KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { tileVerticallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Cascade", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cascadeWindowsCommand(); }});
windowMenu.addMenuItem("Close Window", KeyStroke.getKeyStroke(KeyEvent.VK_W, buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { WindowFrame curWF = WindowFrame.getCurrentWindowFrame();
curWF.finished(); }});
if (!TopLevel.isMDIMode()) {
windowMenu.addSeparator();
windowMenu.addMenuItem("Move to Other Display", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { moveToOtherDisplayCommand(); } });
}
windowMenu.addSeparator();
windowMenu.addMenuItem("Layer Visibility...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerVisibilityCommand(); } });
Menu colorSubMenu = new Menu("Color");
windowMenu.add(colorSubMenu);
colorSubMenu.addMenuItem("Restore Default Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultBackgroundCommand(); }});
colorSubMenu.addMenuItem("Black Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { blackBackgroundCommand(); }});
colorSubMenu.addMenuItem("White Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { whiteBackgroundCommand(); }});
Menu messagesSubMenu = new Menu("Messages Window");
windowMenu.add(messagesSubMenu);
messagesSubMenu.addMenuItem("Save Messages", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().save(); }});
messagesSubMenu.addMenuItem("Clear", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().clear(); }});
/****************************** THE TOOL MENU ******************************/
Menu toolMenu = new Menu("Tool", 'T');
menuBar.add(toolMenu);
//------------------- DRC
Menu drcSubMenu = new Menu("DRC", 'D');
toolMenu.add(drcSubMenu);
drcSubMenu.addMenuItem("Check Hierarchically", KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkHierarchically(); }});
drcSubMenu.addMenuItem("Check Selection Area Hierarchically", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkAreaHierarchically(); }});
//------------------- Simulation (SPICE)
Menu spiceSimulationSubMenu = new Menu("Simulation (SPICE)", 'S');
toolMenu.add(spiceSimulationSubMenu);
spiceSimulationSubMenu.addMenuItem("Write SPICE Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.SPICE, true); }});
spiceSimulationSubMenu.addMenuItem("Write CDL Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CDL, true); }});
spiceSimulationSubMenu.addMenuItem("Plot Spice Listing...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotSpiceResults(); }});
m = spiceSimulationSubMenu.addMenuItem("Plot Spice for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
spiceSimulationSubMenu.addMenuItem("Set Spice Model...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setSpiceModel(); }});
spiceSimulationSubMenu.addMenuItem("Add Multiplier", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
spiceSimulationSubMenu.addSeparator();
spiceSimulationSubMenu.addMenuItem("Set Generic SPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 2 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_2_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 3 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_3_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set HSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_H_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set PSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_P_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set GnuCap Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_GC_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SmartSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_SM_TEMPLATE_KEY); }});
//------------------- Simulation (Verilog)
Menu verilogSimulationSubMenu = new Menu("Simulation (Verilog)", 'V');
toolMenu.add(verilogSimulationSubMenu);
verilogSimulationSubMenu.addMenuItem("Write Verilog Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.VERILOG, true); } });
verilogSimulationSubMenu.addMenuItem("Plot Verilog VCD Dump...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotVerilogResults(); }});
m = verilogSimulationSubMenu.addMenuItem("Plot Verilog for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
verilogSimulationSubMenu.addSeparator();
verilogSimulationSubMenu.addMenuItem("Set Verilog Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Verilog.VERILOG_TEMPLATE_KEY); }});
verilogSimulationSubMenu.addSeparator();
Menu verilogWireTypeSubMenu = new Menu("Set Verilog Wire", 'W');
verilogWireTypeSubMenu.addMenuItem("Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(0); }});
verilogWireTypeSubMenu.addMenuItem("Trireg", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(1); }});
verilogWireTypeSubMenu.addMenuItem("Default", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(2); }});
verilogSimulationSubMenu.add(verilogWireTypeSubMenu);
Menu transistorStrengthSubMenu = new Menu("Transistor Strength", 'T');
transistorStrengthSubMenu.addMenuItem("Weak", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(true); }});
transistorStrengthSubMenu.addMenuItem("Normal", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(false); }});
verilogSimulationSubMenu.add(transistorStrengthSubMenu);
//------------------- Simulation (others)
Menu netlisters = new Menu("Simulation (others)");
toolMenu.add(netlisters);
netlisters.addMenuItem("Write IRSIM Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { irsimNetlistCommand(); }});
netlisters.addMenuItem("Write Maxwell Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.MAXWELL, true); } });
//------------------- ERC
Menu ercSubMenu = new Menu("ERC", 'E');
toolMenu.add(ercSubMenu);
ercSubMenu.addMenuItem("Check Wells", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ERCWellCheck.analyzeCurCell(true); } });
ercSubMenu.addMenuItem("Antenna Check", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { new ERCAntenna(); } });
//------------------- Network
Menu networkSubMenu = new Menu("Network", 'N');
toolMenu.add(networkSubMenu);
networkSubMenu.addMenuItem("Show Network", KeyStroke.getKeyStroke('K', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNetworkCommand(); } });
networkSubMenu.addMenuItem("List Networks", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listNetworksCommand(); } });
networkSubMenu.addMenuItem("List Connections on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listConnectionsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports below Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsBelowNetworkCommand(); } });
networkSubMenu.addMenuItem("List Geometry on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listGeometryOnNetworkCommand(); } });
networkSubMenu.addSeparator();
networkSubMenu.addMenuItem("Show Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showPowerAndGround(); } });
networkSubMenu.addMenuItem("Validate Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { validatePowerAndGround(); } });
networkSubMenu.addMenuItem("Redo Network Numbering", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { redoNetworkNumberingCommand(); } });
//------------------- Logical Effort
Menu logEffortSubMenu = new Menu("Logical Effort", 'L');
logEffortSubMenu.addMenuItem("Optimize for Equal Gate Delays", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { optimizeEqualGateDelaysCommand(); }});
logEffortSubMenu.addMenuItem("Print Info for Selected Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { printLEInfoCommand(); }});
toolMenu.add(logEffortSubMenu);
//------------------- Routing
Menu routingSubMenu = new Menu("Routing", 'R');
toolMenu.add(routingSubMenu);
routingSubMenu.addCheckBox("Enable Auto-Stitching", Routing.isAutoStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableAutoStitching(e); } });
routingSubMenu.addMenuItem("Auto-Stitch Now", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(false, true); }});
routingSubMenu.addMenuItem("Auto-Stitch Highlighted Now", KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(true, true); }});
routingSubMenu.addSeparator();
routingSubMenu.addCheckBox("Enable Mimic-Stitching", Routing.isMimicStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableMimicStitching(e); }});
routingSubMenu.addMenuItem("Mimic-Stitch Now", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { MimicStitch.mimicStitch(true); }});
routingSubMenu.addMenuItem("Mimic Selected", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.tool.mimicSelected(); }});
routingSubMenu.addSeparator();
routingSubMenu.addMenuItem("Get Unrouted Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { getUnroutedArcCommand(); }});
m = routingSubMenu.addMenuItem("Copy Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
m = routingSubMenu.addMenuItem("Paste Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
//------------------- Generation
Menu generationSubMenu = new Menu("Generation", 'G');
toolMenu.add(generationSubMenu);
generationSubMenu.addMenuItem("Coverage Implants Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { implantGeneratorCommand(true, false); }});
generationSubMenu.addMenuItem("Pad Frame Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { padFrameGeneratorCommand(); }});
toolMenu.addSeparator();
toolMenu.addMenuItem("Tool Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolOptions.toolOptionsCommand(); } });
toolMenu.addMenuItem("List Tools",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listToolsCommand(); } });
Menu languagesSubMenu = new Menu("Languages");
languagesSubMenu.addMenuItem("Run Java Bean Shell Script", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { javaBshScriptCommand(); }});
toolMenu.add(languagesSubMenu);
/****************************** THE HELP MENU ******************************/
Menu helpMenu = new Menu("Help", 'H');
menuBar.add(helpMenu);
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
helpMenu.addMenuItem("About Electric...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { aboutCommand(); } });
}
helpMenu.addMenuItem("Help Index", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { toolTipsCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Describe this Technology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { describeTechnologyCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Make fake circuitry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeFakeCircuitryCommand(); } });
helpMenu.addMenuItem("Make fake simulation window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { WaveformWindow.makeFakeWaveformCommand(); }});
// helpMenu.addMenuItem("Whit Diffie's design...", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { whitDiffieCommand(); } });
/****************************** Russell's TEST MENU ******************************/
Menu russMenu = new Menu("Russell", 'R');
menuBar.add(russMenu);
russMenu.addMenuItem("Generate fill cells", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.FillLibGen();
}
});
russMenu.addMenuItem("Gate Generator Regression", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateRegression();
}
});
russMenu.addMenuItem("Generate gate layouts", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateLayoutGenerator();
}
});
russMenu.addMenuItem("create flat netlists for Ivan", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.IvanFlat();
}
});
russMenu.addMenuItem("layout flat", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.LayFlat();
}
});
russMenu.addMenuItem("Jemini", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.ncc.NccJob();
}
});
russMenu.addMenuItem("Random Test", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.Test();
}
});
/****************************** Jon's TEST MENU ******************************/
Menu jongMenu = new Menu("JonG", 'J');
menuBar.add(jongMenu);
jongMenu.addMenuItem("Describe Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(false); }});
jongMenu.addMenuItem("Describe Proto Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(true); }});
jongMenu.addMenuItem("Describe Current Library Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listLibVars(); }});
jongMenu.addMenuItem("Eval Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { evalVarsOnObject(); }});
jongMenu.addMenuItem("LE test1", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { LENetlister.test1(); }});
jongMenu.addMenuItem("Open Purple Lib", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { openP4libCommand(); }});
//jongMenu.addMenuItem("Check Exports", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { checkExports(); }});
/****************************** Gilda's TEST MENU ******************************/
Menu gildaMenu = new Menu("Gilda", 'G');
menuBar.add(gildaMenu);
gildaMenu.addMenuItem("Merge Polyons", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, true);}});
gildaMenu.addMenuItem("Covering Implants", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, false);}});
gildaMenu.addMenuItem("Covering Implants Old", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(false, false);}});
gildaMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(true); } });
/********************************* Hidden Menus *******************************/
Menu wiringShortcuts = new Menu("Circuit Editing");
menuBar.addHidden(wiringShortcuts);
wiringShortcuts.addMenuItem("Wire to Poly", KeyStroke.getKeyStroke(KeyEvent.VK_0, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(0); }});
wiringShortcuts.addMenuItem("Wire to M1", KeyStroke.getKeyStroke(KeyEvent.VK_1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(1); }});
wiringShortcuts.addMenuItem("Wire to M2", KeyStroke.getKeyStroke(KeyEvent.VK_2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(2); }});
wiringShortcuts.addMenuItem("Wire to M3", KeyStroke.getKeyStroke(KeyEvent.VK_3, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(3); }});
wiringShortcuts.addMenuItem("Wire to M4", KeyStroke.getKeyStroke(KeyEvent.VK_4, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(4); }});
wiringShortcuts.addMenuItem("Wire to M5", KeyStroke.getKeyStroke(KeyEvent.VK_5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(5); }});
wiringShortcuts.addMenuItem("Wire to M6", KeyStroke.getKeyStroke(KeyEvent.VK_6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(6); }});
wiringShortcuts.addMenuItem("Switch Wiring Target", KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.switchWiringTarget(); }});
// return the menu bar
return menuBar;
}
// ---------------------- THE FILE MENU -----------------
public static void newLibraryCommand()
{
String newLibName = JOptionPane.showInputDialog("New Library Name", "");
if (newLibName == null) return;
Library lib = Library.newInstance(newLibName, null);
if (lib == null) return;
lib.setCurrent();
WindowFrame.wantToRedoLibraryTree();
EditWindow.repaintAll();
TopLevel.getCurrentJFrame().getToolBar().setEnabled(ToolBar.SaveLibraryName, Library.getCurrent() != null);
}
/**
* This method implements the command to read a library.
* It is interactive, and pops up a dialog box.
*/
public static void openLibraryCommand()
{
String fileName = OpenFile.chooseInputFile(OpenFile.Type.ELIB, null);
if (fileName != null)
{
// start a job to do the input
URL fileURL = TextUtils.makeURLToFile(fileName);
ReadELIB job = new ReadELIB(fileURL);
}
}
/**
* Class to read a library in a new thread.
* For a non-interactive script, use ReadELIB job = new ReadELIB(filename).
*/
public static class ReadELIB extends Job
{
URL fileURL;
public ReadELIB(URL fileURL)
{
super("Read Library", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.fileURL = fileURL;
startJob();
}
public boolean doIt()
{
Library lib = Input.readLibrary(fileURL, OpenFile.Type.ELIB);
Undo.noUndoAllowed();
if (lib == null) return false;
lib.setCurrent();
Cell cell = lib.getCurCell();
if (cell == null)
System.out.println("No current cell in this library");
else
{
// check if edit window open with null cell, use that one if exists
for (Iterator it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
WindowContent content = wf.getContent();
if (content.getCell() == null)
{
wf.setCellWindow(cell);
WindowFrame.setCurrentWindowFrame(wf);
TopLevel.getCurrentJFrame().getToolBar().setEnabled(ToolBar.SaveLibraryName, Library.getCurrent() != null);
return true;
}
}
WindowFrame.createEditWindow(cell);
// no clean for now.
TopLevel.getCurrentJFrame().getToolBar().setEnabled(ToolBar.SaveLibraryName, Library.getCurrent() != null);
}
return true;
}
}
/**
* This method implements the command to import a library (Readable Dump format).
* It is interactive, and pops up a dialog box.
*/
public static void importLibraryCommand()
{
String fileName = OpenFile.chooseInputFile(OpenFile.Type.READABLEDUMP, null);
if (fileName != null)
{
// start a job to do the input
URL fileURL = TextUtils.makeURLToFile(fileName);
ReadTextLibrary job = new ReadTextLibrary(fileURL);
}
}
/**
* Class to read a text library in a new thread.
* For a non-interactive script, use ReadTextLibrary job = new ReadTextLibrary(filename).
*/
private static class ReadTextLibrary extends Job
{
URL fileURL;
protected ReadTextLibrary(URL fileURL)
{
super("Read Text Library", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.fileURL = fileURL;
startJob();
}
public boolean doIt()
{
Library lib = Input.readLibrary(fileURL, OpenFile.Type.READABLEDUMP);
Undo.noUndoAllowed();
if (lib == null) return false;
lib.setCurrent();
Cell cell = lib.getCurCell();
if (cell == null) System.out.println("No current cell in this library"); else
{
// check if edit window open with null cell, use that one if exists
for (Iterator it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
WindowContent content = wf.getContent();
if (content instanceof EditWindow)
{
if (content.getCell() == null)
{
content.setCell(cell, VarContext.globalContext);
return true;
}
}
}
WindowFrame.createEditWindow(cell);
}
return true;
}
}
public static void closeLibraryCommand(Library lib)
{
int response = JOptionPane.showConfirmDialog(TopLevel.getCurrentJFrame(), "Are you sure you want to close library " + lib.getLibName() + "?");
if (response != JOptionPane.YES_OPTION) return;
String libName = lib.getLibName();
WindowFrame.removeLibraryReferences(lib);
if (lib.kill())
System.out.println("Library " + libName + " closed");
WindowFrame.wantToRedoLibraryTree();
EditWindow.repaintAll();
// Disable save icon if no more libraries are open
TopLevel.getCurrentJFrame().getToolBar().setEnabled(ToolBar.SaveLibraryName, Library.getCurrent() != null);
}
/**
* This method implements the command to save a library.
* It is interactive, and pops up a dialog box.
* @return true if library saved, false otherwise.
*/
public static boolean saveLibraryCommand(Library lib, OpenFile.Type type)
{
String [] extensions = type.getExtensions();
String extension = extensions[0];
String fileName;
if (lib.isFromDisk() && type == OpenFile.Type.ELIB)
{
fileName = lib.getLibFile().getPath();
} else
{
fileName = OpenFile.chooseOutputFile(type, null, lib.getLibName() + "." + extension);
if (fileName == null) return false;
int dotPos = fileName.lastIndexOf('.');
if (dotPos < 0) fileName += "." + extension; else
{
if (!fileName.substring(dotPos+1).equals(extension))
{
fileName = fileName.substring(0, dotPos) + "." + extension;
}
}
}
SaveLibrary job = new SaveLibrary(lib, fileName, type);
return true;
}
/**
* Class to save a library in a new thread.
* For a non-interactive script, use SaveLibrary job = new SaveLibrary(filename).
* Saves as an elib.
*/
public static class SaveLibrary extends Job
{
Library lib;
String newName;
OpenFile.Type type;
public SaveLibrary(Library lib, String newName, OpenFile.Type type)
{
super("Write Library", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.lib = lib;
this.newName = newName;
this.type = type;
startJob();
}
public boolean doIt()
{
// rename the library if requested
if (newName != null)
{
URL libURL = TextUtils.makeURLToFile(newName);
lib.setLibFile(libURL);
lib.setLibName(TextUtils.getFileNameWithoutExtension(libURL));
}
boolean error = Output.writeLibrary(lib, type);
if (error)
{
System.out.println("Error writing the library file");
}
return true;
}
}
/**
* This method implements the command to save a library to a different file.
* It is interactive, and pops up a dialog box.
*/
public static void saveAsLibraryCommand()
{
Library lib = Library.getCurrent();
lib.clearFromDisk();
saveLibraryCommand(lib, OpenFile.Type.ELIB);
}
/**
* This method implements the command to save all libraries.
*/
public static void saveAllLibrariesCommand()
{
for(Iterator it = Library.getLibraries(); it.hasNext(); )
{
Library lib = (Library)it.next();
if (lib.isHidden()) continue;
if (!lib.isChangedMajor() && !lib.isChangedMinor()) continue;
if (!saveLibraryCommand(lib, OpenFile.Type.ELIB)) break;
}
}
/**
* This method implements the export cell command for different export types.
* It is interactive, and pops up a dialog box.
*/
public static void exportCellCommand(OpenFile.Type type, boolean isNetlist)
{
if (type == OpenFile.Type.POSTSCRIPT)
{
if (PostScript.syncAll()) return;
}
EditWindow wnd = EditWindow.needCurrent();
Cell cell = wnd.getCell();
if (cell == null)
{
System.out.println("No cell in this window");
return;
}
VarContext context = wnd.getVarContext();
String [] extensions = type.getExtensions();
String filePath = cell.getProtoName() + "." + extensions[0];
if (User.isShowFileSelectionForNetlists() || !isNetlist)
{
filePath = OpenFile.chooseOutputFile(type, null, filePath);
if (filePath == null) return;
} else
{
filePath = User.getWorkingDirectory() + File.separator + filePath;
}
exportCellCommand(cell, context, filePath, type);
}
/**
* This is the non-interactive version of exportCellCommand
*/
public static void exportCellCommand(Cell cell, VarContext context, String filePath, OpenFile.Type type)
{
ExportCell job = new ExportCell(cell, context, filePath, type);
}
/**
* Class to export a cell in a new thread.
* For a non-interactive script, use
* ExportCell job = new ExportCell(Cell cell, String filename, Output.ExportType type).
* Saves as an elib.
*/
private static class ExportCell extends Job
{
Cell cell;
VarContext context;
String filePath;
OpenFile.Type type;
public ExportCell(Cell cell, VarContext context, String filePath, OpenFile.Type type)
{
super("Export "+cell.describe()+" ("+type+")", User.tool, Job.Type.EXAMINE, null, null, Job.Priority.USER);
this.cell = cell;
this.context = context;
this.filePath = filePath;
this.type = type;
startJob();
}
public boolean doIt()
{
Output.writeCell(cell, context, filePath, type);
return true;
}
}
/**
* This method implements the command to print the current window.
*/
public static void printCommand()
{
Cell printCell = WindowFrame.needCurCell();
if (printCell == null) return;
PrinterJob pj = PrinterJob.getPrinterJob();
pj.setJobName("Cell "+printCell.describe());
ElectricPrinter ep = new ElectricPrinter();
ep.setPrintCell(printCell);
pj.setPrintable(ep);
// see if a default printer should be mentioned
String pName = Output.getPrinterName();
PrintService [] printers = PrintServiceLookup.lookupPrintServices(null, null);
PrintService printerToUse = null;
for(int i=0; i<printers.length; i++)
{
if (pName.equals(printers[i].getName()))
{
printerToUse = printers[i];
break;
}
}
if (printerToUse != null)
{
try
{
pj.setPrintService(printerToUse);
} catch (PrinterException e)
{
}
}
if (pj.printDialog())
{
printerToUse = pj.getPrintService();
if (printerToUse != null)
Output.setPrinterName(printerToUse.getName());
PrintJob job = new PrintJob(printCell, pj);
}
}
/**
* Class to print a cell in a new thread.
*/
private static class PrintJob extends Job
{
Cell cell;
PrinterJob pj;
public PrintJob(Cell cell, PrinterJob pj)
{
super("Print "+cell.describe(), User.tool, Job.Type.EXAMINE, null, null, Job.Priority.USER);
this.cell = cell;
this.pj = pj;
startJob();
}
public boolean doIt()
{
try {
pj.print();
} catch (PrinterException pe)
{
System.out.println("Print aborted.");
}
return true;
}
}
static class ElectricPrinter implements Printable
{
private Cell printCell;
private Image img = null;
public void setPrintCell(Cell printCell) { this.printCell = printCell; }
public int print(Graphics g, PageFormat pageFormat, int page)
throws java.awt.print.PrinterException
{
if (page != 0) return Printable.NO_SUCH_PAGE;
// create an EditWindow for rendering this cell
if (img == null)
{
EditWindow w = EditWindow.CreateElectricDoc(null, null);
int iw = (int)pageFormat.getImageableWidth();
int ih = (int)pageFormat.getImageableHeight();
w.setScreenSize(new Dimension(iw, ih));
w.setCell(printCell, VarContext.globalContext);
PixelDrawing offscreen = w.getOffscreen();
offscreen.setBackgroundColor(Color.WHITE);
offscreen.drawImage();
img = offscreen.getImage();
}
// copy the image to the page
int ix = (int)pageFormat.getImageableX();
int iy = (int)pageFormat.getImageableY();
g.drawImage(img, ix, iy, null);
return Printable.PAGE_EXISTS;
}
}
/**
* This method implements the command to quit Electric.
*/
public static boolean quitCommand()
{
if (preventLoss(null, 0)) return (false);
QuitJob job = new QuitJob();
return (true);
}
/**
* Class to quit Electric in a new thread.
*/
private static class QuitJob extends Job
{
public QuitJob()
{
super("Quitting", User.tool, Job.Type.EXAMINE, null, null, Job.Priority.USER);
startJob();
}
public boolean doIt()
{
System.exit(0);
return true;
}
}
/**
* Method to ensure that one or more libraries are saved.
* @param desiredLib the library to check for being saved.
* If desiredLib is null, all libraries are checked.
* @param action the type of action that will occur:
* 0: quit;
* 1: close a library;
* 2: replace a library.
* @return true if the operation should be aborted;
* false to continue with the quit/close/replace.
*/
public static boolean preventLoss(Library desiredLib, int action)
{
boolean saveCancelled = false;
for(Iterator it = Library.getLibraries(); it.hasNext(); )
{
Library lib = (Library)it.next();
if (desiredLib != null && desiredLib != lib) continue;
if (lib.isHidden()) continue;
if (!lib.isChangedMajor() && !lib.isChangedMinor()) continue;
// warn about this library
String how = "significantly";
if (!lib.isChangedMajor()) how = "insignificantly";
String theAction = "Save before quitting?";
if (action == 1) theAction = "Save before closing?"; else
if (action == 2) theAction = "Save before replacing?";
String [] options = {"Yes", "No", "Cancel", "No to All"};
int ret = JOptionPane.showOptionDialog(TopLevel.getCurrentJFrame(),
"Library " + lib.getLibName() + " has changed " + how + ". " + theAction,
"Save Library?", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]);
if (ret == 0)
{
// save the library
if (!saveLibraryCommand(lib, OpenFile.Type.ELIB))
saveCancelled = true;
continue;
}
if (ret == 1) continue;
if (ret == 2) return true;
if (ret == 3) break;
}
if (saveCancelled) return true;
return false;
}
// ---------------------- THE EDIT MENU -----------------
public static void undoCommand() { new UndoCommand(); }
/**
* This class implement the command to undo the last change.
*/
private static class UndoCommand extends Job
{
private UndoCommand()
{
super("Undo", User.tool, Job.Type.UNDO, Undo.upCell(false), null, Job.Priority.USER);
startJob();
}
public boolean doIt()
{
Highlight.clear();
Highlight.finished();
if (!Undo.undoABatch())
System.out.println("Undo failed!");
return true;
}
}
public static void redoCommand() { new RedoCommand(); }
/**
* This class implement the command to undo the last change (Redo).
*/
private static class RedoCommand extends Job
{
private RedoCommand()
{
super("Redo", User.tool, Job.Type.UNDO, Undo.upCell(true), null, Job.Priority.USER);
startJob();
}
public boolean doIt()
{
Highlight.clear();
Highlight.finished();
if (!Undo.redoABatch())
System.out.println("Redo failed!");
return true;
}
}
/**
* This method implements the command to show the Key Bindings Options dialog.
*/
public static void keyBindingsCommand()
{
// edit key bindings for current menu
TopLevel top = (TopLevel)TopLevel.getCurrentJFrame();
EditKeyBindings dialog = new EditKeyBindings(top.getTheMenuBar(), top, true);
dialog.show();
}
/**
* This method shows the GetInfo dialog for the highlighted nodes, arcs, and/or text.
*/
public static void getInfoCommand()
{
if (Highlight.getNumHighlights() == 0)
{
// information about the cell
Cell c = WindowFrame.getCurrentCell();
if (c != null) c.getInfo();
} else
{
// information about the selected items
int arcCount = 0;
int nodeCount = 0;
int exportCount = 0;
int textCount = 0;
int graphicsCount = 0;
for(Iterator it = Highlight.getHighlights(); it.hasNext(); )
{
Highlight h = (Highlight)it.next();
ElectricObject eobj = h.getElectricObject();
if (h.getType() == Highlight.Type.EOBJ)
{
if (eobj instanceof NodeInst || eobj instanceof PortInst)
{
nodeCount++;
} else if (eobj instanceof ArcInst)
{
arcCount++;
}
} else if (h.getType() == Highlight.Type.TEXT)
{
if (eobj instanceof Export) exportCount++; else
textCount++;
} else if (h.getType() == Highlight.Type.BBOX)
{
graphicsCount++;
} else if (h.getType() == Highlight.Type.LINE)
{
graphicsCount++;
}
}
if (arcCount <= 1 && nodeCount <= 1 && exportCount <= 1 && textCount <= 1 && graphicsCount == 0)
{
if (arcCount == 1) GetInfoArc.showDialog();
if (nodeCount == 1) GetInfoNode.showDialog();
if (exportCount == 1) GetInfoExport.showDialog();
if (textCount == 1) GetInfoText.showDialog();
} else
{
GetInfoMulti.showDialog();
}
}
}
/**
* Method to handle the "See All Parameters on Node" command.
*/
public static void seeAllParametersCommand()
{
ParameterVisibility job = new ParameterVisibility(0);
}
/**
* Method to handle the "Hide All Parameters on Node" command.
*/
public static void hideAllParametersCommand()
{
ParameterVisibility job = new ParameterVisibility(1);
}
/**
* Method to handle the "Default Parameter Visibility" command.
*/
public static void defaultParamVisibilityCommand()
{
ParameterVisibility job = new ParameterVisibility(2);
}
/**
* Class to do antenna checking in a new thread.
*/
private static class ParameterVisibility extends Job
{
private int how;
protected ParameterVisibility(int how)
{
super("Change Parameter Visibility", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.how = how;
startJob();
}
public boolean doIt()
{
// change visibility of parameters on the current node(s)
int changeCount = 0;
List list = Highlight.getHighlighted(true, false);
for(Iterator it = list.iterator(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
if (!(ni.getProto() instanceof Cell)) continue;
boolean changed = false;
for(Iterator vIt = ni.getVariables(); vIt.hasNext(); )
{
Variable var = (Variable)vIt.next();
Variable nVar = findParameterSource(var, ni);
if (nVar == null) continue;
switch (how)
{
case 0: // make all parameters visible
if (var.isDisplay()) continue;
var.setDisplay();
changed = true;
break;
case 1: // make all parameters invisible
if (!var.isDisplay()) continue;
var.clearDisplay();
changed = true;
break;
case 2: // make all parameters have default visiblity
if (nVar.getTextDescriptor().isInterior())
{
// prototype wants parameter to be invisible
if (!var.isDisplay()) continue;
var.clearDisplay();
changed = true;
} else
{
// prototype wants parameter to be visible
if (var.isDisplay()) continue;
var.setDisplay();
changed = true;
}
break;
}
}
if (changed)
{
Undo.redrawObject(ni);
changeCount++;
}
}
if (changeCount == 0) System.out.println("No Parameter visibility changed"); else
System.out.println("Changed visibility on " + changeCount + " nodes");
return true;
}
}
/**
* Method to find the formal parameter that corresponds to the actual parameter
* "var" on node "ni". Returns null if not a parameter or cannot be found.
*/
private static Variable findParameterSource(Variable var, NodeInst ni)
{
// find this parameter in the cell
Cell np = (Cell)ni.getProto();
Cell cnp = np.contentsView();
if (cnp != null) np = cnp;
for(Iterator it = np.getVariables(); it.hasNext(); )
{
Variable nVar = (Variable)it.next();
if (var.getKey() == nVar.getKey()) return nVar;
}
return null;
}
/**
* Method to handle the "List Layer Coverage" command.
*/
public static void layerCoverageCommand(boolean test)
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
Job job = new LayerCoverage(curCell, test);
}
private static class LayerCoverage extends Job
{
private Cell curCell;
private boolean testCase;
PolyQTree tree = new PolyQTree();
public static class LayerVisitor extends HierarchyEnumerator.Visitor
{
private boolean testCase;
private PolyQTree tree;
private AffineTransform transformation;
public LayerVisitor(boolean test, PolyQTree t)
{
this.testCase = test;
this.tree = t;
}
public void exitCell(HierarchyEnumerator.CellInfo info)
{
//return true;
}
public boolean enterCell(HierarchyEnumerator.CellInfo info)
{
Cell curCell = info.getCell();
// Traversing arcs
for (Iterator it = curCell.getArcs(); it.hasNext(); )
{
ArcInst arc = (ArcInst)it.next();
ArcProto arcType = arc.getProto();
Technology tech = arcType.getTechnology();
Poly[] polyList = tech.getShapeOfArc(arc);
// Treating the arcs associated to each node
// Arcs don't need to be rotated
for (int i = 0; i < polyList.length; i++)
{
Poly poly = polyList[i];
Layer layer = poly.getLayer();
Layer.Function func = layer.getFunction();
if (!testCase && !func.isPoly() && !func.isMetal()) continue;
tree.insert((Object)layer, curCell.getBounds(), new PolyQTree.PolyNode(poly));
}
}
// Traversing nodes
for (Iterator it = curCell.getNodes(); it.hasNext(); )
{
NodeInst node = (NodeInst)it .next();
// Coverage implants are pure primitive nodes
// and they are ignored.
if (!testCase && node.getFunction() == NodeProto.Function.NODE) continue;
NodeProto protoType = node.getProto();
// Analyzing only leaves
if (!(protoType instanceof Cell))
{
Technology tech = protoType.getTechnology();
Poly[] polyList = tech.getShapeOfNode(node);
AffineTransform transform = node.rotateOut();
for (int i = 0; i < polyList.length; i++)
{
Poly poly = polyList[i];
Layer layer = poly.getLayer();
Layer.Function func = layer.getFunction();
// Only checking poly or metal
if (!testCase && !func.isPoly() && !func.isMetal()) continue;
poly.transform(transform);
poly.transform(info.getTransformToRoot());
tree.insert((Object)layer, curCell.getBounds(), new PolyQTree.PolyNode(poly));
}
}
}
return true;
}
public boolean visitNodeInst(Nodable no, HierarchyEnumerator.CellInfo info)
{
return true;
}
}
protected LayerCoverage(Cell cell, boolean test)
{
super("Layer Coverage", User.tool, Job.Type.EXAMINE, null, null, Job.Priority.USER);
this.curCell = cell;
this.testCase = test;
setReportExecutionFlag(true);
startJob();
}
public boolean doIt()
{
// enumerate the hierarchy below here
LayerVisitor visitor = new LayerVisitor(testCase, tree);
HierarchyEnumerator.enumerateCell(curCell, VarContext.globalContext, null, visitor);
double lambdaSqr = 1;
// @todo GVG Calculates lambda!
Rectangle2D bbox = curCell.getBounds();
double totalArea = (bbox.getHeight()*bbox.getWidth())/lambdaSqr;
// Traversing tree with merged geometry
for (Iterator it = tree.getKeyIterator(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
Set set = tree.getObjects(layer, false);
double layerArea = 0;
// Get all objects and sum the area
for (Iterator i = set.iterator(); i.hasNext(); )
{
PolyQTree.PolyNode area = (PolyQTree.PolyNode)i.next();
layerArea += area.getArea();
}
System.out.println("Layer " + layer.getName() + " covers " + TextUtils.formatDouble(layerArea) + " square lambda (" + TextUtils.formatDouble((layerArea/totalArea)*100, 0) + "%)");
}
System.out.println("Cell is " + TextUtils.formatDouble(totalArea) + " square lambda");
return true;
}
// // initialize for analysis
// us_coveragetech = cell->tech;
//
// // determine which layers are being collected
// us_coveragelayercount = 0;
// for(i=0; i<us_coveragetech->layercount; i++)
// {
// fun = layerfunction(us_coveragetech, i);
// if ((fun&LFPSEUDO) != 0) continue;
// if (!layerismetal(fun) && !layerispoly(fun)) continue;
// us_coveragelayercount++;
// }
// if (us_coveragelayercount == 0)
// {
// ttyputerr(_("No metal or polysilicon layers in this technology"));
// return;
// }
// us_coveragelayers = (INTBIG *)emalloc(us_coveragelayercount * SIZEOFINTBIG, us_tool->cluster);
// if (us_coveragelayers == 0) return;
// us_coveragelayercount = 0;
// for(i=0; i<us_coveragetech->layercount; i++)
// {
// fun = layerfunction(us_coveragetech, i);
// if ((fun&LFPSEUDO) != 0) continue;
// if (!layerismetal(fun) && !layerispoly(fun)) continue;
// us_coveragelayers[us_coveragelayercount++] = i;
// }
//
// // show the progress dialog
// us_coveragedialog = DiaInitProgress(_("Merging geometry..."), 0);
// if (us_coveragedialog == 0)
// {
// termerrorlogging(TRUE);
// return;
// }
// DiaSetProgress(us_coveragedialog, 0, 1);
//
// // reset merging information
// for(lib = el_curlib; lib != NOLIBRARY; lib = lib->nextlibrary)
// {
// for(np = lib->firstnodeproto; np != NONODEPROTO; np = np->nextnodeproto)
// {
// np->temp1 = 0;
//
// // if this cell has parameters, force its polygons to be examined for every instance
// for(i=0; i<np->numvar; i++)
// {
// var = &np->firstvar[i];
// if (TDGETISPARAM(var->textdescript) != 0) break;
// }
// if (i < np->numvar) np->temp1 = -1;
// }
// }
//
// // run through the work and count the number of polygons
// us_coveragepolyscrunched = 0;
// us_gathercoveragegeometry(cell, el_matid, 0);
// us_coveragejobsize = us_coveragepolyscrunched;
//
// // now gather all of the geometry into the polygon merging system
// polymerge = (void **)emalloc(us_coveragelayercount * (sizeof (void *)), us_tool->cluster);
// if (polymerge == 0) return;
// for(i=0; i<us_coveragelayercount; i++)
// polymerge[i] = mergenew(us_tool->cluster);
// us_coveragepolyscrunched = 0;
// us_gathercoveragegeometry(cell, el_matid, polymerge);
//
// // extract the information
// us_coveragearea = (float *)emalloc(us_coveragelayercount * (sizeof (float)), us_tool->cluster);
// if (us_coveragearea == 0) return;
// for(i=0; i<us_coveragelayercount; i++)
// {
// us_coveragearea[i] = 0.0;
// mergeextract(polymerge[i], us_getcoveragegeometry);
// }
//
// // show the results
// totalarea = (float)(cell->highx - cell->lowx);
// totalarea *= (float)(cell->highy - cell->lowy);
// ttyputmsg(x_("Cell is %g square lambda"), totalarea/(float)lambda/(float)lambda);
// for(i=0; i<us_coveragelayercount; i++)
// {
// if (us_coveragearea[i] == 0.0) continue;
// if (totalarea == 0.0) coverageratio = 0.0; else
// coverageratio = us_coveragearea[i] / totalarea;
// percentcoverage = (INTBIG)(coverageratio * 100.0 + 0.5);
//
// ttyputmsg(x_("Layer %s covers %g square lambda (%ld%%)"),
// layername(us_coveragetech, us_coveragelayers[i]),
// us_coveragearea[i]/(float)lambda/(float)lambda, percentcoverage);
// }
//
// // delete merge information
// for(lib = el_curlib; lib != NOLIBRARY; lib = lib->nextlibrary)
// {
// for(np = lib->firstnodeproto; np != NONODEPROTO; np = np->nextnodeproto)
// {
// if (np->temp1 == 0 || np->temp1 == -1) continue;
// submerge = (void **)np->temp1;
// for(i=0; i<us_coveragelayercount; i++)
// mergedelete(submerge[i]);
// efree((CHAR *)submerge);
// }
// }
// for(i=0; i<us_coveragelayercount; i++)
// mergedelete(polymerge[i]);
// efree((CHAR *)polymerge);
}
/**
* This method implements the command to highlight all objects in the current Cell.
*/
public static void selectAllCommand()
{
doSelection(false, false);
}
/**
* This method implements the command to highlight all objects in the current Cell
* that are easy to select.
*/
public static void selectEasyCommand()
{
doSelection(true, false);
}
/**
* This method implements the command to highlight all objects in the current Cell
* that are hard to select.
*/
public static void selectHardCommand()
{
doSelection(false, true);
}
private static void doSelection(boolean mustBeEasy, boolean mustBeHard)
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
boolean cellsAreHard = !User.isEasySelectionOfCellInstances();
Highlight.clear();
for(Iterator it = curCell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
boolean hard = ni.isHardSelect();
if ((ni.getProto() instanceof Cell) && cellsAreHard) hard = true;
if (mustBeEasy && hard) continue;
if (mustBeHard && !hard) continue;
if (ni.isInvisiblePinWithText())
{
for(Iterator vIt = ni.getVariables(); vIt.hasNext(); )
{
Variable var = (Variable)vIt.next();
if (var.isDisplay())
{
Highlight.addText(ni, curCell, var, null);
break;
}
}
} else
{
Highlight.addElectricObject(ni, curCell);
}
}
for(Iterator it = curCell.getArcs(); it.hasNext(); )
{
ArcInst ai = (ArcInst)it.next();
boolean hard = ai.isHardSelect();
if (mustBeEasy && hard) continue;
if (mustBeHard && !hard) continue;
Highlight.addElectricObject(ai, curCell);
}
Highlight.finished();
}
/**
* This method implements the command to highlight all objects in the current Cell
* that are like the currently selected object.
*/
public static void selectAllLikeThisCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
HashMap likeThis = new HashMap();
List highlighted = Highlight.getHighlighted(true, true);
for(Iterator it = highlighted.iterator(); it.hasNext(); )
{
Geometric geom = (Geometric)it.next();
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
likeThis.put(ni.getProto(), ni);
} else
{
ArcInst ai = (ArcInst)geom;
likeThis.put(ai.getProto(), ai);
}
}
Highlight.clear();
for(Iterator it = curCell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
Object isLikeThis = likeThis.get(ni.getProto());
if (isLikeThis == null) continue;
if (ni.isInvisiblePinWithText())
{
for(Iterator vIt = ni.getVariables(); vIt.hasNext(); )
{
Variable var = (Variable)vIt.next();
if (var.isDisplay())
{
Highlight.addText(ni, curCell, var, null);
break;
}
}
} else
{
Highlight.addElectricObject(ni, curCell);
}
}
for(Iterator it = curCell.getArcs(); it.hasNext(); )
{
ArcInst ai = (ArcInst)it.next();
Object isLikeThis = likeThis.get(ai.getProto());
if (isLikeThis == null) continue;
Highlight.addElectricObject(ai, curCell);
}
Highlight.finished();
}
/**
* This method implements the command to highlight nothing in the current Cell.
*/
public static void selectNothingCommand()
{
Highlight.clear();
Highlight.finished();
}
/**
* This method implements the command to deselect all selected arcs.
*/
public static void deselectAllArcsCommand()
{
List newHighList = new ArrayList();
for(Iterator it = Highlight.getHighlights(); it.hasNext(); )
{
Highlight h = (Highlight)it.next();
if (h.getType() == Highlight.Type.EOBJ || h.getType() == Highlight.Type.TEXT)
{
if (h.getElectricObject() instanceof ArcInst) continue;
}
newHighList.add(h);
}
Highlight.clear();
Highlight.setHighlightList(newHighList);
Highlight.finished();
}
/**
* This method implements the command to make all selected objects be easy-to-select.
*/
public static void selectMakeEasyCommand()
{
List highlighted = Highlight.getHighlighted(true, true);
for(Iterator it = highlighted.iterator(); it.hasNext(); )
{
Geometric geom = (Geometric)it.next();
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
ni.clearHardSelect();
} else
{
ArcInst ai = (ArcInst)geom;
ai.clearHardSelect();
}
}
}
/**
* This method implements the command to make all selected objects be hard-to-select.
*/
public static void selectMakeHardCommand()
{
List highlighted = Highlight.getHighlighted(true, true);
for(Iterator it = highlighted.iterator(); it.hasNext(); )
{
Geometric geom = (Geometric)it.next();
if (geom instanceof NodeInst)
{
NodeInst ni = (NodeInst)geom;
ni.setHardSelect();
} else
{
ArcInst ai = (ArcInst)geom;
ai.setHardSelect();
}
}
}
/**
* This method implements the command to replace the rectangular highlight
* with the selection of objects in that rectangle.
*/
public static void selectEnclosedObjectsCommand()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Rectangle2D selection = Highlight.getHighlightedArea(wnd);
Highlight.clear();
Highlight.selectArea(wnd, selection.getMinX(), selection.getMaxX(), selection.getMinY(), selection.getMaxY(), false,
ToolBar.getSelectSpecial());
Highlight.finished();
}
/**
* This method implements the command to show the next logged error.
* The error log lists the results of the latest command (DRC, NCC, etc.)
*/
public static void showNextErrorCommand()
{
String msg = ErrorLog.reportNextError();
System.out.println(msg);
}
/**
* This method implements the command to show the last logged error.
* The error log lists the results of the latest command (DRC, NCC, etc.)
*/
public static void showPrevErrorCommand()
{
String msg = ErrorLog.reportPrevError();
System.out.println(msg);
}
// ---------------------- THE CELL MENU -----------------
/**
* This method implements the command to do cell options.
*/
public static void cellControlCommand()
{
CellOptions dialog = new CellOptions(TopLevel.getCurrentJFrame(), true);
dialog.show();
}
/**
* This command opens a dialog box to edit a Cell.
*/
public static void newCellCommand()
{
NewCell dialog = new NewCell(TopLevel.getCurrentJFrame(), true);
dialog.show();
}
public static void cellBrowserCommand(CellBrowser.DoAction action)
{
CellBrowser dialog = new CellBrowser(TopLevel.getCurrentJFrame(), true, action);
dialog.show();
}
/**
* This method implements the command to delete the current Cell.
*/
public static void deleteCellCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
CircuitChanges.deleteCell(curCell, true);
}
/**
* This method implements the command to do cross-library copies.
*/
public static void crossLibraryCopyCommand()
{
CrossLibCopy dialog = new CrossLibCopy(TopLevel.getCurrentJFrame(), true);
dialog.show();
}
/**
* This command pushes down the hierarchy
*/
public static void downHierCommand() {
EditWindow curEdit = EditWindow.needCurrent();
curEdit.downHierarchy();
}
/**
* This command goes up the hierarchy
*/
public static void upHierCommand() {
EditWindow curEdit = EditWindow.needCurrent();
curEdit.upHierarchy();
}
/**
* This method implements the command to make a new version of the current Cell.
*/
public static void newCellVersionCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
CircuitChanges.newVersionOfCell(curCell);
}
/**
* This method implements the command to make a copy of the current Cell.
*/
public static void duplicateCellCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
String newName = JOptionPane.showInputDialog(TopLevel.getCurrentJFrame(), "Name of duplicated cell",
curCell.getProtoName() + "NEW");
if (newName == null) return;
CircuitChanges.duplicateCell(curCell, newName);
}
/**
* This method implements the command to delete old, unused versions of cells.
*/
public static void deleteOldCellVersionsCommand()
{
CircuitChanges.deleteUnusedOldVersions();
}
/**
* This method implements the command to do cell parameters.
*/
public static void cellParametersCommand()
{
CellParameters dialog = new CellParameters(TopLevel.getCurrentJFrame(), true);
dialog.show();
}
/**
* This method implements the command to expand the selected cells by 1 level down.
*/
public static void expandOneLevelDownCommand()
{
List list = Highlight.getHighlighted(true, false);
CircuitChanges.ExpandUnExpand job = new CircuitChanges.ExpandUnExpand(list, false, 1);
}
/**
* This method implements the command to expand the selected cells all the way to the bottom of the hierarchy.
*/
public static void expandFullCommand()
{
List list = Highlight.getHighlighted(true, false);
CircuitChanges.ExpandUnExpand job = new CircuitChanges.ExpandUnExpand(list, false, Integer.MAX_VALUE);
}
/**
* This method implements the command to expand the selected cells by a given number of levels from the top.
*/
public static void expandSpecificCommand()
{
Object obj = JOptionPane.showInputDialog("Number of levels to expand", "1");
int levels = TextUtils.atoi((String)obj);
List list = Highlight.getHighlighted(true, false);
CircuitChanges.ExpandUnExpand job = new CircuitChanges.ExpandUnExpand(list, false, levels);
}
/**
* This method implements the command to unexpand the selected cells by 1 level up.
*/
public static void unexpandOneLevelUpCommand()
{
List list = Highlight.getHighlighted(true, false);
CircuitChanges.ExpandUnExpand job = new CircuitChanges.ExpandUnExpand(list, true, 1);
}
/**
* This method implements the command to unexpand the selected cells all the way from the bottom of the hierarchy.
*/
public static void unexpandFullCommand()
{
List list = Highlight.getHighlighted(true, false);
CircuitChanges.ExpandUnExpand job = new CircuitChanges.ExpandUnExpand(list, true, Integer.MAX_VALUE);
}
/**
* This method implements the command to unexpand the selected cells by a given number of levels from the bottom.
*/
public static void unexpandSpecificCommand()
{
Object obj = JOptionPane.showInputDialog("Number of levels to unexpand", "1");
int levels = TextUtils.atoi((String)obj);
List list = Highlight.getHighlighted(true, false);
CircuitChanges.ExpandUnExpand job = new CircuitChanges.ExpandUnExpand(list, true, levels);
}
// ---------------------- THE VIEW MENU -----------------
/**
* This method implements the command to control Views.
*/
public static void viewControlCommand()
{
ViewControl dialog = new ViewControl(TopLevel.getCurrentJFrame(), true);
dialog.show();
}
public static void changeViewCommand()
{
Cell cell = WindowFrame.getCurrentCell();
if (cell == null) return;
List views = View.getOrderedViews();
String [] viewNames = new String[views.size()];
for(int i=0; i<views.size(); i++)
viewNames[i] = ((View)views.get(i)).getFullName();
Object newName = JOptionPane.showInputDialog(TopLevel.getCurrentJFrame(), "New view for this cell",
"Choose alternate view", JOptionPane.QUESTION_MESSAGE, null, viewNames, cell.getView().getFullName());
if (newName == null) return;
String newViewName = (String)newName;
View newView = View.findView(newViewName);
if (newView != null && newView != cell.getView())
{
CircuitChanges.changeCellView(cell, newView);
}
}
public static void editLayoutViewCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
Cell layoutView = curCell.otherView(View.LAYOUT);
if (layoutView != null)
WindowFrame.createEditWindow(layoutView);
}
public static void editSchematicViewCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
Cell schematicView = curCell.otherView(View.SCHEMATIC);
if (schematicView != null)
WindowFrame.createEditWindow(schematicView);
}
public static void editMultiPageSchematicViewCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
String newSchematicPage = JOptionPane.showInputDialog("Page Number", "");
if (newSchematicPage == null) return;
int pageNo = TextUtils.atoi(newSchematicPage);
if (pageNo <= 0)
{
System.out.println("Multi-page schematics are numbered starting at page 1");
return;
}
View v = View.findMultiPageSchematicView(pageNo);
if (v != null)
{
Cell otherView = curCell.otherView(v);
if (otherView != null)
{
WindowFrame.createEditWindow(otherView);
return;
}
}
System.out.println("Cannot find schematic page " + pageNo + " of this cell");
}
public static void editIconViewCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
Cell iconView = curCell.otherView(View.ICON);
if (iconView != null)
WindowFrame.createEditWindow(iconView);
}
public static void editVHDLViewCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
Cell vhdlView = curCell.otherView(View.VHDL);
if (vhdlView != null)
WindowFrame.createEditWindow(vhdlView);
}
public static void editDocViewCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
Cell docView = curCell.otherView(View.DOC);
if (docView != null)
WindowFrame.createEditWindow(docView);
}
public static void editSkeletonViewCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
Cell skelView = curCell.otherView(View.LAYOUTSKEL);
if (skelView != null)
WindowFrame.createEditWindow(skelView);
}
public static void editOtherViewCommand()
{
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
List views = View.getOrderedViews();
String [] viewNames = new String[views.size()];
for(int i=0; i<views.size(); i++)
viewNames[i] = ((View)views.get(i)).getFullName();
Object newName = JOptionPane.showInputDialog(TopLevel.getCurrentJFrame(), "Which associated view do you want to see?",
"Choose alternate view", JOptionPane.QUESTION_MESSAGE, null, viewNames, curCell.getView().getFullName());
if (newName == null) return;
String newViewName = (String)newName;
View newView = View.findView(newViewName);
Cell otherView = curCell.otherView(newView);
if (otherView != null)
WindowFrame.createEditWindow(otherView);
}
// ---------------------- THE WINDOW MENU -----------------
public static void fullDisplay()
{
// get the current frame
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
if (wf == null) return;
// make the circuit fill the window
wf.getContent().fillScreen();
}
public static void zoomOutDisplay()
{
// get the current frame
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
if (wf == null) return;
// zoom out
wf.getContent().zoomOutContents();
}
public static void zoomInDisplay()
{
// get the current frame
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
if (wf == null) return;
// zoom in
wf.getContent().zoomInContents();
}
public static void zoomBoxCommand()
{
// only works with click zoom wire listener
EventListener oldListener = WindowFrame.getListener();
WindowFrame.setListener(ClickZoomWireListener.theOne);
ClickZoomWireListener.theOne.zoomBoxSingleShot(oldListener);
}
/**
* Method to make the current window's grid be just visible.
* If it is zoomed-out beyond grid visibility, it is zoomed-in so that the grid is shown.
* If it is zoomed-in such that the grid is not at minimum pitch,
* it is zoomed-out so that the grid is barely able to fit.
*/
public static void makeGridJustVisibleCommand()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Rectangle2D displayable = wnd.displayableBounds();
Dimension sz = wnd.getSize();
double scaleX = wnd.getGridXSpacing() * sz.width / 5 / displayable.getWidth();
double scaleY = wnd.getGridYSpacing() * sz.height / 5 / displayable.getHeight();
double scale = Math.min(scaleX, scaleY);
wnd.setScale(wnd.getScale() / scale);
wnd.repaintContents();
}
/**
* Method to zoom the current window so that its scale matches that of the "other" window.
* For this to work, there must be exactly one other window shown.
*/
public static void matchOtherWindowCommand()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
int numOthers = 0;
EditWindow other = null;
for(Iterator it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
if (wf.getContent() instanceof EditWindow)
{
EditWindow wfWnd = (EditWindow)wf.getContent();
if (wfWnd == wnd) continue;
numOthers++;
other = wfWnd;
}
}
if (numOthers != 1)
{
System.out.println("There must be exactly two windows in order for one to match the other");
return;
}
wnd.setScale(other.getScale());
wnd.repaintContents();
}
public static void focusOnHighlighted()
{
// get the current frame
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
if (wf == null) return;
// focus on highlighted
wf.getContent().focusOnHighlighted();
}
/**
* This method implements the command to toggle the display of the grid.
*/
public static void toggleGridCommand()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
wnd.setGrid(!wnd.isGrid());
}
/**
* This method implements the command to tile the windows horizontally.
*/
public static void tileHorizontallyCommand()
{
// get the overall area in which to work
Rectangle tileArea = getWindowArea();
// tile the windows in this area
int numWindows = WindowFrame.getNumWindows();
int windowHeight = tileArea.height / numWindows;
int i=0;
for(Iterator it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
Rectangle windowArea = new Rectangle(tileArea.x, tileArea.y + i*windowHeight, tileArea.width, windowHeight);
i++;
wf.setWindowSize(windowArea);
}
}
/**
* This method implements the command to tile the windows vertically.
*/
public static void tileVerticallyCommand()
{
// get the overall area in which to work
Rectangle tileArea = getWindowArea();
// tile the windows in this area
int numWindows = WindowFrame.getNumWindows();
int windowWidth = tileArea.width / numWindows;
int i=0;
for(Iterator it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
Rectangle windowArea = new Rectangle(tileArea.x + i*windowWidth, tileArea.y, windowWidth, tileArea.height);
i++;
wf.setWindowSize(windowArea);
}
}
/**
* This method implements the command to tile the windows cascaded.
*/
public static void cascadeWindowsCommand()
{
// cascade the windows in this area
int numWindows = WindowFrame.getNumWindows();
if (numWindows <= 1)
{
tileVerticallyCommand();
return;
}
// get the overall area in which to work
Rectangle tileArea = getWindowArea();
int windowWidth = tileArea.width * 3 / 4;
int windowHeight = tileArea.height * 3 / 4;
int windowSpacing = Math.min(tileArea.width - windowWidth, tileArea.height - windowHeight) / (numWindows-1);
int numRuns = 1;
if (windowSpacing < 70)
{
numRuns = 70 / windowSpacing;
if (70 % windowSpacing != 0) numRuns++;
windowSpacing *= numRuns;
}
int windowXSpacing = (tileArea.width - windowWidth) / (numWindows-1) * numRuns;
int windowYSpacing = (tileArea.height - windowHeight) / (numWindows-1) * numRuns;
int i=0;
for(Iterator it = WindowFrame.getWindows(); it.hasNext(); )
{
WindowFrame wf = (WindowFrame)it.next();
int index = i / numRuns;
Rectangle windowArea = new Rectangle(tileArea.x + index*windowXSpacing,
tileArea.y + index*windowYSpacing, windowWidth, windowHeight);
i++;
wf.setWindowSize(windowArea);
}
}
private static Rectangle getWindowArea()
{
// get the overall area in which to work
Dimension sz = TopLevel.getScreenSize();
Rectangle tileArea = new Rectangle(sz);
// remove the tool palette
PaletteFrame pf = TopLevel.getPaletteFrame();
Rectangle pb = pf.getPaletteLocation();
removeOccludingRectangle(tileArea, pb);
// remove the messages window
MessagesWindow mw = TopLevel.getMessagesWindow();
Rectangle mb = mw.getMessagesLocation();
removeOccludingRectangle(tileArea, mb);
return tileArea;
}
private static void removeOccludingRectangle(Rectangle screen, Rectangle occluding)
{
int lX = (int)screen.getMinX();
int hX = (int)screen.getMaxX();
int lY = (int)screen.getMinY();
int hY = (int)screen.getMaxY();
if (occluding.width > occluding.height)
{
// horizontally occluding window
if (occluding.getMaxY() - lY < hY - occluding.getMinY())
{
// occluding window on top
lY = (int)occluding.getMaxY();
} else
{
// occluding window on bottom
hY = (int)occluding.getMinY();
}
} else
{
if (occluding.getMaxX() - lX < hX - occluding.getMinX())
{
// occluding window on left
lX = (int)occluding.getMaxX();
} else
{
// occluding window on right
hX = (int)occluding.getMinX();
}
}
screen.width = hX - lX; screen.height = hY - lY;
screen.x = lX; screen.y = lY;
}
/**
* This method implements the command to control Layer visibility.
*/
public static void layerVisibilityCommand()
{
LayerVisibility dialog = new LayerVisibility(TopLevel.getCurrentJFrame(), false);
dialog.show();
}
/**
* This method implements the command to set default colors.
*/
public static void defaultBackgroundCommand()
{
User.setColorBackground(Color.LIGHT_GRAY.getRGB());
User.setColorGrid(Color.BLACK.getRGB());
User.setColorHighlight(Color.WHITE.getRGB());
User.setColorPortHighlight(Color.YELLOW.getRGB());
User.setColorText(Color.BLACK.getRGB());
User.setColorInstanceOutline(Color.BLACK.getRGB());
EditWindow.repaintAllContents();
TopLevel.getPaletteFrame().loadForTechnology();
}
/**
* This method implements the command to set colors so that there is a black background.
*/
public static void blackBackgroundCommand()
{
User.setColorBackground(Color.BLACK.getRGB());
User.setColorGrid(Color.WHITE.getRGB());
User.setColorHighlight(Color.RED.getRGB());
User.setColorPortHighlight(Color.YELLOW.getRGB());
User.setColorText(Color.WHITE.getRGB());
User.setColorInstanceOutline(Color.WHITE.getRGB());
EditWindow.repaintAllContents();
TopLevel.getPaletteFrame().loadForTechnology();
}
/**
* This method implements the command to set colors so that there is a white background.
*/
public static void whiteBackgroundCommand()
{
User.setColorBackground(Color.WHITE.getRGB());
User.setColorGrid(Color.BLACK.getRGB());
User.setColorHighlight(Color.RED.getRGB());
User.setColorPortHighlight(Color.DARK_GRAY.getRGB());
User.setColorText(Color.BLACK.getRGB());
User.setColorInstanceOutline(Color.BLACK.getRGB());
EditWindow.repaintAllContents();
TopLevel.getPaletteFrame().loadForTechnology();
}
public static void moveToOtherDisplayCommand()
{
// this only works in SDI mode
if (TopLevel.isMDIMode()) return;
// find current screen
WindowFrame curWF = WindowFrame.getCurrentWindowFrame();
WindowContent content = curWF.getContent();
GraphicsConfiguration curConfig = content.getPanel().getGraphicsConfiguration();
GraphicsDevice curDevice = curConfig.getDevice();
// get all screens
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
// find screen after current screen
int i;
for (i=0; i<gs.length; i++) {
if (gs[i] == curDevice) break;
}
if (i == (gs.length - 1)) i = 0; else i++; // go to next device
curWF.moveEditWindow(gs[i].getDefaultConfiguration());
}
// ---------------------- THE TOOLS MENU -----------------
// Logical Effort Tool
public static void optimizeEqualGateDelaysCommand()
{
EditWindow curEdit = EditWindow.needCurrent();
if (curEdit == null) return;
LETool letool = LETool.getLETool();
if (letool == null) {
System.out.println("Logical Effort tool not found");
return;
}
// set current cell to use global context
curEdit.setCell(curEdit.getCell(), VarContext.globalContext);
// optimize cell for equal gate delays
letool.optimizeEqualGateDelays(curEdit.getCell(), curEdit.getVarContext(), curEdit);
}
/** Print Logical Effort info for highlighted nodes */
public static void printLEInfoCommand() {
if (Highlight.getNumHighlights() == 0) {
System.out.println("Nothing highlighted");
return;
}
for (Iterator it = Highlight.getHighlights(); it.hasNext();) {
Highlight h = (Highlight)it.next();
if (h.getType() != Highlight.Type.EOBJ) continue;
ElectricObject eobj = h.getElectricObject();
if (eobj instanceof PortInst) {
PortInst pi = (PortInst)eobj;
pi.getInfo();
eobj = pi.getNodeInst();
}
if (eobj instanceof NodeInst) {
NodeInst ni = (NodeInst)eobj;
LETool.printResults(ni);
}
}
}
/**
* Method to handle the "Show Network" command.
*/
public static void showNetworkCommand()
{
Set nets = Highlight.getHighlightedNetworks();
Highlight.clear();
for(Iterator it = nets.iterator(); it.hasNext(); )
{
JNetwork net = (JNetwork)it.next();
Cell cell = net.getParent();
Highlight.addNetwork(net, cell);
}
Highlight.finished();
}
/**
* Method to handle the "List Networks" command.
*/
public static void listNetworksCommand()
{
Cell cell = WindowFrame.getCurrentCell();
if (cell == null) return;
Netlist netlist = cell.getUserNetlist();
int total = 0;
for(Iterator it = netlist.getNetworks(); it.hasNext(); )
{
JNetwork net = (JNetwork)it.next();
String netName = net.describe();
if (netName.length() == 0) continue;
StringBuffer infstr = new StringBuffer();
infstr.append("'" + netName + "'");
// if (net->buswidth > 1)
// {
// formatinfstr(infstr, _(" (bus with %d signals)"), net->buswidth);
// }
boolean connected = false;
for(Iterator aIt = net.getArcs(); aIt.hasNext(); )
{
ArcInst ai = (ArcInst)aIt.next();
if (!connected)
{
connected = true;
infstr.append(", on arcs:");
}
infstr.append(" " + ai.describe());
}
boolean exported = false;
for(Iterator eIt = net.getExports(); eIt.hasNext(); )
{
Export pp = (Export)eIt.next();
if (!exported)
{
exported = true;
infstr.append(", with exports:");
}
infstr.append(" " + pp.getProtoName());
}
System.out.println(infstr.toString());
total++;
}
if (total == 0) System.out.println("There are no networks in this cell");
}
/**
* Method to handle the "List Connections On Network" command.
*/
public static void listConnectionsOnNetworkCommand()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
Set nets = Highlight.getHighlightedNetworks();
Netlist netlist = cell.getUserNetlist();
for(Iterator it = nets.iterator(); it.hasNext(); )
{
JNetwork net = (JNetwork)it.next();
System.out.println("Network '" + net.describe() + "':");
int total = 0;
for(Iterator nIt = netlist.getNodables(); nIt.hasNext(); )
{
Nodable no = (Nodable)nIt.next();
NodeProto np = no.getProto();
HashMap portNets = new HashMap();
for(Iterator pIt = np.getPorts(); pIt.hasNext(); )
{
PortProto pp = (PortProto)pIt.next();
if (pp.isIsolated())
{
NodeInst ni = (NodeInst)no;
for(Iterator cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = (Connection)cIt.next();
ArcInst ai = con.getArc();
JNetwork oNet = netlist.getNetwork(ai, 0);
portNets.put(oNet, pp);
}
} else
{
int width = 1;
if (pp instanceof Export)
{
Export e = (Export)pp;
width = netlist.getBusWidth(e);
}
for(int i=0; i<width; i++)
{
JNetwork oNet = netlist.getNetwork(no, pp, i);
portNets.put(oNet, pp);
}
}
}
// if there is only 1 net connected, the node is unimportant
if (portNets.size() <= 1) continue;
PortProto pp = (PortProto)portNets.get(net);
if (pp == null) continue;
if (total == 0) System.out.println(" Connects to:");
String name = null;
if (no instanceof NodeInst) name = ((NodeInst)no).describe(); else
{
name = no.getName();
}
System.out.println(" Node " + name + ", port " + pp.getProtoName());
total++;
}
if (total == 0) System.out.println(" Not connected");
}
}
/**
* Method to handle the "List Exports On Network" command.
*/
public static void listExportsOnNetworkCommand()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
Set nets = Highlight.getHighlightedNetworks();
Netlist netlist = cell.getUserNetlist();
for(Iterator it = nets.iterator(); it.hasNext(); )
{
JNetwork net = (JNetwork)it.next();
System.out.println("Network '" + net.describe() + "':");
// find all exports on network "net"
FlagSet fs = Geometric.getFlagSet(1);
for(Iterator lIt = Library.getLibraries(); lIt.hasNext(); )
{
Library lib = (Library)lIt.next();
for(Iterator cIt = lib.getCells(); cIt.hasNext(); )
{
Cell oCell = (Cell)cIt.next();
for(Iterator pIt = oCell.getPorts(); pIt.hasNext(); )
{
Export pp = (Export)pIt.next();
pp.clearBit(fs);
}
}
}
System.out.println(" Going up the hierarchy from cell " + cell.describe() + ":");
findPortsUp(netlist, net, cell, fs);
System.out.println(" Going down the hierarchy from cell " + cell.describe() + ":");
findPortsDown(netlist, net, cell, fs);
fs.freeFlagSet();
}
}
/**
* Method to handle the "List Exports Below Network" command.
*/
public static void listExportsBelowNetworkCommand()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
Set nets = Highlight.getHighlightedNetworks();
Netlist netlist = cell.getUserNetlist();
for(Iterator it = nets.iterator(); it.hasNext(); )
{
JNetwork net = (JNetwork)it.next();
System.out.println("Network '" + net.describe() + "':");
// find all exports on network "net"
FlagSet fs = Geometric.getFlagSet(1);
for(Iterator lIt = Library.getLibraries(); lIt.hasNext(); )
{
Library lib = (Library)lIt.next();
for(Iterator cIt = lib.getCells(); cIt.hasNext(); )
{
Cell oCell = (Cell)cIt.next();
for(Iterator pIt = oCell.getPorts(); pIt.hasNext(); )
{
Export pp = (Export)pIt.next();
pp.clearBit(fs);
}
}
}
findPortsDown(netlist, net, cell, fs);
fs.freeFlagSet();
}
}
/**
* helper method for "telltool network list-hierarchical-ports" to print all
* ports connected to net "net" in cell "cell", and recurse up the hierarchy
*/
private static void findPortsUp(Netlist netlist, JNetwork net, Cell cell, FlagSet fs)
{
// look at every node in the cell
for(Iterator it = cell.getPorts(); it.hasNext(); )
{
Export pp = (Export)it.next();
int width = netlist.getBusWidth(pp);
for(int i=0; i<width; i++)
{
JNetwork ppNet = netlist.getNetwork(pp, i);
if (ppNet != net) continue;
if (pp.isBit(fs)) continue;
pp.setBit(fs);
System.out.println(" Export " + pp.getProtoName() + " in cell " + cell.describe());
// code to find the proper instance
Cell instanceCell = cell.iconView();
if (instanceCell == null) instanceCell = cell;
// ascend to higher cell and continue
for(Iterator uIt = instanceCell.getUsagesOf(); uIt.hasNext(); )
{
NodeUsage nu = (NodeUsage)uIt.next();
Cell superCell = nu.getParent();
Netlist superNetlist = superCell.getUserNetlist();
for(Iterator nIt = superNetlist.getNodables(); nIt.hasNext(); )
{
Nodable no = (Nodable)nIt.next();
if (no.getProto() != cell) continue;
JNetwork superNet = superNetlist.getNetwork(no, pp, i);
findPortsUp(superNetlist, superNet, superCell, fs);
}
}
}
}
}
/**
* helper method for "telltool network list-hierarchical-ports" to print all
* ports connected to net "net" in cell "cell", and recurse down the hierarchy
*/
private static void findPortsDown(Netlist netlist, JNetwork net, Cell cell, FlagSet fs)
{
// look at every node in the cell
for(Iterator it = netlist.getNodables(); it.hasNext(); )
{
Nodable no = (Nodable)it.next();
// only want complex nodes
NodeProto subnp = no.getProto();
if (!(subnp instanceof Cell)) continue;
Cell subCell = (Cell)subnp;
// look at all wires connected to the node
for(Iterator pIt = subCell.getPorts(); pIt.hasNext(); )
{
Export pp = (Export)pIt.next();
int width = netlist.getBusWidth(pp);
for(int i=0; i<width; i++)
{
JNetwork oNet = netlist.getNetwork(no, pp, i);
if (oNet != net) continue;
// found the net here: report it
if (pp.isBit(fs)) continue;
pp.setBit(fs);
System.out.println(" Export " + pp.getProtoName() + " in cell " + subCell.describe());
Netlist subNetlist = subCell.getUserNetlist();
JNetwork subNet = subNetlist.getNetwork(pp, i);
findPortsDown(subNetlist, subNet, subCell, fs);
}
}
}
}
/**
* Method to handle the "List Geometry On Network" command.
*/
public static void listGeometryOnNetworkCommand()
{
System.out.println("Can't Yet");
// /* gather geometry on this network */
// np = net->parent;
// firstarpe = net_gathergeometry(net, &p_gate, &n_gate, &p_active, &n_active, TRUE);
//
// /* copy the linked list to an array for sorting */
// total = 0;
// for(arpe = firstarpe; arpe != NOAREAPERIM; arpe = arpe->nextareaperim)
// if (arpe->layer >= 0) total++;
// if (total == 0)
// {
// ttyputmsg(_("No geometry on network '%s' in cell %s"), describenetwork(net),
// describenodeproto(np));
// return;
// }
// arpelist = (AREAPERIM **)emalloc(total * (sizeof (AREAPERIM *)), net_tool->cluster);
// if (arpelist == 0) return;
// i = 0;
// for(arpe = firstarpe; arpe != NOAREAPERIM; arpe = arpe->nextareaperim)
// if (arpe->layer >= 0) arpelist[i++] = arpe;
//
// /* sort the layers */
// esort(arpelist, total, sizeof (AREAPERIM *), net_areaperimdepthascending);
//
// ttyputmsg(_("For network '%s' in cell %s:"), describenetwork(net),
// describenodeproto(np));
// lambda = lambdaofcell(np);
// widest = 0;
// for(i=0; i<total; i++)
// {
// arpe = arpelist[i];
// lname = layername(arpe->tech, arpe->layer);
// len = estrlen(lname);
// if (len > widest) widest = len;
// }
// totalWire = 0;
// for(i=0; i<total; i++)
// {
// arpe = arpelist[i];
// lname = layername(arpe->tech, arpe->layer);
// infstr = initinfstr();
// for(j=estrlen(lname); j<widest; j++) addtoinfstr(infstr, ' ');
// pad = returninfstr(infstr);
// if (arpe->perimeter == 0)
// {
// ttyputmsg(_("Layer %s:%s area=%7g half-perimeter=%s"), lname, pad,
// arpe->area/(float)lambda/(float)lambda, latoa(arpe->perimeter/2, 0));
// } else
// {
// ratio = (arpe->area / (float)lambda) / (float)(arpe->perimeter/2);
// ttyputmsg(_("Layer %s:%s area=%7g half-perimeter=%s ratio=%g"), lname,
// pad, arpe->area/(float)lambda/(float)lambda,
// latoa(arpe->perimeter/2, lambda), ratio);
//
// /* accumulate total wire length on all metal/poly layers */
// fun = layerfunction(arpe->tech, arpe->layer);
// if ((layerispoly(fun) && !layerisgatepoly(fun)) || layerismetal(fun))
// totalWire += arpe->perimeter / 2;
// }
// efree((CHAR *)arpelist[i]);
// }
// if (totalWire > 0.0) ttyputmsg(_("Total wire length = %s"), latoa(totalWire,lambda));
}
public static void showPowerAndGround()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return;
Netlist netlist = cell.getUserNetlist();
HashSet pAndG = new HashSet();
for(Iterator it = cell.getPorts(); it.hasNext(); )
{
Export pp = (Export)it.next();
if (pp.isPower() || pp.isGround())
{
int width = netlist.getBusWidth(pp);
for(int i=0; i<width; i++)
{
JNetwork net = netlist.getNetwork(pp, i);
pAndG.add(net);
}
}
}
for(Iterator it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = (NodeInst)it.next();
NodeProto.Function fun = ni.getFunction();
if (fun != NodeProto.Function.CONPOWER && fun != NodeProto.Function.CONGROUND)
continue;
for(Iterator cIt = ni.getConnections(); cIt.hasNext(); )
{
Connection con = (Connection)cIt.next();
ArcInst ai = con.getArc();
int width = netlist.getBusWidth(ai);
for(int i=0; i<width; i++)
{
JNetwork net = netlist.getNetwork(ai, i);
pAndG.add(net);
}
}
}
Highlight.clear();
for(Iterator it = pAndG.iterator(); it.hasNext(); )
{
JNetwork net = (JNetwork)it.next();
Highlight.addNetwork(net, cell);
}
Highlight.finished();
if (pAndG.size() == 0)
System.out.println("This cell has no Power or Ground networks");
}
public static void validatePowerAndGround()
{
System.out.println("Validating power and ground networks");
int total = 0;
for(Iterator lIt = Library.getLibraries(); lIt.hasNext(); )
{
Library lib = (Library)lIt.next();
for(Iterator cIt = lib.getCells(); cIt.hasNext(); )
{
Cell cell = (Cell)cIt.next();
for(Iterator pIt = cell.getPorts(); pIt.hasNext(); )
{
Export pp = (Export)pIt.next();
if (pp.isNamedGround() && pp.getCharacteristic() != PortProto.Characteristic.GND)
{
System.out.println("Cell " + cell.describe() + ", export " + pp.getProtoName() +
": does not have 'GROUND' characteristic");
total++;
}
if (pp.isNamedPower() && pp.getCharacteristic() != PortProto.Characteristic.PWR)
{
System.out.println("Cell " + cell.describe() + ", export " + pp.getProtoName() +
": does not have 'POWER' characteristic");
total++;
}
}
}
}
if (total == 0) System.out.println("No problems found"); else
System.out.println("Found " + total + " export problems");
}
public static void redoNetworkNumberingCommand()
{
long startTime = System.currentTimeMillis();
int ncell = 0;
for(Iterator it = Library.getLibraries(); it.hasNext(); )
{
Library lib = (Library)it.next();
for(Iterator cit = lib.getCells(); cit.hasNext(); )
{
Cell cell = (Cell)cit.next();
ncell++;
cell.getNetlist(false);
}
}
long endTime = System.currentTimeMillis();
float finalTime = (endTime - startTime) / 1000F;
System.out.println("**** Renumber networks of "+ncell+" cells took " + finalTime + " seconds");
}
public static void irsimNetlistCommand()
{
EditWindow curEdit = EditWindow.needCurrent();
if (curEdit == null) return;
IRSIMTool.tool.netlistCell(curEdit.getCell(), curEdit.getVarContext(), curEdit);
}
/**
* Method to add a "M" multiplier factor to the currently selected node.
*/
public static void addMultiplierCommand()
{
NodeInst ni = (NodeInst)Highlight.getOneElectricObject(NodeInst.class);
if (ni == null) return;
AddMultiplier job = new AddMultiplier(ni);
}
private static class AddMultiplier extends Job
{
private NodeInst ni;
protected AddMultiplier(NodeInst ni)
{
super("Add Spice Multiplier", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.ni = ni;
startJob();
}
public boolean doIt()
{
Variable var = ni.newVar("ATTR_M", new Double(1.0));
if (var != null)
{
var.setDisplay();
TextDescriptor td = var.getTextDescriptor();
td.setOff(-1.5, -1);
td.setDispPart(TextDescriptor.DispPos.NAMEVALUE);
}
return true;
}
}
/**
* Method to create a new template in the current cell.
* Templates can be for SPICE or Verilog, depending on the Variable name.
* @param templateKey the name of the variable to create.
*/
public static void makeTemplate(Variable.Key templateKey)
{
MakeTemplate job = new MakeTemplate(templateKey);
}
private static class MakeTemplate extends Job
{
private Variable.Key templateKey;
protected MakeTemplate(Variable.Key templateKey)
{
super("Make template", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.templateKey = templateKey;
startJob();
}
public boolean doIt()
{
Cell cell = WindowFrame.needCurCell();
if (cell == null) return false;
Variable templateVar = cell.getVar(templateKey);
if (templateVar != null)
{
System.out.println("This cell already has a template");
return false;
}
templateVar = cell.newVar(templateKey, "*Undefined");
if (templateVar != null)
{
templateVar.setDisplay();
TextDescriptor td = templateVar.getTextDescriptor();
td.setInterior();
td.setDispPart(TextDescriptor.DispPos.NAMEVALUE);
}
return true;
}
}
public static void getUnroutedArcCommand()
{
User.tool.setCurrentArcProto(Generic.tech.unrouted_arc);
}
public static void padFrameGeneratorCommand()
{
String fileName = OpenFile.chooseInputFile(OpenFile.Type.PADARR, null);
if (fileName != null)
{
PadGenerator.generate(fileName);
}
}
public static void listToolsCommand()
{
System.out.println("Tools in Electric:");
for(Iterator it = Tool.getTools(); it.hasNext(); )
{
Tool tool = (Tool)it.next();
StringBuffer infstr = new StringBuffer();
if (tool.isOn()) infstr.append("On"); else
infstr.append("Off");
if (tool.isBackground()) infstr.append(", Background");
if (tool.isFixErrors()) infstr.append(", Correcting");
if (tool.isIncremental()) infstr.append(", Incremental");
if (tool.isAnalysis()) infstr.append(", Analysis");
if (tool.isSynthesis()) infstr.append(", Synthesis");
System.out.println(tool.getName() + ": " + infstr.toString());
}
}
public static void javaBshScriptCommand()
{
String fileName = OpenFile.chooseInputFile(OpenFile.Type.JAVA, null);
if (fileName != null)
{
// start a job to run the script
EvalJavaBsh.runScript(fileName);
}
}
// ---------------------- THE HELP MENU -----------------
public static void aboutCommand()
{
About dialog = new About(TopLevel.getCurrentJFrame(), true);
dialog.show();
}
public static void toolTipsCommand()
{
HelpViewer dialog = new HelpViewer(TopLevel.getCurrentJFrame(), false, null);
dialog.show();
}
public static void describeTechnologyCommand()
{
Technology tech = Technology.getCurrent();
System.out.println("Technology " + tech.getTechName());
System.out.println(" Full name: " + tech.getTechDesc());
if (tech.isScaleRelevant())
{
System.out.println(" Scale: 1 grid unit is " + tech.getScale() + " nanometers (" +
(tech.getScale()/1000) + " microns)");
}
int arcCount = 0;
for(Iterator it = tech.getArcs(); it.hasNext(); )
{
PrimitiveArc ap = (PrimitiveArc)it.next();
if (!ap.isNotUsed()) arcCount++;
}
StringBuffer sb = new StringBuffer();
sb.append(" Has " + arcCount + " arcs (wires):");
for(Iterator it = tech.getArcs(); it.hasNext(); )
{
PrimitiveArc ap = (PrimitiveArc)it.next();
if (ap.isNotUsed()) continue;
sb.append(" " + ap.getProtoName());
}
System.out.println(sb.toString());
int pinCount = 0, totalCount = 0, pureCount = 0, contactCount = 0;
for(Iterator it = tech.getNodes(); it.hasNext(); )
{
PrimitiveNode np = (PrimitiveNode)it.next();
if (np.isNotUsed()) continue;
NodeProto.Function fun = np.getFunction();
totalCount++;
if (fun == NodeProto.Function.PIN) pinCount++; else
if (fun == NodeProto.Function.CONTACT || fun == NodeProto.Function.CONNECT) contactCount++; else
if (fun == NodeProto.Function.NODE) pureCount++;
}
if (pinCount > 0)
{
sb = new StringBuffer();
sb.append(" Has " + pinCount + " pin nodes for making bends in arcs:");
for(Iterator it = tech.getNodes(); it.hasNext(); )
{
PrimitiveNode np = (PrimitiveNode)it.next();
if (np.isNotUsed()) continue;
NodeProto.Function fun = np.getFunction();
if (fun == NodeProto.Function.PIN) sb.append(" " + np.getProtoName());
}
System.out.println(sb.toString());
}
if (contactCount > 0)
{
sb = new StringBuffer();
sb.append(" Has " + contactCount + " contact nodes for joining different arcs:");
for(Iterator it = tech.getNodes(); it.hasNext(); )
{
PrimitiveNode np = (PrimitiveNode)it.next();
if (np.isNotUsed()) continue;
NodeProto.Function fun = np.getFunction();
if (fun == NodeProto.Function.CONTACT || fun == NodeProto.Function.CONNECT)
sb.append(" " + np.getProtoName());
}
System.out.println(sb.toString());
}
if (pinCount+contactCount+pureCount < totalCount)
{
sb = new StringBuffer();
sb.append(" Has " + (totalCount-pinCount-contactCount-pureCount) + " regular nodes:");
for(Iterator it = tech.getNodes(); it.hasNext(); )
{
PrimitiveNode np = (PrimitiveNode)it.next();
if (np.isNotUsed()) continue;
NodeProto.Function fun = np.getFunction();
if (fun != NodeProto.Function.PIN && fun != NodeProto.Function.CONTACT &&
fun != NodeProto.Function.CONNECT && fun != NodeProto.Function.NODE)
sb.append(" " + np.getProtoName());
}
System.out.println(sb.toString());
}
if (pureCount > 0)
{
sb = new StringBuffer();
sb.append(" Has " + pureCount + " pure-layer nodes for creating custom geometry:");
for(Iterator it = tech.getNodes(); it.hasNext(); )
{
PrimitiveNode np = (PrimitiveNode)it.next();
if (np.isNotUsed()) continue;
NodeProto.Function fun = np.getFunction();
if (fun == NodeProto.Function.NODE) sb.append(" " + np.getProtoName());
}
System.out.println(sb.toString());
}
}
/**
* This method implements the command to insert a jog in an arc
*/
public static void insertJogInArcCommand()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
ArcInst ai = (ArcInst)Highlight.getOneElectricObject(ArcInst.class);
if (ai == null) return;
if (CircuitChanges.cantEdit(ai.getParent(), null, true)) return;
System.out.println("Select the position in the arc to place the jog");
EventListener currentListener = WindowFrame.getListener();
WindowFrame.setListener(new InsertJogInArcListener(wnd, ai, currentListener));
}
/**
* Class to handle the interactive selection of a jog point in an arc.
*/
private static class InsertJogInArcListener
implements MouseMotionListener, MouseListener
{
private EditWindow wnd;
private ArcInst ai;
private EventListener currentListener;
/**
* Create a new insert-jog-point listener
* @param wnd Controlling window
* @param ai the arc that is having a jog inserted.
* @param currentListener listener to restore when done
*/
public InsertJogInArcListener(EditWindow wnd, ArcInst ai, EventListener currentListener)
{
this.wnd = wnd;
this.ai = ai;
this.currentListener = currentListener;
}
public void mousePressed(MouseEvent evt) {}
public void mouseClicked(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
public void mouseDragged(MouseEvent evt)
{
mouseMoved(evt);
}
public void mouseReleased(MouseEvent evt)
{
Point2D insert = getInsertPoint(evt);
InsertJogPoint job = new InsertJogPoint(ai, insert);
WindowFrame.setListener(currentListener);
}
public void mouseMoved(MouseEvent evt)
{
Point2D insert = getInsertPoint(evt);
double x = insert.getX();
double y = insert.getY();
double width = (ai.getWidth() - ai.getProto().getWidthOffset()) / 2;
Highlight.clear();
Highlight.addLine(new Point2D.Double(x-width, y-width), new Point2D.Double(x-width, y+width), ai.getParent());
Highlight.addLine(new Point2D.Double(x-width, y+width), new Point2D.Double(x+width, y+width), ai.getParent());
Highlight.addLine(new Point2D.Double(x+width, y+width), new Point2D.Double(x+width, y-width), ai.getParent());
Highlight.addLine(new Point2D.Double(x+width, y-width), new Point2D.Double(x-width, y-width), ai.getParent());
Highlight.finished();
wnd.repaint();
}
private Point2D getInsertPoint(MouseEvent evt)
{
Point2D mouseDB = wnd.screenToDatabase((int)evt.getX(), (int)evt.getY());
Point2D insert = EMath.closestPointToSegment(ai.getHead().getLocation(), ai.getTail().getLocation(), mouseDB);
EditWindow.gridAlign(insert);
return insert;
}
private static class InsertJogPoint extends Job
{
ArcInst ai;
Point2D insert;
protected InsertJogPoint(ArcInst ai, Point2D insert)
{
super("Insert Jog in Arc", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.ai = ai;
this.insert = insert;
startJob();
}
public boolean doIt()
{
// create the break pins
ArcProto ap = ai.getProto();
NodeProto np = ((PrimitiveArc)ap).findPinProto();
if (np == null) return false;
NodeInst ni = NodeInst.makeInstance(np, insert, np.getDefWidth(), np.getDefHeight(),
0, ai.getParent(), null);
if (ni == null)
{
System.out.println("Cannot create pin " + np.describe());
return false;
}
NodeInst ni2 = NodeInst.makeInstance(np, insert, np.getDefWidth(), np.getDefHeight(),
0, ai.getParent(), null);
if (ni2 == null)
{
System.out.println("Cannot create pin " + np.describe());
return false;
}
// get location of connection to these pins
PortInst pi = ni.getOnlyPortInst();
PortInst pi2 = ni2.getOnlyPortInst();
// // see if edge alignment is appropriate
// if (us_edgealignment_ratio != 0 && (ai->end[0].xpos == ai->end[1].xpos ||
// ai->end[0].ypos == ai->end[1].ypos))
// {
// edgealignment = muldiv(us_edgealignment_ratio, WHOLE, el_curlib->lambda[el_curtech->techindex]);
// px = us_alignvalue(x, edgealignment, &otheralign);
// py = us_alignvalue(y, edgealignment, &otheralign);
// if (px != x || py != y)
// {
// // shift the nodes and make sure the ports are still valid
// startobjectchange((INTBIG)ni, VNODEINST);
// modifynodeinst(ni, px-x, py-y, px-x, py-y, 0, 0);
// endobjectchange((INTBIG)ni, VNODEINST);
// startobjectchange((INTBIG)ni2, VNODEINST);
// modifynodeinst(ni2, px-x, py-y, px-x, py-y, 0, 0);
// endobjectchange((INTBIG)ni2, VNODEINST);
// (void)shapeportpoly(ni, ppt, poly, FALSE);
// if (!isinside(nx, ny, poly)) getcenter(poly, &nx, &ny);
// }
// }
// now save the arc information and delete it
PortInst headPort = ai.getHead().getPortInst();
PortInst tailPort = ai.getTail().getPortInst();
Point2D headPt = ai.getHead().getLocation();
Point2D tailPt = ai.getTail().getLocation();
double width = ai.getWidth();
boolean headNegated = ai.getHead().isNegated();
boolean tailNegated = ai.getTail().isNegated();
if (ai.isReverseEnds())
{
boolean swap = headNegated; headNegated = tailNegated; tailNegated = swap;
}
String arcName = ai.getName();
int angle = (ai.getAngle() + 900) % 3600;
ai.kill();
// create the new arcs
ArcInst newAi1 = ArcInst.makeInstance(ap, width, headPort, headPt, pi, insert, null);
if (headNegated) newAi1.getHead().setNegated(true);
ArcInst newAi2 = ArcInst.makeInstance(ap, width, pi, insert, pi2, insert, null);
ArcInst newAi3 = ArcInst.makeInstance(ap, width, pi2, insert, tailPort, tailPt, null);
if (tailNegated) newAi3.getTail().setNegated(true);
if (arcName != null)
{
if (headPt.distance(insert) > tailPt.distance(insert))
{
newAi1.setName(arcName);
} else
{
newAi3.setName(arcName);
}
}
newAi2.setAngle(angle);
// highlight one of the jog nodes
Highlight.clear();
Highlight.addElectricObject(ni, ai.getParent());
Highlight.finished();
return true;
}
}
}
/**
* This method implements the command to show the undo history.
*/
public static void showUndoListCommand()
{
Undo.showHistoryList();
}
// public static void showRTreeCommand()
// {
// Library curLib = Library.getCurrent();
// Cell curCell = curLib.getCurCell();
// System.out.println("Current cell is " + curCell.describe());
// if (curCell == null) return;
// curCell.getRTree().printRTree(0);
// }
public static void makeFakeCircuitryCommand()
{
// test code to make and show something
MakeFakeCircuitry job = new MakeFakeCircuitry();
}
/**
* Class to read a library in a new thread.
*/
private static class MakeFakeCircuitry extends Job
{
protected MakeFakeCircuitry()
{
super("Make fake circuitry", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
startJob();
}
public boolean doIt()
{
// get information about the nodes
NodeProto m1m2Proto = NodeProto.findNodeProto("mocmos:Metal-1-Metal-2-Con");
NodeProto m2PinProto = NodeProto.findNodeProto("mocmos:Metal-2-Pin");
NodeProto p1PinProto = NodeProto.findNodeProto("mocmos:Polysilicon-1-Pin");
NodeProto m1PolyConProto = NodeProto.findNodeProto("mocmos:Metal-1-Polysilicon-1-Con");
NodeProto pTransProto = NodeProto.findNodeProto("mocmos:P-Transistor");
NodeProto nTransProto = NodeProto.findNodeProto("mocmos:N-Transistor");
NodeProto cellCenterProto = NodeProto.findNodeProto("generic:Facet-Center");
NodeProto invisiblePinProto = NodeProto.findNodeProto("generic:Invisible-Pin");
// get information about the arcs
ArcProto m1Proto = ArcProto.findArcProto("mocmos:Metal-1");
ArcProto m2Proto = ArcProto.findArcProto("mocmos:Metal-2");
ArcProto p1Proto = ArcProto.findArcProto("mocmos:Polysilicon-1");
// get the current library
Library mainLib = Library.getCurrent();
// create a layout cell in the library
Cell myCell = Cell.newInstance(mainLib, "test{lay}");
NodeInst cellCenter = NodeInst.newInstance(cellCenterProto, new Point2D.Double(30.0, 30.0), cellCenterProto.getDefWidth(), cellCenterProto.getDefHeight(), 0, myCell, null);
cellCenter.setVisInside();
cellCenter.setHardSelect();
NodeInst metal12Via = NodeInst.newInstance(m1m2Proto, new Point2D.Double(-20.0, 20.0), m1m2Proto.getDefWidth(), m1m2Proto.getDefHeight(), 0, myCell, null);
NodeInst contactNode = NodeInst.newInstance(m1PolyConProto, new Point2D.Double(20.0, 20.0), m1PolyConProto.getDefWidth(), m1PolyConProto.getDefHeight(), 0, myCell, null);
NodeInst metal2Pin = NodeInst.newInstance(m2PinProto, new Point2D.Double(-20.0, 10.0), m2PinProto.getDefWidth(), m2PinProto.getDefHeight(), 0, myCell, null);
NodeInst poly1PinA = NodeInst.newInstance(p1PinProto, new Point2D.Double(20.0, -20.0), p1PinProto.getDefWidth(), p1PinProto.getDefHeight(), 0, myCell, null);
NodeInst poly1PinB = NodeInst.newInstance(p1PinProto, new Point2D.Double(20.0, -10.0), p1PinProto.getDefWidth(), p1PinProto.getDefHeight(), 0, myCell, null);
NodeInst transistor = NodeInst.newInstance(pTransProto, new Point2D.Double(0.0, -20.0), pTransProto.getDefWidth(), pTransProto.getDefHeight(), 0, myCell, null);
NodeInst rotTrans = NodeInst.newInstance(nTransProto, new Point2D.Double(0.0, 10.0), nTransProto.getDefWidth(), nTransProto.getDefHeight(), 3150, myCell, "rotated");
if (metal12Via == null || contactNode == null || metal2Pin == null || poly1PinA == null ||
poly1PinB == null || transistor == null || rotTrans == null) return false;
// make arcs to connect them
PortInst m1m2Port = metal12Via.getOnlyPortInst();
PortInst contactPort = contactNode.getOnlyPortInst();
PortInst m2Port = metal2Pin.getOnlyPortInst();
PortInst p1PortA = poly1PinA.getOnlyPortInst();
PortInst p1PortB = poly1PinB.getOnlyPortInst();
PortInst transPortR = transistor.findPortInst("p-trans-poly-right");
PortInst transRPortR = rotTrans.findPortInst("n-trans-poly-right");
ArcInst metal2Arc = ArcInst.makeInstance(m2Proto, m2Proto.getWidth(), m2Port, m1m2Port, null);
if (metal2Arc == null) return false;
metal2Arc.setRigid();
ArcInst metal1Arc = ArcInst.makeInstance(m1Proto, m1Proto.getWidth(), contactPort, m1m2Port, null);
if (metal1Arc == null) return false;
ArcInst polyArc1 = ArcInst.makeInstance(p1Proto, p1Proto.getWidth(), contactPort, p1PortB, null);
if (polyArc1 == null) return false;
ArcInst polyArc3 = ArcInst.makeInstance(p1Proto, p1Proto.getWidth(), p1PortB, p1PortA, null);
if (polyArc3 == null) return false;
ArcInst polyArc2 = ArcInst.makeInstance(p1Proto, p1Proto.getWidth(), transPortR, p1PortA, null);
if (polyArc2 == null) return false;
ArcInst polyArc4 = ArcInst.makeInstance(p1Proto, p1Proto.getWidth(), transRPortR, p1PortB, null);
if (polyArc4 == null) return false;
// export the two pins
Export m1Export = Export.newInstance(myCell, m1m2Port, "in");
m1Export.setCharacteristic(PortProto.Characteristic.IN);
Export p1Export = Export.newInstance(myCell, p1PortA, "out");
p1Export.setCharacteristic(PortProto.Characteristic.OUT);
System.out.println("Created cell " + myCell.describe());
// now up the hierarchy
Cell higherCell = Cell.newInstance(mainLib, "higher{lay}");
NodeInst higherCellCenter = NodeInst.newInstance(cellCenterProto, new Point2D.Double(0.0, 0.0), cellCenterProto.getDefWidth(), cellCenterProto.getDefHeight(), 0, higherCell, null);
higherCellCenter.setVisInside();
higherCellCenter.setHardSelect();
Rectangle2D bounds = myCell.getBounds();
double myWidth = myCell.getDefWidth();
double myHeight = myCell.getDefHeight();
NodeInst instance1Node = NodeInst.newInstance(myCell, new Point2D.Double(0, 0), myWidth, myHeight, 0, higherCell, null);
instance1Node.setExpanded();
NodeInst instance1UNode = NodeInst.newInstance(myCell, new Point2D.Double(0, 100), myWidth, myHeight, 0, higherCell, null);
NodeInst instance2Node = NodeInst.newInstance(myCell, new Point2D.Double(100, 0), myWidth, myHeight, 900, higherCell, null);
instance2Node.setExpanded();
NodeInst instance2UNode = NodeInst.newInstance(myCell, new Point2D.Double(100, 100), myWidth, myHeight, 900, higherCell, null);
NodeInst instance3Node = NodeInst.newInstance(myCell, new Point2D.Double(200, 0), myWidth, myHeight, 1800, higherCell, null);
instance3Node.setExpanded();
NodeInst instance3UNode = NodeInst.newInstance(myCell, new Point2D.Double(200, 100), myWidth, myHeight, 1800, higherCell, null);
NodeInst instance4Node = NodeInst.newInstance(myCell, new Point2D.Double(300, 0), myWidth, myHeight, 2700, higherCell, null);
instance4Node.setExpanded();
NodeInst instance4UNode = NodeInst.newInstance(myCell, new Point2D.Double(300, 100), myWidth, myHeight, 2700, higherCell, null);
// transposed
NodeInst instance5Node = NodeInst.newInstance(myCell, new Point2D.Double(0, 200), -myWidth, myHeight, 0, higherCell, null);
instance5Node.setExpanded();
NodeInst instance5UNode = NodeInst.newInstance(myCell, new Point2D.Double(0, 300), -myWidth, myHeight, 0, higherCell, null);
NodeInst instance6Node = NodeInst.newInstance(myCell, new Point2D.Double(100, 200), -myWidth, myHeight, 900, higherCell, null);
instance6Node.setExpanded();
NodeInst instance6UNode = NodeInst.newInstance(myCell, new Point2D.Double(100, 300), -myWidth, myHeight, 900, higherCell, null);
NodeInst instance7Node = NodeInst.newInstance(myCell, new Point2D.Double(200, 200), -myWidth, myHeight, 1800, higherCell, null);
instance7Node.setExpanded();
NodeInst instance7UNode = NodeInst.newInstance(myCell, new Point2D.Double(200, 300), -myWidth, myHeight, 1800, higherCell, null);
NodeInst instance8Node = NodeInst.newInstance(myCell, new Point2D.Double(300, 200), -myWidth, myHeight, 2700, higherCell, null);
instance8Node.setExpanded();
NodeInst instance8UNode = NodeInst.newInstance(myCell, new Point2D.Double(300, 300), -myWidth, myHeight, 2700, higherCell, null);
PortInst instance1Port = instance1Node.findPortInst("in");
PortInst instance2Port = instance1UNode.findPortInst("in");
ArcInst instanceArc = ArcInst.makeInstance(m1Proto, m1Proto.getWidth(), instance1Port, instance2Port, null);
System.out.println("Created cell " + higherCell.describe());
// now a rotation test
Cell rotTestCell = Cell.newInstance(mainLib, "rotationTest{lay}");
NodeInst rotTestCellCenter = NodeInst.newInstance(cellCenterProto, new Point2D.Double(0.0, 0.0), cellCenterProto.getDefWidth(), cellCenterProto.getDefHeight(), 0, rotTestCell, null);
rotTestCellCenter.setVisInside();
rotTestCellCenter.setHardSelect();
NodeInst r0Node = NodeInst.newInstance(myCell, new Point2D.Double(0, 0), myWidth, myHeight, 0, rotTestCell, null);
r0Node.setExpanded();
NodeInst nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(0, -35), 0, 0, 0, rotTestCell, null);
Variable var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 0");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r90Node = NodeInst.newInstance(myCell, new Point2D.Double(100, 0), myWidth, myHeight, 900, rotTestCell, null);
r90Node.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(100, -35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 90");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r180Node = NodeInst.newInstance(myCell, new Point2D.Double(200, 0), myWidth, myHeight, 1800, rotTestCell, null);
r180Node.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(200, -35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 180");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r270Node = NodeInst.newInstance(myCell, new Point2D.Double(300, 0), myWidth, myHeight, 2700, rotTestCell, null);
r270Node.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(300, -35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 270");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
// Mirrored in X
NodeInst r0MXNode = NodeInst.newInstance(myCell, new Point2D.Double(0, 100), -myWidth, myHeight, 0, rotTestCell, null);
r0MXNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(0, 100-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 0 MX");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r90MXNode = NodeInst.newInstance(myCell, new Point2D.Double(100, 100), -myWidth, myHeight, 900, rotTestCell, null);
r90MXNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(100, 100-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 90 MX");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r180MXNode = NodeInst.newInstance(myCell, new Point2D.Double(200, 100), -myWidth, myHeight, 1800, rotTestCell, null);
r180MXNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(200, 100-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 180 MX");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r270MXNode = NodeInst.newInstance(myCell, new Point2D.Double(300, 100), -myWidth, myHeight, 2700, rotTestCell, null);
r270MXNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(300, 100-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 270 MX");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
// Mirrored in Y
NodeInst r0MYNode = NodeInst.newInstance(myCell, new Point2D.Double(0, 200), myWidth, -myHeight, 0, rotTestCell, null);
r0MYNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(0, 200-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 0 MY");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r90MYNode = NodeInst.newInstance(myCell, new Point2D.Double(100, 200), myWidth, -myHeight, 900, rotTestCell, null);
r90MYNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(100, 200-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 90 MY");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r180MYNode = NodeInst.newInstance(myCell, new Point2D.Double(200, 200), myWidth, -myHeight, 1800, rotTestCell, null);
r180MYNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(200, 200-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 180 MY");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r270MYNode = NodeInst.newInstance(myCell, new Point2D.Double(300, 200), myWidth, -myHeight, 2700, rotTestCell, null);
r270MYNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(300, 200-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 270 MY");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
// Mirrored in X and Y
NodeInst r0MXYNode = NodeInst.newInstance(myCell, new Point2D.Double(0, 300), -myWidth, -myHeight, 0, rotTestCell, null);
r0MXYNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(0, 300-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 0 MXY");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r90MXYNode = NodeInst.newInstance(myCell, new Point2D.Double(100, 300), -myWidth, -myHeight, 900, rotTestCell, null);
r90MXYNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(100, 300-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 90 MXY");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r180MXYNode = NodeInst.newInstance(myCell, new Point2D.Double(200, 300), -myWidth, -myHeight, 1800, rotTestCell, null);
r180MXYNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(200, 300-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 180 MXY");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
NodeInst r270MXYNode = NodeInst.newInstance(myCell, new Point2D.Double(300, 300), -myWidth, -myHeight, 2700, rotTestCell, null);
r270MXYNode.setExpanded();
nodeLabel = NodeInst.newInstance(invisiblePinProto, new Point2D.Double(300, 300-35), 0, 0, 0, rotTestCell, null);
var = nodeLabel.newVar(Artwork.ART_MESSAGE, "Rotated 270 MXY");
var.setDisplay(); var.getTextDescriptor().setRelSize(10);
System.out.println("Created cell " + rotTestCell.describe());
// now up the hierarchy even farther
Cell bigCell = Cell.newInstance(mainLib, "big{lay}");
NodeInst bigCellCenter = NodeInst.newInstance(cellCenterProto, new Point2D.Double(0.0, 0.0), cellCenterProto.getDefWidth(), cellCenterProto.getDefHeight(), 0, bigCell, null);
bigCellCenter.setVisInside();
bigCellCenter.setHardSelect();
int arraySize = 20;
for(int y=0; y<arraySize; y++)
{
for(int x=0; x<arraySize; x++)
{
String theName = "arr["+ x + "][" + y + "]";
NodeInst instanceNode = NodeInst.newInstance(myCell, new Point2D.Double(x*(myWidth+2), y*(myHeight+2)),
myWidth, myHeight, 0, bigCell, theName);
TextDescriptor td = instanceNode.getNameTextDescriptor();
td.setOff(0, 8);
instanceNode.setNameTextDescriptor(td);
if ((x%2) == (y%2)) instanceNode.setExpanded();
}
}
System.out.println("Created cell " + bigCell.describe());
// display a cell
WindowFrame.createEditWindow(myCell);
return true;
}
}
// ---------------------- Gilda's Stuff MENU -----------------
public static void implantGeneratorCommand(boolean newIdea, boolean test) {
Cell curCell = WindowFrame.needCurCell();
if (curCell == null) return;
Job job = null;
if (newIdea)
{
job = new CoverImplant(curCell, test);
}
else
{
job = new CoverImplantOld(curCell);
}
}
private static class CoverImplant extends Job
{
private Cell curCell;
private boolean testMerge = false;
protected CoverImplant(Cell cell, boolean test)
{
super("Coverage Implant", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.curCell = cell;
this.testMerge = test;
setReportExecutionFlag(true);
startJob();
}
public boolean doIt()
{
List deleteList = new ArrayList(); // New coverage implants are pure primitive nodes
PolyQTree tree = new PolyQTree();
// Traversing arcs
for (Iterator it = curCell.getArcs(); it.hasNext(); )
{
ArcInst arc = (ArcInst)it.next();
ArcProto arcType = arc.getProto();
Technology tech = arcType.getTechnology();
Poly[] polyList = tech.getShapeOfArc(arc);
// Treating the arcs associated to each node
// Arcs don't need to be rotated
for (int i = 0; i < polyList.length; i++)
{
Poly poly = polyList[i];
Layer layer = poly.getLayer();
Layer.Function func = layer.getFunction();
if (Main.getDebug() || func.isSubstrate())
{
//Area bounds = new PolyQTree.PolyNode(poly.getBounds2D());
tree.insert((Object)layer, curCell.getBounds(), new PolyQTree.PolyNode(poly.getBounds2D()));
}
}
}
// Traversing nodes
for (Iterator it = curCell.getNodes(); it.hasNext(); )
{
NodeInst node = (NodeInst)it .next();
// New coverage implants are pure primitive nodes
// and previous get deleted and ignored.
if (!Main.getDebug() && node.getFunction() == NodeProto.Function.NODE)
{
deleteList.add(node);
continue;
}
NodeProto protoType = node.getProto();
if (protoType instanceof Cell) continue;
Technology tech = protoType.getTechnology();
Poly[] polyList = tech.getShapeOfNode(node);
AffineTransform transform = node.rotateOut();
for (int i = 0; i < polyList.length; i++)
{
Poly poly = polyList[i];
Layer layer = poly.getLayer();
Layer.Function func = layer.getFunction();
// Only substrate layers, skipping center information
if (Main.getDebug() || func.isSubstrate())
{
poly.transform(transform);
//Area bounds = new PolyQTree.PolyNode(poly.getBounds2D());
tree.insert((Object)layer, curCell.getBounds(), new PolyQTree.PolyNode(poly.getBounds2D()));
}
}
}
// tree.print();
// With polygons collected, new geometries are calculated
Highlight.clear();
List nodesList = new ArrayList();
// Need to detect if geometry was really modified
for(Iterator it = tree.getKeyIterator(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
Set set = tree.getObjects(layer, true);
// Ready to create new implants.
for (Iterator i = set.iterator(); i.hasNext(); )
{
Rectangle2D rect = ((PolyQTree.PolyNode)i.next()).getBounds2D();
Point2D center = new Point2D.Double(rect.getCenterX(), rect.getCenterY());
PrimitiveNode priNode = layer.getPureLayerNode();
// Adding the new implant. New implant not assigned to any local variable .
NodeInst node = NodeInst.makeInstance(priNode, center, rect.getWidth(), rect.getHeight(), 0, curCell, null);
Highlight.addElectricObject(node, curCell);
// New implant can't be selected again
node.setHardSelect();
nodesList.add(node);
}
}
Highlight.finished();
for (Iterator it = deleteList.iterator(); it.hasNext(); )
{
NodeInst node = (NodeInst)it .next();
node.kill();
}
if ( nodesList.isEmpty() )
System.out.println("No implant areas added");
return true;
}
}
private static class CoverImplantOld extends Job
{
private Cell curCell;
protected CoverImplantOld(Cell cell)
{
super("Coverage Implant Old", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
this.curCell = cell;
setReportExecutionFlag(true);
startJob();
}
public boolean doIt()
{
PolyMerge merge = new PolyMerge();
List deleteList = new ArrayList(); // New coverage implants are pure primitive nodes
HashMap allLayers = new HashMap();
// Traversing arcs
for(Iterator it = curCell.getArcs(); it.hasNext(); )
{
ArcInst arc = (ArcInst)it.next();
ArcProto arcType = arc.getProto();
Technology tech = arcType.getTechnology();
Poly[] polyList = tech.getShapeOfArc(arc);
// Treating the arcs associated to each node
// Arcs don't need to be rotated
for (int i = 0; i < polyList.length; i++)
{
Poly poly = polyList[i];
Layer layer = poly.getLayer();
Layer.Function func = layer.getFunction();
if ( func.isSubstrate() )
{
merge.addPolygon(layer, poly);
List rectList = (List)allLayers.get(layer);
if ( rectList == null )
{
rectList = new ArrayList();
allLayers.put(layer, rectList);
}
rectList.add(poly);
}
}
}
// Traversing nodes
for(Iterator it = curCell.getNodes(); it.hasNext(); )
{
NodeInst node = (NodeInst)it .next();
// New coverage implants are pure primitive nodes
// and previous get deleted and ignored.
if ( node.getFunction() == NodeProto.Function.NODE )
{
deleteList.add(node);
continue;
}
NodeProto protoType = node.getProto();
if (protoType instanceof Cell) continue;
Technology tech = protoType.getTechnology();
Poly[] polyList = tech.getShapeOfNode(node);
AffineTransform transform = node.rotateOut();
for (int i = 0; i < polyList.length; i++)
{
Poly poly = polyList[i];
Layer layer = poly.getLayer();
Layer.Function func = layer.getFunction();
// Only substrate layers, skipping center information
if ( func.isSubstrate() )
{
poly.transform(transform);
merge.addPolygon(layer, poly);
List rectList = (List)allLayers.get(layer);
if ( rectList == null )
{
rectList = new ArrayList();
allLayers.put(layer, rectList);
}
rectList.add(poly);
}
}
}
// With polygons collected, new geometries are calculated
Highlight.clear();
List nodesList = new ArrayList();
// Need to detect if geometry was really modified
for(Iterator it = merge.getLayersUsed(); it.hasNext(); )
{
Layer layer = (Layer)it.next();
List list = merge.getMergedPoints(layer) ;
// Temp solution until qtree implementation is ready
// delete uncessary polygons. Doesn't insert poly if identical
// to original. Very ineficient!!
List rectList = (List)allLayers.get(layer);
List delList = new ArrayList();
for (Iterator iter = rectList.iterator(); iter.hasNext();)
{
Poly p = (Poly)iter.next();
Rectangle2D rect = p.getBounds2D();
for (Iterator i = list.iterator(); i.hasNext();)
{
Poly poly = (Poly)i.next();
Rectangle2D r = poly.getBounds2D();
if (r.equals(rect))
{
delList.add(poly);
}
}
}
for (Iterator iter = delList.iterator(); iter.hasNext();)
{
list.remove(iter.next());
}
// Ready to create new implants.
for(Iterator i = list.iterator(); i.hasNext(); )
{
Poly poly = (Poly)i.next();
Rectangle2D rect = poly.getBounds2D();
Point2D center = new Point2D.Double(rect.getCenterX(), rect.getCenterY());
PrimitiveNode priNode = layer.getPureLayerNode();
// Adding the new implant. New implant not assigned to any local variable .
NodeInst node = NodeInst.makeInstance(priNode, center, rect.getWidth(), rect.getHeight(), 0, curCell, null);
Highlight.addElectricObject(node, curCell);
// New implant can't be selected again
node.setHardSelect();
nodesList.add(node);
}
}
Highlight.finished();
for (Iterator it = deleteList.iterator(); it.hasNext(); )
{
NodeInst node = (NodeInst)it .next();
node.kill();
}
if ( nodesList.isEmpty() )
System.out.println("No implant areas added");
return true;
}
}
// ---------------------- THE JON GAINSLEY MENU -----------------
public static void listVarsOnObject(boolean useproto) {
if (Highlight.getNumHighlights() == 0) {
// list vars on cell
WindowFrame wf = WindowFrame.getCurrentWindowFrame();
if (wf == null) return;
Cell cell = wf.getContent().getCell();
cell.getInfo();
return;
}
for (Iterator it = Highlight.getHighlights(); it.hasNext();) {
Highlight h = (Highlight)it.next();
if (h.getType() != Highlight.Type.EOBJ) continue;
ElectricObject eobj = h.getElectricObject();
if (eobj instanceof PortInst) {
PortInst pi = (PortInst)eobj;
pi.getInfo();
eobj = pi.getNodeInst();
}
if (eobj instanceof NodeInst) {
NodeInst ni = (NodeInst)eobj;
if (useproto) {
System.out.println("using prototype");
((ElectricObject)ni.getProto()).getInfo();
} else {
ni.getInfo();
}
}
}
}
public static void evalVarsOnObject() {
EditWindow curEdit = EditWindow.needCurrent();
if (Highlight.getNumHighlights() == 0) return;
for (Iterator it = Highlight.getHighlights(); it.hasNext();) {
Highlight h = (Highlight)it.next();
if (h.getType() != Highlight.Type.EOBJ) continue;
ElectricObject eobj = h.getElectricObject();
Iterator itVar = eobj.getVariables();
while(itVar.hasNext()) {
Variable var = (Variable)itVar.next();
Object obj = curEdit.getVarContext().evalVar(var);
System.out.print(var.getKey().getName() + ": ");
System.out.println(obj);
}
}
}
public static void listLibVars() {
Library lib = Library.getCurrent();
Iterator itVar = lib.getVariables();
System.out.println("----------"+lib+" Vars-----------");
while(itVar.hasNext()) {
Variable var = (Variable)itVar.next();
Object obj = VarContext.globalContext.evalVar(var);
System.out.println(var.getKey().getName() + ": " +obj);
}
}
public static void openP4libCommand() {
URL url = TextUtils.makeURLToFile("/export/gainsley/soesrc_java/test/purpleFour.elib");
ReadELIB job = new ReadELIB(url);
// OpenBinLibraryThread oThread = new OpenBinLibraryThread("/export/gainsley/soesrc_java/test/purpleFour.elib");
// oThread.start();
}
public static void whitDiffieCommand()
{
MakeWhitDesign job = new MakeWhitDesign();
}
private static class MakeWhitDesign extends Job
{
protected MakeWhitDesign()
{
super("Make Whit design", User.tool, Job.Type.CHANGE, null, null, Job.Priority.USER);
startJob();
}
public boolean doIt()
{
String [] theStrings =
{
// correct data
// "a1f0f1k0p0", "a2f1f2k1p1", "a3f2f3k2p2", "a0a4f0f3f4k3p3", "a0a5f0f4f5k4p4", "a6f5f6k5p5", "a0a7f0f6f7k6p6", "a0f0f7k7p7",
// "a0f1k0k1p0", "a1f2k1k2p1", "a2f3k2k3p2", "a3f0f4k0k3k4p3", "a4f0f5k0k4k5p4", "a5f6k5k6p5", "a6f0f7k0k6k7p6", "a7f0k0k7p7",
// "a0f0k1p0p1", "a1f1k2p1p2", "a2f2k3p2p3", "a3f3k0k4p0p3p4", "a4f4k0k5p0p4p5", "a5f5k6p5p6", "a6f6k0k7p0p6p7", "a7f7k0p0p7",
// "a0a1f0k0p1", "a1a2f1k1p2", "a2a3f2k2p3", "a0a3a4f3k3p0p4", "a0a4a5f4k4p0p5", "a5a6f5k5p6", "a0a6a7f6k6p0p7", "a0a7f7k7p0",
// "e1j0j1o0d0", "e2j1j2o1d1", "e3j2j3o2d2", "e0e4j0j3j4o3d3", "e0e5j0j4j5o4d4", "e6j5j6o5d5", "e0e7j0j6j7o6d6", "e0j0j7o7d7",
// "e0j1o0o1d0", "e1j2o1o2d1", "e2j3o2o3d2", "e3j0j4o0o3o4d3", "e4j0j5o0o4o5d4", "e5j6o5o6d5", "e6j0j7o0o6o7d6", "e7j0o0o7d7",
// "e0j0o1d0d1", "e1j1o2d1d2", "e2j2o3d2d3", "e3j3o0o4d0d3d4", "e4j4o0o5d0d4d5", "e5j5o6d5d6", "e6j6o0o7d0d6d7", "e7j7o0d0d7",
// "e0e1j0o0d1", "e1e2j1o1d2", "e2e3j2o2d3", "e0e3e4j3o3d0d4", "e0e4e5j4o4d0d5", "e5e6j5o5d6", "e0e6e7j6o6d0d7", "e0e7j7o7d0",
// "i1n0n1c0h0", "i2n1n2c1h1", "i3n2n3c2h2", "i0i4n0n3n4c3h3", "i0i5n0n4n5c4h4", "i6n5n6c5h5", "i0i7n0n6n7c6h6", "i0n0n7c7h7",
// "i0n1c0c1h0", "i1n2c1c2h1", "i2n3c2c3h2", "i3n0n4c0c3c4h3", "i4n0n5c0c4c5h4", "i5n6c5c6h5", "i6n0n7c0c6c7h6", "i7n0c0c7h7",
// "i0n0c1h0h1", "i1n1c2h1h2", "i2n2c3h2h3", "i3n3c0c4h0h3h4", "i4n4c0c5h0h4h5", "i5n5c6h5h6", "i6n6c0c7h0h6h7", "i7n7c0h0h7",
// "i0i1n0c0h1", "i1i2n1c1h2", "i2i3n2c2h3", "i0i3i4n3c3h0h4", "i0i4i5n4c4h0h5", "i5i6n5c5h6", "i0i6i7n6c6h0h7", "i0i7n7c7h0",
// "m1b0b1g0l0", "m2b1b2g1l1", "m3b2b3g2l2", "m0m4b0b3b4g3l3", "m0m5b0b4b5g4l4", "m6b5b6g5l5", "m0m7b0b6b7g6l6", "m0b0b7g7l7",
// "m0b1g0g1l0", "m1b2g1g2l1", "m2b3g2g3l2", "m3b0b4g0g3g4l3", "m4b0b5g0g4g5l4", "m5b6g5g6l5", "m6b0b7g0g6g7l6", "m7b0g0g7l7",
// "m0b0g1l0l1", "m1b1g2l1l2", "m2b2g3l2l3", "m3b3g0g4l0l3l4", "m4b4g0g5l0l4l5", "m5b5g6l5l6", "m6b6g0g7l0l6l7", "m7b7g0l0l7",
// "m0m1b0g0l1", "m1m2b1g1l2", "m2m3b2g2l3", "m0m3m4b3g3l0l4", "m0m4m5b4g4l0l5", "m5m6b5g5l6", "m0m6m7b6g6l0l7", "m0m7b7g7l0"
// sorted data
// "a1f0f1k0p0", "a2f1f2k1p1", "a3f2f3k2p2", "a0a4f0f3f4k3p3", "a0a5f0f4f5k4p4", "a6f5f6k5p5", "a0a7f0f6f7k6p6", "a0f0f7k7p7",
// "a0f1k0k1p0", "a1f2k1k2p1", "a2f3k2k3p2", "a3f0f4k0k3k4p3", "a4f0f5k0k4k5p4", "a5f6k5k6p5", "a6f0f7k0k6k7p6", "a7f0k0k7p7",
// "a0f0k1p0p1", "a1f1k2p1p2", "a2f2k3p2p3", "a3f3k0k4p0p3p4", "a4f4k0k5p0p4p5", "a5f5k6p5p6", "a6f6k0k7p0p6p7", "a7f7k0p0p7",
// "a0a1f0k0p1", "a1a2f1k1p2", "a2a3f2k2p3", "a0a3a4f3k3p0p4", "a0a4a5f4k4p0p5", "a5a6f5k5p6", "a0a6a7f6k6p0p7", "a0a7f7k7p0",
// "d0e1j0j1o0", "d1e2j1j2o1", "d2e3j2j3o2", "d3e0e4j0j3j4o3", "d4e0e5j0j4j5o4", "d5e6j5j6o5", "d6e0e7j0j6j7o6", "d7e0j0j7o7",
// "d0e0j1o0o1", "d1e1j2o1o2", "d2e2j3o2o3", "d3e3j0j4o0o3o4", "d4e4j0j5o0o4o5", "d5e5j6o5o6", "d6e6j0j7o0o6o7", "d7e7j0o0o7",
// "d0d1e0j0o1", "d1d2e1j1o2", "d2d3e2j2o3", "d0d3d4e3j3o0o4", "d0d4d5e4j4o0o5", "d5d6e5j5o6", "d0d6d7e6j6o0o7", "d0d7e7j7o0",
// "d1e0e1j0o0", "d2e1e2j1o1", "d3e2e3j2o2", "d0d4e0e3e4j3o3", "d0d5e0e4e5j4o4", "d6e5e6j5o5", "d0d7e0e6e7j6o6", "d0e0e7j7o7",
// "c0h0i1n0n1", "c1h1i2n1n2", "c2h2i3n2n3", "c3h3i0i4n0n3n4", "c4h4i0i5n0n4n5", "c5h5i6n5n6", "c6h6i0i7n0n6n7", "c7h7i0n0n7",
// "c0c1h0i0n1", "c1c2h1i1n2", "c2c3h2i2n3", "c0c3c4h3i3n0n4", "c0c4c5h4i4n0n5", "c5c6h5i5n6", "c0c6c7h6i6n0n7", "c0c7h7i7n0",
// "c1h0h1i0n0", "c2h1h2i1n1", "c3h2h3i2n2", "c0c4h0h3h4i3n3", "c0c5h0h4h5i4n4", "c6h5h6i5n5", "c0c7h0h6h7i6n6", "c0h0h7i7n7",
// "c0h1i0i1n0", "c1h2i1i2n1", "c2h3i2i3n2", "c3h0h4i0i3i4n3", "c4h0h5i0i4i5n4", "c5h6i5i6n5", "c6h0h7i0i6i7n6", "c7h0i0i7n7",
// "b0b1g0l0m1", "b1b2g1l1m2", "b2b3g2l2m3", "b0b3b4g3l3m0m4", "b0b4b5g4l4m0m5", "b5b6g5l5m6", "b0b6b7g6l6m0m7", "b0b7g7l7m0",
// "b1g0g1l0m0", "b2g1g2l1m1", "b3g2g3l2m2", "b0b4g0g3g4l3m3", "b0b5g0g4g5l4m4", "b6g5g6l5m5", "b0b7g0g6g7l6m6", "b0g0g7l7m7",
// "b0g1l0l1m0", "b1g2l1l2m1", "b2g3l2l3m2", "b3g0g4l0l3l4m3", "b4g0g5l0l4l5m4", "b5g6l5l6m5", "b6g0g7l0l6l7m6", "b7g0l0l7m7",
// "b0g0l1m0m1", "b1g1l2m1m2", "b2g2l3m2m3", "b3g3l0l4m0m3m4", "b4g4l0l5m0m4m5", "b5g5l6m5m6", "b6g6l0l7m0m6m7", "b7g7l0m0m7"
// original data
// "a1f0f1k0p0", "a2f1f2k1p1", "a3f2f3k2p2", "a0a4f0f3f4k3p3", "a0a5f0f4f5k4p4", "a6f5f6k5p5", "a0a7f0f6f7k6p6", "a0f0f7k7p7",
// "a0f1k0k1p0", "a1f2k1k2p1", "a2f3k2k3p2", "a3f0f4k0k3k4p3", "a4f0f5k0k4k5p4", "a5f6k5k6p5", "a6f0f7k0k6k7p6", "a7f0k0k7p7",
// "a0f0k1p0p1", "a1f1k2p1p2", "a2f2k3p2p3", "a3f3k0k4p0p3p4", "a4f4k0k5p0p4p5", "a5f5k6p5p6", "a6f6k0k7p0p6p7", "a7f7k0p0p7",
// "a0a1f0k0p1", "a1a2f1k1p2", "a2a3f2k2p3", "a0a3a4f3k3p0p4", "a0a4a5f4k4p0p5", "a5a6f5k5p6", "a0a6a7f6k6p0p7", "a0a7f7k7p0",
// "b1g0g1l0m0", "b2g1g2l1m1", "b3g2g3l2m2", "b0b4g0g3g4l3m3", "b0b5g0g4g5l4m4", "b6g5g6l5m5", "b0b7g0g6g7l6m6", "b0g0g7l7m7",
// "b0g1l0l1m0", "b1g2l1l2m1", "b2g3l2l3m2", "b3g0g4l0l3l4m3", "b4g0g5l0l4l5m4", "b5g6l5l6m5", "b6g0g7l0l6l7m6", "b7g0l0l7m7",
// "b0g0l1m0m1", "b1g1l2m1m2", "b2g2l3m2m3", "b3g3l0l4m0m3m4", "b4g4l0l5m0m4m5", "b5g5l6m5m6", "b6g6l0l7m0m6m7", "b7g7l0m0m7",
// "b0b1g0l0m1", "b1b2g1l1m2", "b2b3g2l2m3", "b0b3b4g3l3m0m4", "b0b4b5g4l4m0m5", "b5b6g5l5m6", "b0b6b7g6l6m0m7", "b0b7g7l7m0",
// "c1h0h1i0n0", "c2h1h2i1n1", "c3h2h3i2n2", "c0c4h0h3h4i3n3", "c0c5h0h4h5i4n4", "c6h5h6i5n5", "c0c7h0h6h7i6n6", "c0h0h7i7n7",
// "c0h1i0i1n0", "c1h2i1i2n1", "c2h3i2i3n2", "c3h0h4i0i3i4n3", "c4h0h5i0i4i5n4", "c5h6i5i6n5", "c6h0h7i0i6i7n6", "c7h0i0i7n7",
// "c0h0i1n0n1", "c1h1i2n1n2", "c2h2i3n2n3", "c3h3i0i4n0n3n4", "c4h4i0i5n0n4n5", "c5h5i6n5n6", "c6h6i0i7n0n6n7", "c7h7i0n0n7",
// "c0c1h0i0n1", "c1c2h1i1n2", "c2c3h2i2n3", "c0c3c4h3i3n0n4", "c0c4c5h4i4n0n5", "c5c6h5i5n6", "c0c6c7h6i6n0n7", "c0c7h7i7n0",
// "d1e0e1j0o0", "d2e1e2j1o1", "d3e2e3j2o2", "d0d4e0e3e4j3o3", "d0d5e0e4e5j4o4", "d6e5e6j5o5", "d0d7e0e6e7j6o6", "d0e0e7j7o7",
// "d0e1j0j1o0", "d1e2j1j2o1", "d2e3j2j3o2", "d3e0e4j0j3j4o3", "d4e0e5j0j4j5o4", "d5e6j5j6o5", "d6e0e7j0j6j7o6", "d7e0j0j7o7",
// "d0e0j1o0o1", "d1e1j2o1o2", "d2e2j3o2o3", "d3e3j0j4o0o3o4", "d4e4j0j5o0o4o5", "d5e5j6o5o6", "d6e6j0j7o0o6o7", "d7e7j0o0o7",
// "d0d1e0j0o1", "d1d2e1j1o2", "d2d3e2j2o3", "d0d3d4e3j3o0o4", "d0d4d5e4j4o0o5", "d5d6e5j5o6", "d0d6d7e6j6o0o7", "d0d7e7j7o0"
// bad data
"a1f0f1k0p0", "a2f1f2k1p1", "a3f2f3k2p2", "a0a4f0f3f4k3p3", "a0a5f0f4f5k4p4", "a6f5f6k5p5", "a0a7f0f6f7k6p6", "a0f0f7k7p7",
"a0f1k0k1p0", "a1f2k1k2p1", "a2f3k2k3p2", "a3f0f4k0k3k4p3", "a4f0f5k0k4k5p4", "a5f6k5k6p5", "a6f0f7k0k6k7p6", "a7f0k0k7p7",
"a0f0k1p0p1", "a1f1k2p1p2", "a2f2k3p2p3", "a3f3k0k4p0p3p4", "a4f4k0k5p0p4p5", "a5f5k6p5p6", "a6f6k0k7p0p6p7", "a7f7k0p0p7",
"a0a1f0k0p1", "a1a2f1k1p2", "a2a3f2k2p3", "a0a3a4f3k3p0p4", "a0a4a5f4k4p0p5", "a5a6f5k5p6", "a0a6a7f6k6p0p7", "a0a7f7k7p0",
"b1g0g1l0m0", "b2g1g2l1m1", "b3g2g3l2m2", "b0b4g0g3g4l3m3", "b0b5g0g4g5l4m4", "b6g5g6l5m5", "b0b7g0g6g7l6m6", "b0g0g7l7m7",
"b0g1l0l1m0", "b1g2l1l2m1", "b2g3l2l3m2", "b3g0g4l0l3l4m3", "b4g0g5l0l4l5m4", "b5g6l5l6m5", "b6g0g7l0l6l7m6", "b7g0l0l7m7",
"b0g0l1m0m1", "b1g1l2m1m2", "b2g2l3m2m3", "b3g3l0l4m0m3m4", "b4g4l0l5m0m4m5", "b5g5l6m5m6", "b6g6l0l7m0m6m7", "b7g7l0m0m7",
"b0b1g0l0m1", "b1b2g1l1m2", "b2b3g2l2m3", "b0b3b4g3l3m0m4", "b0b4b5g4l4m0m5", "b5b6g5l5m6", "b0b6b7g6l6m0m7", "b0b7g7l7m0",
"c1h0h1i0n0", "c2h1h2i1n1", "c3h2h3i2n2", "c0c4h0h3h4i3n3", "c0c5h0h4h5i4n4", "c6h5h6i5n5", "c0c7h0h6h7i6n6", "c0h0h7i7n7",
"c0h1i0i1n0", "c1h2i1i2n1", "c2h3i2i3n2", "c3h0h4i0i3i4n3", "c4h0h5i0i4i5n4", "c5h6i5i6n5", "c6h0h7i0i6i7n6", "c7h0i0i7n7",
"c0h0i1n0n1", "c1h1i2n1n2", "c2h2i3n2n3", "c3h3i0i4n0n3n4", "c4h4i0i5n0n4n5", "c5h5i6n5n6", "c6h6i0i7n0n6n7", "c7h7i0n0n7",
"c0c1h0i0n1", "c1c2h1i1n2", "c2c3h2i2n3", "c0c3c4h3i3n0n4", "c0c4c5h4i4n0n5", "c5c6h5i5n6", "c0c6c7h6i6n0n7", "c0c7h7i7n0",
"d1e0e1j0o0", "d2e1e2j1o1", "d3e2e3j2o2", "d0d4e0e3e4j3o3", "d0d5e0e4e5j4o4", "d6e5e6j5o5", "d0d7e0e6e7j6o6", "d0e0e7j7o7",
"d0e1j0j1o0", "d1e2j1j2o1", "d2e3j2j3o2", "d3e0e4j0j3j4o3", "d4e0e5j0j4j5o4", "d5e6j5j6o5", "d6e0e7j0j6j7o6", "d7e0j0j7o7",
"d0e0j1o0o1", "d1e1j2o1o2", "d2e2j3o2o3", "d3e3j0j4o0o3o4", "d4e4j0j5o0o4o5", "d5e5j6o5o6", "d6e6j0j7o0o6o7", "d7e7j0o0o7",
"d0d1e0j0o1", "d1d2e1j1o2", "d2d3e2j2o3", "d0d3d4e3j3o0o4", "d0d4d5e4j4o0o5", "d5d6e5j5o6", "d0d6d7e6j6o0o7", "d0d7e7j7o0"
};
boolean threePage = false;
for(int v=0; v<33; v++)
{
if (v != 32) continue;
String title = "whit";
if (v < 16) title += "Input" + (v+1); else
if (v < 32) title += "Output" + (v-15);
Cell myCell = Cell.newInstance(Library.getCurrent(), title+"{sch}");
// create the input and output pins
NodeProto pinNp = com.sun.electric.technology.technologies.Generic.tech.universalPinNode;
NodeInst [] inputs = new NodeInst[128];
NodeInst [] outputs = new NodeInst[128];
NodeInst [] inputsAbove = new NodeInst[128];
NodeInst [] outputsAbove = new NodeInst[128];
NodeInst [] inputsBelow = new NodeInst[128];
NodeInst [] outputsBelow = new NodeInst[128];
for(int j=0; j<3; j++)
{
if (!threePage && j != 1) continue;
for(int i=0; i<128; i++)
{
// the input side
int index = i;
if (j == 0) index += 128; else
if (j == 2) index -= 128;
NodeInst in = NodeInst.newInstance(pinNp, new Point2D.Double(-200.0, index*5), 1, 1, 0, myCell, null);
switch (j)
{
case 0: inputsAbove[i] = in; break;
case 1: inputs[i] = in; break;
case 2: inputsBelow[i] = in; break;
}
if (j == 1)
{
NodeInst leftArrow = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.boxNode,
new Point2D.Double(-267, i*5), 10, 0, 0, myCell, null);
NodeInst leftArrowHead = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.arrowNode,
new Point2D.Double(-264, i*5), 4, 4, 0, myCell, null);
}
// the output side
NodeInst out = NodeInst.newInstance(pinNp, new Point2D.Double(200.0, index*5), 0, 0, 0, myCell, null);
switch (j)
{
case 0: outputsAbove[i] = out; break;
case 1: outputs[i] = out; break;
case 2: outputsBelow[i] = out; break;
}
if (j == 1)
{
NodeInst circle = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.circleNode, new Point2D.Double(202.5, i*5), 5, 5, 0, myCell, null);
NodeInst horiz = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.boxNode,
new Point2D.Double(202.5, i*5), 4, 0, 0, myCell, null);
NodeInst vert = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.boxNode,
new Point2D.Double(202.5, i*5), 0, 4, 0, myCell, null);
NodeInst rightArrow = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.boxNode,
new Point2D.Double(210, i*5), 10, 0, 0, myCell, null);
NodeInst rightArrowHead = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.arrowNode,
new Point2D.Double(213, i*5), 4, 4, 0, myCell, null);
}
}
}
for(int i=0; i<16; i++)
{
NodeInst inputBox = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.boxNode,
new Point2D.Double(-222.0, i*5*8+20-2.5), 40, 40, 0, myCell, null);
Variable inVar = inputBox.newVar("label", "S-box");
inVar.setDisplay();
inVar.getTextDescriptor().setRelSize(12);
}
NodeInst inputBox1 = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.boxNode,
new Point2D.Double(-252.0, 320-2.5), 20, 640, 0, myCell, null);
Variable inVar1 = inputBox1.newVar("label", "Keying");
inVar1.setDisplay();
inVar1.getTextDescriptor().setRotation(TextDescriptor.Rotation.ROT90);
inVar1.getTextDescriptor().setRelSize(15);
NodeInst inputBox2 = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.boxNode,
new Point2D.Double(-282.0, 320-2.5), 20, 640, 0, myCell, null);
Variable inVar2 = inputBox2.newVar("label", "Input");
inVar2.setDisplay();
inVar2.getTextDescriptor().setRotation(TextDescriptor.Rotation.ROT90);
inVar2.getTextDescriptor().setRelSize(15);
NodeInst outputBox = NodeInst.newInstance(com.sun.electric.technology.technologies.Artwork.tech.boxNode,
new Point2D.Double(225.0, 320-2.5), 20, 640, 0, myCell, null);
Variable inVar3 = outputBox.newVar("label", "Output");
inVar3.setDisplay();
inVar3.getTextDescriptor().setRotation(TextDescriptor.Rotation.ROT90);
inVar3.getTextDescriptor().setRelSize(15);
NodeInst titleBox = NodeInst.newInstance(com.sun.electric.technology.technologies.Generic.tech.invisiblePinNode,
new Point2D.Double(0, 670), 0, 0, 0, myCell, null);
Variable inVar4 = titleBox.newVar("label", "One Round of AES");
inVar4.setDisplay();
inVar4.getTextDescriptor().setRelSize(24);
// wire them together
ArcProto wire = com.sun.electric.technology.technologies.Generic.tech.universal_arc;
for(int i=0; i<theStrings.length; i++)
{
int len = theStrings[i].length();
for(int j=0; j<len; j+=2)
{
char letter = theStrings[i].charAt(j);
char number = theStrings[i].charAt(j+1);
int index = (letter - 'a')*8 + (number - '0');
if (v < 16)
{
// only interested in the proper letter
if (v + 'a' != letter) continue;
} else if (v < 32)
{
if (i/8 != v-16) continue;
}
// handle wrapping
if (threePage && Math.abs(index - i) > 64)
{
if (i < 64)
{
PortInst inPort = inputsBelow[index].getOnlyPortInst();
PortInst outPort = outputs[i].getOnlyPortInst();
ArcInst.newInstance(wire, 0, inPort, outPort, null);
inPort = inputs[index].getOnlyPortInst();
outPort = outputsAbove[i].getOnlyPortInst();
ArcInst.newInstance(wire, 0, inPort, outPort, null);
} else
{
PortInst inPort = inputsAbove[index].getOnlyPortInst();
PortInst outPort = outputs[i].getOnlyPortInst();
ArcInst.newInstance(wire, 0, inPort, outPort, null);
inPort = inputs[index].getOnlyPortInst();
outPort = outputsBelow[i].getOnlyPortInst();
ArcInst.newInstance(wire, 0, inPort, outPort, null);
}
} else
{
PortInst inPort = inputs[index].getOnlyPortInst();
PortInst outPort = outputs[i].getOnlyPortInst();
ArcInst.newInstance(wire, 0, inPort, outPort, null);
}
}
}
// display the full drawing
if (v == 32) WindowFrame.createEditWindow(myCell);
}
return true;
}
}
}
| false | true | public static MenuBar createMenuBar()
{
// create the menu bar
MenuBar menuBar = new MenuBar();
MenuItem m;
int buckyBit = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/****************************** THE FILE MENU ******************************/
Menu fileMenu = new Menu("File", 'F');
menuBar.add(fileMenu);
fileMenu.addMenuItem("New Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newLibraryCommand(); } });
fileMenu.addMenuItem("Open Library", KeyStroke.getKeyStroke('O', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { openLibraryCommand(); } });
Menu importSubMenu = new Menu("Import");
fileMenu.add(importSubMenu);
importSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { importLibraryCommand(); } });
fileMenu.addMenuItem("I/O Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { IOOptions.ioOptionsCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Close Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { closeLibraryCommand(Library.getCurrent()); } });
fileMenu.addMenuItem("Save Library", KeyStroke.getKeyStroke('S', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.ELIB); } });
fileMenu.addMenuItem("Save Library as...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAsLibraryCommand(); } });
fileMenu.addMenuItem("Save All Libraries",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAllLibrariesCommand(); } });
Menu exportSubMenu = new Menu("Export");
fileMenu.add(exportSubMenu);
exportSubMenu.addMenuItem("CIF (Caltech Intermediate Format)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CIF, false); } });
exportSubMenu.addMenuItem("GDS II (Stream)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.GDS, false); } });
exportSubMenu.addMenuItem("PostScript", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.POSTSCRIPT, false); } });
exportSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.READABLEDUMP); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Change Current Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.changeCurrentLibraryCommand(); } });
fileMenu.addMenuItem("List Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.listLibrariesCommand(); } });
fileMenu.addMenuItem("Rename Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.renameLibraryCommand(); } });
fileMenu.addMenuItem("Mark All Libraries for Saving", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.markAllLibrariesForSavingCommand(); } });
fileMenu.addMenuItem("Repair Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.checkAndRepairCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Print...", KeyStroke.getKeyStroke('P', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { printCommand(); } });
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
fileMenu.addSeparator();
fileMenu.addMenuItem("Quit", KeyStroke.getKeyStroke('Q', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { quitCommand(); } });
}
/****************************** THE EDIT MENU ******************************/
Menu editMenu = new Menu("Edit", 'E');
menuBar.add(editMenu);
editMenu.addMenuItem("Cut", KeyStroke.getKeyStroke('X', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.cut(); } });
editMenu.addMenuItem("Copy", KeyStroke.getKeyStroke('C', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.copy(); } });
editMenu.addMenuItem("Paste", KeyStroke.getKeyStroke('V', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.paste(); } });
editMenu.addMenuItem("Duplicate", KeyStroke.getKeyStroke('M', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.duplicate(); } });
editMenu.addSeparator();
Menu arcSubMenu = new Menu("Arc", 'A');
editMenu.add(arcSubMenu);
arcSubMenu.addMenuItem("Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcRigidCommand(); }});
arcSubMenu.addMenuItem("Not Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotRigidCommand(); }});
arcSubMenu.addMenuItem("Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcFixedAngleCommand(); }});
arcSubMenu.addMenuItem("Not Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotFixedAngleCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Toggle Directionality", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcDirectionalCommand(); }});
arcSubMenu.addMenuItem("Toggle Ends Extension", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcEndsExtendCommand(); }});
arcSubMenu.addMenuItem("Reverse", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcReverseCommand(); }});
arcSubMenu.addMenuItem("Toggle Head-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipHeadCommand(); }});
arcSubMenu.addMenuItem("Toggle Tail-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipTailCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Rip Bus", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.ripBus(); }});
editMenu.addSeparator();
editMenu.addMenuItem("Undo", KeyStroke.getKeyStroke('Z', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { undoCommand(); } });
editMenu.addMenuItem("Redo", KeyStroke.getKeyStroke('Y', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { redoCommand(); } });
editMenu.addSeparator();
Menu rotateSubMenu = new Menu("Rotate", 'R');
editMenu.add(rotateSubMenu);
rotateSubMenu.addMenuItem("90 Degrees Clockwise", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(2700); }});
rotateSubMenu.addMenuItem("90 Degrees Counterclockwise", KeyStroke.getKeyStroke('J', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(900); }});
rotateSubMenu.addMenuItem("180 Degrees", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(1800); }});
rotateSubMenu.addMenuItem("Other...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(0); }});
Menu mirrorSubMenu = new Menu("Mirror", 'M');
editMenu.add(mirrorSubMenu);
mirrorSubMenu.addMenuItem("Horizontally (flip over X-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(true); }});
mirrorSubMenu.addMenuItem("Vertically (flip over Y-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(false); }});
Menu sizeSubMenu = new Menu("Size", 'S');
editMenu.add(sizeSubMenu);
sizeSubMenu.addMenuItem("Interactively", KeyStroke.getKeyStroke('B', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeObjects(); } });
sizeSubMenu.addMenuItem("All Selected Nodes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllNodes(); }});
sizeSubMenu.addMenuItem("All Selected Arcs...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllArcs(); }});
Menu moveSubMenu = new Menu("Move", 'V');
editMenu.add(moveSubMenu);
moveSubMenu.addMenuItem("Spread...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Spread.showSpreadDialog(); }});
moveSubMenu.addMenuItem("Move Objects By...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { MoveBy.showMoveByDialog(); }});
moveSubMenu.addMenuItem("Align to Grid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignToGrid(); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Horizontally to Left", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 0); }});
moveSubMenu.addMenuItem("Align Horizontally to Right", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 1); }});
moveSubMenu.addMenuItem("Align Horizontally to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 2); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Vertically to Top", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 0); }});
moveSubMenu.addMenuItem("Align Vertically to Bottom", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 1); }});
moveSubMenu.addMenuItem("Align Vertically to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 2); }});
editMenu.addMenuItem("Toggle Port Negation", KeyStroke.getKeyStroke('T', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.toggleNegatedCommand(); }});
editMenu.addSeparator();
m=editMenu.addMenuItem("Erase", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelected(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), null);
editMenu.addMenuItem("Erase Geometry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelectedGeometry(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Edit Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { EditOptions.editOptionsCommand(); } });
editMenu.addMenuItem("Key Bindings...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { keyBindingsCommand(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Get Info...", KeyStroke.getKeyStroke('I', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { getInfoCommand(); } });
Menu editInfoSubMenu = new Menu("Info", 'V');
editMenu.add(editInfoSubMenu);
editInfoSubMenu.addMenuItem("Attributes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Attributes.showDialog(); } });
editInfoSubMenu.addMenuItem("See All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { seeAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Hide All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { hideAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Default Parameter Visibility", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultParamVisibilityCommand(); } });
editInfoSubMenu.addSeparator();
editInfoSubMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(false); } });
editMenu.addSeparator();
Menu modeSubMenu = new Menu("Modes");
editMenu.add(modeSubMenu);
Menu modeSubMenuEdit = new Menu("Edit");
modeSubMenu.add(modeSubMenuEdit);
ButtonGroup editGroup = new ButtonGroup();
JMenuItem cursorClickZoomWire, cursorSelect, cursorWiring, cursorPan, cursorZoom, cursorOutline, cursorMeasure;
cursorClickZoomWire = modeSubMenuEdit.addRadioButton(ToolBar.cursorClickZoomWireName, true, editGroup, KeyStroke.getKeyStroke('S', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.clickZoomWireCommand(); } });
ToolBar.CursorMode cm = ToolBar.getCursorMode();
if (cm == ToolBar.CursorMode.CLICKZOOMWIRE) cursorClickZoomWire.setSelected(true);
if (ToolBar.secondaryInputModes) {
cursorSelect = modeSubMenuEdit.addRadioButton(ToolBar.cursorSelectName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectCommand(); } });
cursorWiring = modeSubMenuEdit.addRadioButton(ToolBar.cursorWiringName, false, editGroup, KeyStroke.getKeyStroke('W', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.wiringCommand(); } });
if (cm == ToolBar.CursorMode.SELECT) cursorSelect.setSelected(true);
if (cm == ToolBar.CursorMode.WIRE) cursorWiring.setSelected(true);
}
cursorPan = modeSubMenuEdit.addRadioButton(ToolBar.cursorPanName, false, editGroup, KeyStroke.getKeyStroke('P', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.panCommand(); } });
cursorZoom = modeSubMenuEdit.addRadioButton(ToolBar.cursorZoomName, false, editGroup, KeyStroke.getKeyStroke('Z', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.zoomCommand(); } });
cursorOutline = modeSubMenuEdit.addRadioButton(ToolBar.cursorOutlineName, false, editGroup, KeyStroke.getKeyStroke('Y', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.outlineEditCommand(); } });
cursorMeasure = modeSubMenuEdit.addRadioButton(ToolBar.cursorMeasureName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.measureCommand(); } });
if (cm == ToolBar.CursorMode.PAN) cursorPan.setSelected(true);
if (cm == ToolBar.CursorMode.ZOOM) cursorZoom.setSelected(true);
if (cm == ToolBar.CursorMode.OUTLINE) cursorOutline.setSelected(true);
if (cm == ToolBar.CursorMode.MEASURE) cursorMeasure.setSelected(true);
Menu modeSubMenuMovement = new Menu("Movement");
modeSubMenu.add(modeSubMenuMovement);
ButtonGroup movementGroup = new ButtonGroup();
JMenuItem moveFull, moveHalf, moveQuarter;
moveFull = modeSubMenuMovement.addRadioButton(ToolBar.moveFullName, true, movementGroup, KeyStroke.getKeyStroke('F', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.fullArrowDistanceCommand(); } });
moveHalf = modeSubMenuMovement.addRadioButton(ToolBar.moveHalfName, false, movementGroup, KeyStroke.getKeyStroke('H', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.halfArrowDistanceCommand(); } });
moveQuarter = modeSubMenuMovement.addRadioButton(ToolBar.moveQuarterName, false, movementGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.quarterArrowDistanceCommand(); } });
double ad = ToolBar.getArrowDistance();
if (ad == 1.0) moveFull.setSelected(true); else
if (ad == 0.5) moveHalf.setSelected(true); else
moveQuarter.setSelected(true);
Menu modeSubMenuSelect = new Menu("Select");
modeSubMenu.add(modeSubMenuSelect);
ButtonGroup selectGroup = new ButtonGroup();
JMenuItem selectArea, selectObjects;
selectArea = modeSubMenuSelect.addRadioButton(ToolBar.selectAreaName, true, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectAreaCommand(); } });
selectObjects = modeSubMenuSelect.addRadioButton(ToolBar.selectObjectsName, false, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectObjectsCommand(); } });
ToolBar.SelectMode sm = ToolBar.getSelectMode();
if (sm == ToolBar.SelectMode.AREA) selectArea.setSelected(true); else
selectObjects.setSelected(true);
modeSubMenuSelect.addCheckBox(ToolBar.specialSelectName, false, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.toggleSelectSpecialCommand(e); } });
editMenu.addMenuItem("Array...", KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Array.showArrayDialog(); } });
editMenu.addMenuItem("Insert Jog In Arc", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { insertJogInArcCommand(); } });
editMenu.addMenuItem("Change...", KeyStroke.getKeyStroke('C', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Change.showChangeDialog(); } });
Menu textSubMenu = new Menu("Text");
editMenu.add(textSubMenu);
textSubMenu.addMenuItem("Find Text...", KeyStroke.getKeyStroke('L', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { FindText.findTextDialog(); }});
textSubMenu.addMenuItem("Change Text Size...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ChangeText.changeTextDialog(); }});
textSubMenu.addMenuItem("Read Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.readTextCell(); }});
textSubMenu.addMenuItem("Save Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.writeTextCell(); }});
Menu cleanupSubMenu = new Menu("Cleanup Cell");
editMenu.add(cleanupSubMenu);
cleanupSubMenu.addMenuItem("Cleanup Pins", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(false); }});
cleanupSubMenu.addMenuItem("Cleanup Pins Everywhere", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(true); }});
cleanupSubMenu.addMenuItem("Show Nonmanhattan", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showNonmanhattanCommand(); }});
cleanupSubMenu.addMenuItem("Shorten Selected Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.shortenArcsCommand(); }});
Menu specialSubMenu = new Menu("Special Function");
editMenu.add(specialSubMenu);
specialSubMenu.addMenuItem("Show Undo List", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); } });
m = specialSubMenu.addMenuItem("Show Cursor Coordinates", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
m = specialSubMenu.addMenuItem("Artwork Appearance...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
Menu selListSubMenu = new Menu("Selection");
editMenu.add(selListSubMenu);
selListSubMenu.addMenuItem("Select All", KeyStroke.getKeyStroke('A', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllCommand(); }});
selListSubMenu.addMenuItem("Select All Like This", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLikeThisCommand(); }});
selListSubMenu.addMenuItem("Select Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEasyCommand(); }});
selListSubMenu.addMenuItem("Select Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectHardCommand(); }});
selListSubMenu.addMenuItem("Select Nothing", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectNothingCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Select Object...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SelectObject.selectObjectDialog(); }});
selListSubMenu.addMenuItem("Deselect All Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deselectAllArcsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Make Selected Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
selListSubMenu.addMenuItem("Make Selected Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeHardCommand(); }});
selListSubMenu.addSeparator();
m = selListSubMenu.addMenuItem("Push Selection", KeyStroke.getKeyStroke('1', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
m = selListSubMenu.addMenuItem("Pop Selection", KeyStroke.getKeyStroke('3', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Enclosed Objects", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEnclosedObjectsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Show Next Error", KeyStroke.getKeyStroke('>'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNextErrorCommand(); }});
selListSubMenu.addMenuItem("Show Previous Error", KeyStroke.getKeyStroke('<'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showPrevErrorCommand(); }});
/****************************** THE CELL MENU ******************************/
Menu cellMenu = new Menu("Cell", 'C');
menuBar.add(cellMenu);
cellMenu.addMenuItem("Edit Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.editCell); }});
cellMenu.addMenuItem("Place Cell Instance...", KeyStroke.getKeyStroke('N', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.newInstance); }});
cellMenu.addMenuItem("New Cell...", KeyStroke.getKeyStroke('N', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellCommand(); } });
cellMenu.addMenuItem("Rename Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.renameCell); }});
cellMenu.addMenuItem("Duplicate Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.duplicateCell); }});
cellMenu.addMenuItem("Delete Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.deleteCell); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("Delete Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteCellCommand(); } });
cellMenu.addMenuItem("Cell Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellControlCommand(); }});
cellMenu.addMenuItem("Cross-Library Copy...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { crossLibraryCopyCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Down Hierarchy", KeyStroke.getKeyStroke('D', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m = cellMenu.addMenuItem("Down Hierarchy In Place", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m.setEnabled(false);
cellMenu.addMenuItem("Up Hierarchy", KeyStroke.getKeyStroke('U', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { upHierCommand(); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("New Version of Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellVersionCommand(); } });
cellMenu.addMenuItem("Duplicate Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { duplicateCellCommand(); } });
cellMenu.addMenuItem("Delete Unused Old Versions", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteOldCellVersionsCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Describe this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.describeThisCellCommand(); } });
cellMenu.addMenuItem("General Cell Lists...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.generalCellListsCommand(); } });
Menu specListSubMenu = new Menu("Special Cell Lists");
cellMenu.add(specListSubMenu);
specListSubMenu.addMenuItem("List Nodes in this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listNodesInCellCommand(); }});
specListSubMenu.addMenuItem("List Cell Instances", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellInstancesCommand(); }});
specListSubMenu.addMenuItem("List Cell Usage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellUsageCommand(); }});
cellMenu.addMenuItem("Cell Parameters...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellParametersCommand(); } });
cellMenu.addSeparator();
Menu expandListSubMenu = new Menu("Expand Cell Instances");
cellMenu.add(expandListSubMenu);
expandListSubMenu.addMenuItem("One Level Down", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandOneLevelDownCommand(); }});
expandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandFullCommand(); }});
expandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandSpecificCommand(); }});
Menu unExpandListSubMenu = new Menu("Unexpand Cell Instances");
cellMenu.add(unExpandListSubMenu);
unExpandListSubMenu.addMenuItem("One Level Up", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandOneLevelUpCommand(); }});
unExpandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandFullCommand(); }});
unExpandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m = cellMenu.addMenuItem("Look Inside Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m.setEnabled(false);
cellMenu.addSeparator();
cellMenu.addMenuItem("Package Into Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.packageIntoCell(); } });
cellMenu.addMenuItem("Extract Cell Instance", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.extractCells(); } });
/****************************** THE EXPORT MENU ******************************/
Menu exportMenu = new Menu("Export", 'X');
menuBar.add(exportMenu);
exportMenu.addMenuItem("Create Export...", KeyStroke.getKeyStroke('E', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.newExportCommand(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Re-Export Everything", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportAll(); } });
exportMenu.addMenuItem("Re-Export Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportHighlighted(); } });
exportMenu.addMenuItem("Re-Export Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportPowerAndGround(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Delete Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExport(); } });
exportMenu.addMenuItem("Delete All Exports on Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsOnHighlighted(); } });
exportMenu.addMenuItem("Delete Exports in Area", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsInArea(); } });
exportMenu.addMenuItem("Move Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.moveExport(); } });
exportMenu.addMenuItem("Rename Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.renameExport(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Summarize Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(true); } });
exportMenu.addMenuItem("List Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(false); } });
exportMenu.addMenuItem("Show Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showExports(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Show Ports on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showPorts(); } });
/****************************** THE VIEW MENU ******************************/
Menu viewMenu = new Menu("View", 'V');
menuBar.add(viewMenu);
viewMenu.addMenuItem("View Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { viewControlCommand(); } });
viewMenu.addMenuItem("Change Cell's View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { changeViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Edit Layout View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editLayoutViewCommand(); } });
viewMenu.addMenuItem("Edit Schematic View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editMultiPageSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editIconViewCommand(); } });
viewMenu.addMenuItem("Edit VHDL View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editVHDLViewCommand(); } });
viewMenu.addMenuItem("Edit Documentation View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editDocViewCommand(); } });
viewMenu.addMenuItem("Edit Skeleton View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSkeletonViewCommand(); } });
viewMenu.addMenuItem("Edit Other View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editOtherViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Make Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeIconViewCommand(); } });
viewMenu.addMenuItem("Make Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeMultiPageSchematicViewCommand(); } });
/****************************** THE WINDOW MENU ******************************/
Menu windowMenu = new Menu("Window", 'W');
menuBar.add(windowMenu);
m = windowMenu.addMenuItem("Fill Display", KeyStroke.getKeyStroke('9', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { fullDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD9, buckyBit), null);
m = windowMenu.addMenuItem("Redisplay Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.redrawDisplay(); } });
m = windowMenu.addMenuItem("Zoom Out", KeyStroke.getKeyStroke('0', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomOutDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, buckyBit), null);
m = windowMenu.addMenuItem("Zoom In", KeyStroke.getKeyStroke('7', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomInDisplay(); } });
Menu specialZoomSubMenu = new Menu("Special Zoom");
windowMenu.add(specialZoomSubMenu);
m = specialZoomSubMenu.addMenuItem("Focus on Highlighted", KeyStroke.getKeyStroke('F', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { focusOnHighlighted(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD5, buckyBit), null);
m = specialZoomSubMenu.addMenuItem("Zoom Box", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomBoxCommand(); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD7, buckyBit), null);
specialZoomSubMenu.addMenuItem("Make Grid Just Visible", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeGridJustVisibleCommand(); }});
specialZoomSubMenu.addMenuItem("Match Other Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { matchOtherWindowCommand(); }});
windowMenu.addSeparator();
m = windowMenu.addMenuItem("Pan Left", KeyStroke.getKeyStroke('4', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD4, buckyBit), null);
m = windowMenu.addMenuItem("Pan Right", KeyStroke.getKeyStroke('6', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD6, buckyBit), null);
m = windowMenu.addMenuItem("Pan Up", KeyStroke.getKeyStroke('8', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD8, buckyBit), null);
m = windowMenu.addMenuItem("Pan Down", KeyStroke.getKeyStroke('2', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD2, buckyBit), null);
Menu panningDistanceSubMenu = new Menu("Panning Distance");
windowMenu.add(panningDistanceSubMenu);
ButtonGroup windowPanGroup = new ButtonGroup();
JMenuItem panSmall, panMedium, panLarge;
panSmall = panningDistanceSubMenu.addRadioButton("Small", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.15); } });
panMedium = panningDistanceSubMenu.addRadioButton("Medium", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.3); } });
panLarge = panningDistanceSubMenu.addRadioButton("Large", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.6); } });
panLarge.setSelected(true);
windowMenu.addSeparator();
windowMenu.addMenuItem("Toggle Grid", KeyStroke.getKeyStroke('G', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { toggleGridCommand(); } });
windowMenu.addSeparator();
Menu windowPartitionSubMenu = new Menu("Adjust Position");
windowMenu.add(windowPartitionSubMenu);
windowPartitionSubMenu.addMenuItem("Tile Horizontally", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { tileHorizontallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Tile Vertically", KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { tileVerticallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Cascade", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cascadeWindowsCommand(); }});
windowMenu.addMenuItem("Close Window", KeyStroke.getKeyStroke(KeyEvent.VK_W, buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { WindowFrame curWF = WindowFrame.getCurrentWindowFrame();
curWF.finished(); }});
if (!TopLevel.isMDIMode()) {
windowMenu.addSeparator();
windowMenu.addMenuItem("Move to Other Display", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { moveToOtherDisplayCommand(); } });
}
windowMenu.addSeparator();
windowMenu.addMenuItem("Layer Visibility...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerVisibilityCommand(); } });
Menu colorSubMenu = new Menu("Color");
windowMenu.add(colorSubMenu);
colorSubMenu.addMenuItem("Restore Default Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultBackgroundCommand(); }});
colorSubMenu.addMenuItem("Black Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { blackBackgroundCommand(); }});
colorSubMenu.addMenuItem("White Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { whiteBackgroundCommand(); }});
Menu messagesSubMenu = new Menu("Messages Window");
windowMenu.add(messagesSubMenu);
messagesSubMenu.addMenuItem("Save Messages", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().save(); }});
messagesSubMenu.addMenuItem("Clear", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().clear(); }});
/****************************** THE TOOL MENU ******************************/
Menu toolMenu = new Menu("Tool", 'T');
menuBar.add(toolMenu);
//------------------- DRC
Menu drcSubMenu = new Menu("DRC", 'D');
toolMenu.add(drcSubMenu);
drcSubMenu.addMenuItem("Check Hierarchically", KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkHierarchically(); }});
drcSubMenu.addMenuItem("Check Selection Area Hierarchically", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkAreaHierarchically(); }});
//------------------- Simulation (SPICE)
Menu spiceSimulationSubMenu = new Menu("Simulation (SPICE)", 'S');
toolMenu.add(spiceSimulationSubMenu);
spiceSimulationSubMenu.addMenuItem("Write SPICE Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.SPICE, true); }});
spiceSimulationSubMenu.addMenuItem("Write CDL Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CDL, true); }});
spiceSimulationSubMenu.addMenuItem("Plot Spice Listing...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotSpiceResults(); }});
m = spiceSimulationSubMenu.addMenuItem("Plot Spice for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
spiceSimulationSubMenu.addMenuItem("Set Spice Model...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setSpiceModel(); }});
spiceSimulationSubMenu.addMenuItem("Add Multiplier", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
spiceSimulationSubMenu.addSeparator();
spiceSimulationSubMenu.addMenuItem("Set Generic SPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 2 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_2_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 3 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_3_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set HSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_H_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set PSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_P_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set GnuCap Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_GC_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SmartSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_SM_TEMPLATE_KEY); }});
//------------------- Simulation (Verilog)
Menu verilogSimulationSubMenu = new Menu("Simulation (Verilog)", 'V');
toolMenu.add(verilogSimulationSubMenu);
verilogSimulationSubMenu.addMenuItem("Write Verilog Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.VERILOG, true); } });
verilogSimulationSubMenu.addMenuItem("Plot Verilog VCD Dump...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotVerilogResults(); }});
m = verilogSimulationSubMenu.addMenuItem("Plot Verilog for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
verilogSimulationSubMenu.addSeparator();
verilogSimulationSubMenu.addMenuItem("Set Verilog Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Verilog.VERILOG_TEMPLATE_KEY); }});
verilogSimulationSubMenu.addSeparator();
Menu verilogWireTypeSubMenu = new Menu("Set Verilog Wire", 'W');
verilogWireTypeSubMenu.addMenuItem("Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(0); }});
verilogWireTypeSubMenu.addMenuItem("Trireg", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(1); }});
verilogWireTypeSubMenu.addMenuItem("Default", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(2); }});
verilogSimulationSubMenu.add(verilogWireTypeSubMenu);
Menu transistorStrengthSubMenu = new Menu("Transistor Strength", 'T');
transistorStrengthSubMenu.addMenuItem("Weak", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(true); }});
transistorStrengthSubMenu.addMenuItem("Normal", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(false); }});
verilogSimulationSubMenu.add(transistorStrengthSubMenu);
//------------------- Simulation (others)
Menu netlisters = new Menu("Simulation (others)");
toolMenu.add(netlisters);
netlisters.addMenuItem("Write IRSIM Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { irsimNetlistCommand(); }});
netlisters.addMenuItem("Write Maxwell Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.MAXWELL, true); } });
//------------------- ERC
Menu ercSubMenu = new Menu("ERC", 'E');
toolMenu.add(ercSubMenu);
ercSubMenu.addMenuItem("Check Wells", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ERCWellCheck.analyzeCurCell(true); } });
ercSubMenu.addMenuItem("Antenna Check", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { new ERCAntenna(); } });
//------------------- Network
Menu networkSubMenu = new Menu("Network", 'N');
toolMenu.add(networkSubMenu);
networkSubMenu.addMenuItem("Show Network", KeyStroke.getKeyStroke('K', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNetworkCommand(); } });
networkSubMenu.addMenuItem("List Networks", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listNetworksCommand(); } });
networkSubMenu.addMenuItem("List Connections on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listConnectionsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports below Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsBelowNetworkCommand(); } });
networkSubMenu.addMenuItem("List Geometry on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listGeometryOnNetworkCommand(); } });
networkSubMenu.addSeparator();
networkSubMenu.addMenuItem("Show Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showPowerAndGround(); } });
networkSubMenu.addMenuItem("Validate Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { validatePowerAndGround(); } });
networkSubMenu.addMenuItem("Redo Network Numbering", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { redoNetworkNumberingCommand(); } });
//------------------- Logical Effort
Menu logEffortSubMenu = new Menu("Logical Effort", 'L');
logEffortSubMenu.addMenuItem("Optimize for Equal Gate Delays", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { optimizeEqualGateDelaysCommand(); }});
logEffortSubMenu.addMenuItem("Print Info for Selected Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { printLEInfoCommand(); }});
toolMenu.add(logEffortSubMenu);
//------------------- Routing
Menu routingSubMenu = new Menu("Routing", 'R');
toolMenu.add(routingSubMenu);
routingSubMenu.addCheckBox("Enable Auto-Stitching", Routing.isAutoStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableAutoStitching(e); } });
routingSubMenu.addMenuItem("Auto-Stitch Now", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(false, true); }});
routingSubMenu.addMenuItem("Auto-Stitch Highlighted Now", KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(true, true); }});
routingSubMenu.addSeparator();
routingSubMenu.addCheckBox("Enable Mimic-Stitching", Routing.isMimicStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableMimicStitching(e); }});
routingSubMenu.addMenuItem("Mimic-Stitch Now", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { MimicStitch.mimicStitch(true); }});
routingSubMenu.addMenuItem("Mimic Selected", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.tool.mimicSelected(); }});
routingSubMenu.addSeparator();
routingSubMenu.addMenuItem("Get Unrouted Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { getUnroutedArcCommand(); }});
m = routingSubMenu.addMenuItem("Copy Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
m = routingSubMenu.addMenuItem("Paste Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
//------------------- Generation
Menu generationSubMenu = new Menu("Generation", 'G');
toolMenu.add(generationSubMenu);
generationSubMenu.addMenuItem("Coverage Implants Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { implantGeneratorCommand(true, false); }});
generationSubMenu.addMenuItem("Pad Frame Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { padFrameGeneratorCommand(); }});
toolMenu.addSeparator();
toolMenu.addMenuItem("Tool Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolOptions.toolOptionsCommand(); } });
toolMenu.addMenuItem("List Tools",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listToolsCommand(); } });
Menu languagesSubMenu = new Menu("Languages");
languagesSubMenu.addMenuItem("Run Java Bean Shell Script", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { javaBshScriptCommand(); }});
toolMenu.add(languagesSubMenu);
/****************************** THE HELP MENU ******************************/
Menu helpMenu = new Menu("Help", 'H');
menuBar.add(helpMenu);
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
helpMenu.addMenuItem("About Electric...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { aboutCommand(); } });
}
helpMenu.addMenuItem("Help Index", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { toolTipsCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Describe this Technology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { describeTechnologyCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Make fake circuitry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeFakeCircuitryCommand(); } });
helpMenu.addMenuItem("Make fake simulation window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { WaveformWindow.makeFakeWaveformCommand(); }});
// helpMenu.addMenuItem("Whit Diffie's design...", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { whitDiffieCommand(); } });
/****************************** Russell's TEST MENU ******************************/
Menu russMenu = new Menu("Russell", 'R');
menuBar.add(russMenu);
russMenu.addMenuItem("Generate fill cells", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.FillLibGen();
}
});
russMenu.addMenuItem("Gate Generator Regression", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateRegression();
}
});
russMenu.addMenuItem("Generate gate layouts", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateLayoutGenerator();
}
});
russMenu.addMenuItem("create flat netlists for Ivan", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.IvanFlat();
}
});
russMenu.addMenuItem("layout flat", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.LayFlat();
}
});
russMenu.addMenuItem("Jemini", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.ncc.NccJob();
}
});
russMenu.addMenuItem("Random Test", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.Test();
}
});
/****************************** Jon's TEST MENU ******************************/
Menu jongMenu = new Menu("JonG", 'J');
menuBar.add(jongMenu);
jongMenu.addMenuItem("Describe Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(false); }});
jongMenu.addMenuItem("Describe Proto Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(true); }});
jongMenu.addMenuItem("Describe Current Library Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listLibVars(); }});
jongMenu.addMenuItem("Eval Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { evalVarsOnObject(); }});
jongMenu.addMenuItem("LE test1", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { LENetlister.test1(); }});
jongMenu.addMenuItem("Open Purple Lib", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { openP4libCommand(); }});
//jongMenu.addMenuItem("Check Exports", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { checkExports(); }});
/****************************** Gilda's TEST MENU ******************************/
Menu gildaMenu = new Menu("Gilda", 'G');
menuBar.add(gildaMenu);
gildaMenu.addMenuItem("Merge Polyons", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, true);}});
gildaMenu.addMenuItem("Covering Implants", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, false);}});
gildaMenu.addMenuItem("Covering Implants Old", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(false, false);}});
gildaMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(true); } });
/********************************* Hidden Menus *******************************/
Menu wiringShortcuts = new Menu("Circuit Editing");
menuBar.addHidden(wiringShortcuts);
wiringShortcuts.addMenuItem("Wire to Poly", KeyStroke.getKeyStroke(KeyEvent.VK_0, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(0); }});
wiringShortcuts.addMenuItem("Wire to M1", KeyStroke.getKeyStroke(KeyEvent.VK_1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(1); }});
wiringShortcuts.addMenuItem("Wire to M2", KeyStroke.getKeyStroke(KeyEvent.VK_2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(2); }});
wiringShortcuts.addMenuItem("Wire to M3", KeyStroke.getKeyStroke(KeyEvent.VK_3, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(3); }});
wiringShortcuts.addMenuItem("Wire to M4", KeyStroke.getKeyStroke(KeyEvent.VK_4, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(4); }});
wiringShortcuts.addMenuItem("Wire to M5", KeyStroke.getKeyStroke(KeyEvent.VK_5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(5); }});
wiringShortcuts.addMenuItem("Wire to M6", KeyStroke.getKeyStroke(KeyEvent.VK_6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(6); }});
wiringShortcuts.addMenuItem("Switch Wiring Target", KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.switchWiringTarget(); }});
// return the menu bar
return menuBar;
}
| public static MenuBar createMenuBar()
{
// create the menu bar
MenuBar menuBar = new MenuBar();
MenuItem m;
int buckyBit = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
/****************************** THE FILE MENU ******************************/
Menu fileMenu = new Menu("File", 'F');
menuBar.add(fileMenu);
fileMenu.addMenuItem("New Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newLibraryCommand(); } });
fileMenu.addMenuItem("Open Library", KeyStroke.getKeyStroke('O', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { openLibraryCommand(); } });
Menu importSubMenu = new Menu("Import");
fileMenu.add(importSubMenu);
importSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { importLibraryCommand(); } });
fileMenu.addMenuItem("I/O Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { IOOptions.ioOptionsCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Close Library", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { closeLibraryCommand(Library.getCurrent()); } });
fileMenu.addMenuItem("Save Library", KeyStroke.getKeyStroke('S', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.ELIB); } });
fileMenu.addMenuItem("Save Library as...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAsLibraryCommand(); } });
fileMenu.addMenuItem("Save All Libraries",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveAllLibrariesCommand(); } });
Menu exportSubMenu = new Menu("Export");
fileMenu.add(exportSubMenu);
exportSubMenu.addMenuItem("CIF (Caltech Intermediate Format)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CIF, false); } });
exportSubMenu.addMenuItem("GDS II (Stream)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.GDS, false); } });
exportSubMenu.addMenuItem("PostScript", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.POSTSCRIPT, false); } });
exportSubMenu.addMenuItem("Readable Dump", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { saveLibraryCommand(Library.getCurrent(), OpenFile.Type.READABLEDUMP); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Change Current Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.changeCurrentLibraryCommand(); } });
fileMenu.addMenuItem("List Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.listLibrariesCommand(); } });
fileMenu.addMenuItem("Rename Library...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.renameLibraryCommand(); } });
fileMenu.addMenuItem("Mark All Libraries for Saving", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.markAllLibrariesForSavingCommand(); } });
fileMenu.addMenuItem("Repair Libraries", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.checkAndRepairCommand(); } });
fileMenu.addSeparator();
fileMenu.addMenuItem("Print...", KeyStroke.getKeyStroke('P', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { printCommand(); } });
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
fileMenu.addSeparator();
fileMenu.addMenuItem("Quit", KeyStroke.getKeyStroke('Q', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { quitCommand(); } });
}
/****************************** THE EDIT MENU ******************************/
Menu editMenu = new Menu("Edit", 'E');
menuBar.add(editMenu);
editMenu.addMenuItem("Cut", KeyStroke.getKeyStroke('X', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.cut(); } });
editMenu.addMenuItem("Copy", KeyStroke.getKeyStroke('C', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.copy(); } });
editMenu.addMenuItem("Paste", KeyStroke.getKeyStroke('V', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.paste(); } });
editMenu.addMenuItem("Duplicate", KeyStroke.getKeyStroke('M', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { Clipboard.duplicate(); } });
editMenu.addSeparator();
Menu arcSubMenu = new Menu("Arc", 'A');
editMenu.add(arcSubMenu);
arcSubMenu.addMenuItem("Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcRigidCommand(); }});
arcSubMenu.addMenuItem("Not Rigid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotRigidCommand(); }});
arcSubMenu.addMenuItem("Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcFixedAngleCommand(); }});
arcSubMenu.addMenuItem("Not Fixed Angle", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcNotFixedAngleCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Toggle Directionality", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcDirectionalCommand(); }});
arcSubMenu.addMenuItem("Toggle Ends Extension", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcEndsExtendCommand(); }});
arcSubMenu.addMenuItem("Reverse", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcReverseCommand(); }});
arcSubMenu.addMenuItem("Toggle Head-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipHeadCommand(); }});
arcSubMenu.addMenuItem("Toggle Tail-Skip", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.arcSkipTailCommand(); }});
arcSubMenu.addSeparator();
arcSubMenu.addMenuItem("Rip Bus", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.ripBus(); }});
editMenu.addSeparator();
editMenu.addMenuItem("Undo", KeyStroke.getKeyStroke('Z', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { undoCommand(); } });
editMenu.addMenuItem("Redo", KeyStroke.getKeyStroke('Y', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { redoCommand(); } });
editMenu.addSeparator();
Menu rotateSubMenu = new Menu("Rotate", 'R');
editMenu.add(rotateSubMenu);
rotateSubMenu.addMenuItem("90 Degrees Clockwise", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(2700); }});
rotateSubMenu.addMenuItem("90 Degrees Counterclockwise", KeyStroke.getKeyStroke('J', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(900); }});
rotateSubMenu.addMenuItem("180 Degrees", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(1800); }});
rotateSubMenu.addMenuItem("Other...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.rotateObjects(0); }});
Menu mirrorSubMenu = new Menu("Mirror", 'M');
editMenu.add(mirrorSubMenu);
mirrorSubMenu.addMenuItem("Horizontally (flip over X-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(true); }});
mirrorSubMenu.addMenuItem("Vertically (flip over Y-axis)", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.mirrorObjects(false); }});
Menu sizeSubMenu = new Menu("Size", 'S');
editMenu.add(sizeSubMenu);
sizeSubMenu.addMenuItem("Interactively", KeyStroke.getKeyStroke('B', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeObjects(); } });
sizeSubMenu.addMenuItem("All Selected Nodes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllNodes(); }});
sizeSubMenu.addMenuItem("All Selected Arcs...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SizeListener.sizeAllArcs(); }});
Menu moveSubMenu = new Menu("Move", 'V');
editMenu.add(moveSubMenu);
moveSubMenu.addMenuItem("Spread...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Spread.showSpreadDialog(); }});
moveSubMenu.addMenuItem("Move Objects By...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { MoveBy.showMoveByDialog(); }});
moveSubMenu.addMenuItem("Align to Grid", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignToGrid(); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Horizontally to Left", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 0); }});
moveSubMenu.addMenuItem("Align Horizontally to Right", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 1); }});
moveSubMenu.addMenuItem("Align Horizontally to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(true, 2); }});
moveSubMenu.addSeparator();
moveSubMenu.addMenuItem("Align Vertically to Top", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 0); }});
moveSubMenu.addMenuItem("Align Vertically to Bottom", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 1); }});
moveSubMenu.addMenuItem("Align Vertically to Center", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.alignNodes(false, 2); }});
editMenu.addMenuItem("Toggle Port Negation", KeyStroke.getKeyStroke('T', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.toggleNegatedCommand(); }});
editMenu.addSeparator();
m=editMenu.addMenuItem("Erase", KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelected(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), null);
editMenu.addMenuItem("Erase Geometry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.deleteSelectedGeometry(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Edit Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { EditOptions.editOptionsCommand(); } });
editMenu.addMenuItem("Key Bindings...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { keyBindingsCommand(); } });
editMenu.addSeparator();
editMenu.addMenuItem("Get Info...", KeyStroke.getKeyStroke('I', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { getInfoCommand(); } });
Menu editInfoSubMenu = new Menu("Info", 'V');
editMenu.add(editInfoSubMenu);
editInfoSubMenu.addMenuItem("Attributes...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Attributes.showDialog(); } });
editInfoSubMenu.addMenuItem("See All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { seeAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Hide All Parameters on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { hideAllParametersCommand(); } });
editInfoSubMenu.addMenuItem("Default Parameter Visibility", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultParamVisibilityCommand(); } });
editInfoSubMenu.addSeparator();
editInfoSubMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(false); } });
editMenu.addSeparator();
Menu modeSubMenu = new Menu("Modes");
editMenu.add(modeSubMenu);
Menu modeSubMenuEdit = new Menu("Edit");
modeSubMenu.add(modeSubMenuEdit);
ButtonGroup editGroup = new ButtonGroup();
JMenuItem cursorClickZoomWire, cursorSelect, cursorWiring, cursorPan, cursorZoom, cursorOutline, cursorMeasure;
cursorClickZoomWire = modeSubMenuEdit.addRadioButton(ToolBar.cursorClickZoomWireName, true, editGroup, KeyStroke.getKeyStroke('S', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.clickZoomWireCommand(); } });
ToolBar.CursorMode cm = ToolBar.getCursorMode();
if (cm == ToolBar.CursorMode.CLICKZOOMWIRE) cursorClickZoomWire.setSelected(true);
if (ToolBar.secondaryInputModes) {
cursorSelect = modeSubMenuEdit.addRadioButton(ToolBar.cursorSelectName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectCommand(); } });
cursorWiring = modeSubMenuEdit.addRadioButton(ToolBar.cursorWiringName, false, editGroup, KeyStroke.getKeyStroke('W', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.wiringCommand(); } });
if (cm == ToolBar.CursorMode.SELECT) cursorSelect.setSelected(true);
if (cm == ToolBar.CursorMode.WIRE) cursorWiring.setSelected(true);
}
cursorPan = modeSubMenuEdit.addRadioButton(ToolBar.cursorPanName, false, editGroup, KeyStroke.getKeyStroke('P', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.panCommand(); } });
cursorZoom = modeSubMenuEdit.addRadioButton(ToolBar.cursorZoomName, false, editGroup, KeyStroke.getKeyStroke('Z', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.zoomCommand(); } });
cursorOutline = modeSubMenuEdit.addRadioButton(ToolBar.cursorOutlineName, false, editGroup, KeyStroke.getKeyStroke('Y', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.outlineEditCommand(); } });
cursorMeasure = modeSubMenuEdit.addRadioButton(ToolBar.cursorMeasureName, false, editGroup, KeyStroke.getKeyStroke('M', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.measureCommand(); } });
if (cm == ToolBar.CursorMode.PAN) cursorPan.setSelected(true);
if (cm == ToolBar.CursorMode.ZOOM) cursorZoom.setSelected(true);
if (cm == ToolBar.CursorMode.OUTLINE) cursorOutline.setSelected(true);
if (cm == ToolBar.CursorMode.MEASURE) cursorMeasure.setSelected(true);
Menu modeSubMenuMovement = new Menu("Movement");
modeSubMenu.add(modeSubMenuMovement);
ButtonGroup movementGroup = new ButtonGroup();
JMenuItem moveFull, moveHalf, moveQuarter;
moveFull = modeSubMenuMovement.addRadioButton(ToolBar.moveFullName, true, movementGroup, KeyStroke.getKeyStroke('F', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.fullArrowDistanceCommand(); } });
moveHalf = modeSubMenuMovement.addRadioButton(ToolBar.moveHalfName, false, movementGroup, KeyStroke.getKeyStroke('H', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.halfArrowDistanceCommand(); } });
moveQuarter = modeSubMenuMovement.addRadioButton(ToolBar.moveQuarterName, false, movementGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.quarterArrowDistanceCommand(); } });
double ad = ToolBar.getArrowDistance();
if (ad == 1.0) moveFull.setSelected(true); else
if (ad == 0.5) moveHalf.setSelected(true); else
moveQuarter.setSelected(true);
Menu modeSubMenuSelect = new Menu("Select");
modeSubMenu.add(modeSubMenuSelect);
ButtonGroup selectGroup = new ButtonGroup();
JMenuItem selectArea, selectObjects;
selectArea = modeSubMenuSelect.addRadioButton(ToolBar.selectAreaName, true, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectAreaCommand(); } });
selectObjects = modeSubMenuSelect.addRadioButton(ToolBar.selectObjectsName, false, selectGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.selectObjectsCommand(); } });
ToolBar.SelectMode sm = ToolBar.getSelectMode();
if (sm == ToolBar.SelectMode.AREA) selectArea.setSelected(true); else
selectObjects.setSelected(true);
modeSubMenuSelect.addCheckBox(ToolBar.specialSelectName, false, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolBar.toggleSelectSpecialCommand(e); } });
editMenu.addMenuItem("Array...", KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Array.showArrayDialog(); } });
editMenu.addMenuItem("Insert Jog In Arc", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { insertJogInArcCommand(); } });
editMenu.addMenuItem("Change...", KeyStroke.getKeyStroke('C', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { Change.showChangeDialog(); } });
Menu textSubMenu = new Menu("Text");
editMenu.add(textSubMenu);
textSubMenu.addMenuItem("Find Text...", KeyStroke.getKeyStroke('L', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { FindText.findTextDialog(); }});
textSubMenu.addMenuItem("Change Text Size...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ChangeText.changeTextDialog(); }});
textSubMenu.addMenuItem("Read Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.readTextCell(); }});
textSubMenu.addMenuItem("Save Text Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TextWindow.writeTextCell(); }});
Menu cleanupSubMenu = new Menu("Cleanup Cell");
editMenu.add(cleanupSubMenu);
cleanupSubMenu.addMenuItem("Cleanup Pins", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(false); }});
cleanupSubMenu.addMenuItem("Cleanup Pins Everywhere", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.cleanupPinsCommand(true); }});
cleanupSubMenu.addMenuItem("Show Nonmanhattan", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.showNonmanhattanCommand(); }});
cleanupSubMenu.addMenuItem("Shorten Selected Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.shortenArcsCommand(); }});
Menu specialSubMenu = new Menu("Special Function");
editMenu.add(specialSubMenu);
specialSubMenu.addMenuItem("Show Undo List", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); } });
m = specialSubMenu.addMenuItem("Show Cursor Coordinates", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
m = specialSubMenu.addMenuItem("Artwork Appearance...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showUndoListCommand(); }});
m.setEnabled(false);
Menu selListSubMenu = new Menu("Selection");
editMenu.add(selListSubMenu);
selListSubMenu.addMenuItem("Select All", KeyStroke.getKeyStroke('A', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllCommand(); }});
selListSubMenu.addMenuItem("Select All Like This", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectAllLikeThisCommand(); }});
selListSubMenu.addMenuItem("Select Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEasyCommand(); }});
selListSubMenu.addMenuItem("Select Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectHardCommand(); }});
selListSubMenu.addMenuItem("Select Nothing", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectNothingCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Select Object...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { SelectObject.selectObjectDialog(); }});
selListSubMenu.addMenuItem("Deselect All Arcs", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deselectAllArcsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Make Selected Easy", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
selListSubMenu.addMenuItem("Make Selected Hard", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeHardCommand(); }});
selListSubMenu.addSeparator();
m = selListSubMenu.addMenuItem("Push Selection", KeyStroke.getKeyStroke('1', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
m = selListSubMenu.addMenuItem("Pop Selection", KeyStroke.getKeyStroke('3', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { selectMakeEasyCommand(); }});
m.setEnabled(false);
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Enclosed Objects", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { selectEnclosedObjectsCommand(); }});
selListSubMenu.addSeparator();
selListSubMenu.addMenuItem("Show Next Error", KeyStroke.getKeyStroke('>'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNextErrorCommand(); }});
selListSubMenu.addMenuItem("Show Previous Error", KeyStroke.getKeyStroke('<'),
new ActionListener() { public void actionPerformed(ActionEvent e) { showPrevErrorCommand(); }});
/****************************** THE CELL MENU ******************************/
Menu cellMenu = new Menu("Cell", 'C');
menuBar.add(cellMenu);
cellMenu.addMenuItem("Edit Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.editCell); }});
cellMenu.addMenuItem("Place Cell Instance...", KeyStroke.getKeyStroke('N', 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.newInstance); }});
cellMenu.addMenuItem("New Cell...", KeyStroke.getKeyStroke('N', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellCommand(); } });
cellMenu.addMenuItem("Rename Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.renameCell); }});
cellMenu.addMenuItem("Duplicate Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.duplicateCell); }});
cellMenu.addMenuItem("Delete Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellBrowserCommand(CellBrowser.DoAction.deleteCell); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("Delete Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteCellCommand(); } });
cellMenu.addMenuItem("Cell Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellControlCommand(); }});
cellMenu.addMenuItem("Cross-Library Copy...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { crossLibraryCopyCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Down Hierarchy", KeyStroke.getKeyStroke('D', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m = cellMenu.addMenuItem("Down Hierarchy In Place", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { downHierCommand(); }});
m.setEnabled(false);
cellMenu.addMenuItem("Up Hierarchy", KeyStroke.getKeyStroke('U', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { upHierCommand(); }});
cellMenu.addSeparator();
cellMenu.addMenuItem("New Version of Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { newCellVersionCommand(); } });
cellMenu.addMenuItem("Duplicate Current Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { duplicateCellCommand(); } });
cellMenu.addMenuItem("Delete Unused Old Versions", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { deleteOldCellVersionsCommand(); } });
cellMenu.addSeparator();
cellMenu.addMenuItem("Describe this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.describeThisCellCommand(); } });
cellMenu.addMenuItem("General Cell Lists...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.generalCellListsCommand(); } });
Menu specListSubMenu = new Menu("Special Cell Lists");
cellMenu.add(specListSubMenu);
specListSubMenu.addMenuItem("List Nodes in this Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listNodesInCellCommand(); }});
specListSubMenu.addMenuItem("List Cell Instances", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellInstancesCommand(); }});
specListSubMenu.addMenuItem("List Cell Usage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CellLists.listCellUsageCommand(); }});
cellMenu.addMenuItem("Cell Parameters...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cellParametersCommand(); } });
cellMenu.addSeparator();
Menu expandListSubMenu = new Menu("Expand Cell Instances");
cellMenu.add(expandListSubMenu);
expandListSubMenu.addMenuItem("One Level Down", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandOneLevelDownCommand(); }});
expandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandFullCommand(); }});
expandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { expandSpecificCommand(); }});
Menu unExpandListSubMenu = new Menu("Unexpand Cell Instances");
cellMenu.add(unExpandListSubMenu);
unExpandListSubMenu.addMenuItem("One Level Up", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandOneLevelUpCommand(); }});
unExpandListSubMenu.addMenuItem("All the Way", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandFullCommand(); }});
unExpandListSubMenu.addMenuItem("Specified Amount", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m = cellMenu.addMenuItem("Look Inside Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { unexpandSpecificCommand(); }});
m.setEnabled(false);
cellMenu.addSeparator();
cellMenu.addMenuItem("Package Into Cell...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.packageIntoCell(); } });
cellMenu.addMenuItem("Extract Cell Instance", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.extractCells(); } });
/****************************** THE EXPORT MENU ******************************/
Menu exportMenu = new Menu("Export", 'X');
menuBar.add(exportMenu);
exportMenu.addMenuItem("Create Export...", KeyStroke.getKeyStroke('E', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.newExportCommand(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Re-Export Everything", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportAll(); } });
exportMenu.addMenuItem("Re-Export Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportHighlighted(); } });
exportMenu.addMenuItem("Re-Export Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.reExportPowerAndGround(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Delete Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExport(); } });
exportMenu.addMenuItem("Delete All Exports on Highlighted", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsOnHighlighted(); } });
exportMenu.addMenuItem("Delete Exports in Area", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.deleteExportsInArea(); } });
exportMenu.addMenuItem("Move Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.moveExport(); } });
exportMenu.addMenuItem("Rename Export", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.renameExport(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Summarize Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(true); } });
exportMenu.addMenuItem("List Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.describeExports(false); } });
exportMenu.addMenuItem("Show Exports", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showExports(); } });
exportMenu.addSeparator();
exportMenu.addMenuItem("Show Ports on Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ExportChanges.showPorts(); } });
/****************************** THE VIEW MENU ******************************/
Menu viewMenu = new Menu("View", 'V');
menuBar.add(viewMenu);
viewMenu.addMenuItem("View Control...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { viewControlCommand(); } });
viewMenu.addMenuItem("Change Cell's View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { changeViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Edit Layout View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editLayoutViewCommand(); } });
viewMenu.addMenuItem("Edit Schematic View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editMultiPageSchematicViewCommand(); } });
viewMenu.addMenuItem("Edit Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editIconViewCommand(); } });
viewMenu.addMenuItem("Edit VHDL View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editVHDLViewCommand(); } });
viewMenu.addMenuItem("Edit Documentation View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editDocViewCommand(); } });
viewMenu.addMenuItem("Edit Skeleton View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editSkeletonViewCommand(); } });
viewMenu.addMenuItem("Edit Other View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { editOtherViewCommand(); } });
viewMenu.addSeparator();
viewMenu.addMenuItem("Make Icon View", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeIconViewCommand(); } });
viewMenu.addMenuItem("Make Multi-Page Schematic View...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { CircuitChanges.makeMultiPageSchematicViewCommand(); } });
/****************************** THE WINDOW MENU ******************************/
Menu windowMenu = new Menu("Window", 'W');
menuBar.add(windowMenu);
m = windowMenu.addMenuItem("Fill Display", KeyStroke.getKeyStroke('9', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { fullDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD9, buckyBit), null);
m = windowMenu.addMenuItem("Redisplay Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.redrawDisplay(); } });
m = windowMenu.addMenuItem("Zoom Out", KeyStroke.getKeyStroke('0', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomOutDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, buckyBit), null);
m = windowMenu.addMenuItem("Zoom In", KeyStroke.getKeyStroke('7', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomInDisplay(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD7, buckyBit), null);
Menu specialZoomSubMenu = new Menu("Special Zoom");
windowMenu.add(specialZoomSubMenu);
m = specialZoomSubMenu.addMenuItem("Focus on Highlighted", KeyStroke.getKeyStroke('F', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { focusOnHighlighted(); } });
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD5, buckyBit), null);
m = specialZoomSubMenu.addMenuItem("Zoom Box", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { zoomBoxCommand(); }});
specialZoomSubMenu.addMenuItem("Make Grid Just Visible", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeGridJustVisibleCommand(); }});
specialZoomSubMenu.addMenuItem("Match Other Window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { matchOtherWindowCommand(); }});
windowMenu.addSeparator();
m = windowMenu.addMenuItem("Pan Left", KeyStroke.getKeyStroke('4', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD4, buckyBit), null);
m = windowMenu.addMenuItem("Pan Right", KeyStroke.getKeyStroke('6', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panX(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD6, buckyBit), null);
m = windowMenu.addMenuItem("Pan Up", KeyStroke.getKeyStroke('8', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), -1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD8, buckyBit), null);
m = windowMenu.addMenuItem("Pan Down", KeyStroke.getKeyStroke('2', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panY(WindowFrame.getCurrentWindowFrame(), 1); }});
menuBar.addDefaultKeyBinding(m, KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD2, buckyBit), null);
Menu panningDistanceSubMenu = new Menu("Panning Distance");
windowMenu.add(panningDistanceSubMenu);
ButtonGroup windowPanGroup = new ButtonGroup();
JMenuItem panSmall, panMedium, panLarge;
panSmall = panningDistanceSubMenu.addRadioButton("Small", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.15); } });
panMedium = panningDistanceSubMenu.addRadioButton("Medium", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.3); } });
panLarge = panningDistanceSubMenu.addRadioButton("Large", true, windowPanGroup, null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ZoomAndPanListener.panningDistanceCommand(0.6); } });
panLarge.setSelected(true);
windowMenu.addSeparator();
windowMenu.addMenuItem("Toggle Grid", KeyStroke.getKeyStroke('G', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { toggleGridCommand(); } });
windowMenu.addSeparator();
Menu windowPartitionSubMenu = new Menu("Adjust Position");
windowMenu.add(windowPartitionSubMenu);
windowPartitionSubMenu.addMenuItem("Tile Horizontally", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { tileHorizontallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Tile Vertically", KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { tileVerticallyCommand(); }});
windowPartitionSubMenu.addMenuItem("Cascade", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { cascadeWindowsCommand(); }});
windowMenu.addMenuItem("Close Window", KeyStroke.getKeyStroke(KeyEvent.VK_W, buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { WindowFrame curWF = WindowFrame.getCurrentWindowFrame();
curWF.finished(); }});
if (!TopLevel.isMDIMode()) {
windowMenu.addSeparator();
windowMenu.addMenuItem("Move to Other Display", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { moveToOtherDisplayCommand(); } });
}
windowMenu.addSeparator();
windowMenu.addMenuItem("Layer Visibility...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerVisibilityCommand(); } });
Menu colorSubMenu = new Menu("Color");
windowMenu.add(colorSubMenu);
colorSubMenu.addMenuItem("Restore Default Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { defaultBackgroundCommand(); }});
colorSubMenu.addMenuItem("Black Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { blackBackgroundCommand(); }});
colorSubMenu.addMenuItem("White Background Colors", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { whiteBackgroundCommand(); }});
Menu messagesSubMenu = new Menu("Messages Window");
windowMenu.add(messagesSubMenu);
messagesSubMenu.addMenuItem("Save Messages", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().save(); }});
messagesSubMenu.addMenuItem("Clear", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { TopLevel.getMessagesWindow().clear(); }});
/****************************** THE TOOL MENU ******************************/
Menu toolMenu = new Menu("Tool", 'T');
menuBar.add(toolMenu);
//------------------- DRC
Menu drcSubMenu = new Menu("DRC", 'D');
toolMenu.add(drcSubMenu);
drcSubMenu.addMenuItem("Check Hierarchically", KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkHierarchically(); }});
drcSubMenu.addMenuItem("Check Selection Area Hierarchically", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { DRC.checkAreaHierarchically(); }});
//------------------- Simulation (SPICE)
Menu spiceSimulationSubMenu = new Menu("Simulation (SPICE)", 'S');
toolMenu.add(spiceSimulationSubMenu);
spiceSimulationSubMenu.addMenuItem("Write SPICE Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.SPICE, true); }});
spiceSimulationSubMenu.addMenuItem("Write CDL Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.CDL, true); }});
spiceSimulationSubMenu.addMenuItem("Plot Spice Listing...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotSpiceResults(); }});
m = spiceSimulationSubMenu.addMenuItem("Plot Spice for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
spiceSimulationSubMenu.addMenuItem("Set Spice Model...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setSpiceModel(); }});
spiceSimulationSubMenu.addMenuItem("Add Multiplier", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
spiceSimulationSubMenu.addSeparator();
spiceSimulationSubMenu.addMenuItem("Set Generic SPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 2 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_2_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SPICE 3 Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_3_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set HSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_H_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set PSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_P_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set GnuCap Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_GC_TEMPLATE_KEY); }});
spiceSimulationSubMenu.addMenuItem("Set SmartSPICE Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Spice.SPICE_SM_TEMPLATE_KEY); }});
//------------------- Simulation (Verilog)
Menu verilogSimulationSubMenu = new Menu("Simulation (Verilog)", 'V');
toolMenu.add(verilogSimulationSubMenu);
verilogSimulationSubMenu.addMenuItem("Write Verilog Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.VERILOG, true); } });
verilogSimulationSubMenu.addMenuItem("Plot Verilog VCD Dump...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulate.plotVerilogResults(); }});
m = verilogSimulationSubMenu.addMenuItem("Plot Verilog for This Cell", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
verilogSimulationSubMenu.addSeparator();
verilogSimulationSubMenu.addMenuItem("Set Verilog Template", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeTemplate(Verilog.VERILOG_TEMPLATE_KEY); }});
verilogSimulationSubMenu.addSeparator();
Menu verilogWireTypeSubMenu = new Menu("Set Verilog Wire", 'W');
verilogWireTypeSubMenu.addMenuItem("Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(0); }});
verilogWireTypeSubMenu.addMenuItem("Trireg", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(1); }});
verilogWireTypeSubMenu.addMenuItem("Default", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setVerilogWireCommand(2); }});
verilogSimulationSubMenu.add(verilogWireTypeSubMenu);
Menu transistorStrengthSubMenu = new Menu("Transistor Strength", 'T');
transistorStrengthSubMenu.addMenuItem("Weak", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(true); }});
transistorStrengthSubMenu.addMenuItem("Normal", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Simulation.setTransistorStrengthCommand(false); }});
verilogSimulationSubMenu.add(transistorStrengthSubMenu);
//------------------- Simulation (others)
Menu netlisters = new Menu("Simulation (others)");
toolMenu.add(netlisters);
netlisters.addMenuItem("Write IRSIM Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { irsimNetlistCommand(); }});
netlisters.addMenuItem("Write Maxwell Deck...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { exportCellCommand(OpenFile.Type.MAXWELL, true); } });
//------------------- ERC
Menu ercSubMenu = new Menu("ERC", 'E');
toolMenu.add(ercSubMenu);
ercSubMenu.addMenuItem("Check Wells", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ERCWellCheck.analyzeCurCell(true); } });
ercSubMenu.addMenuItem("Antenna Check", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { new ERCAntenna(); } });
//------------------- Network
Menu networkSubMenu = new Menu("Network", 'N');
toolMenu.add(networkSubMenu);
networkSubMenu.addMenuItem("Show Network", KeyStroke.getKeyStroke('K', buckyBit),
new ActionListener() { public void actionPerformed(ActionEvent e) { showNetworkCommand(); } });
networkSubMenu.addMenuItem("List Networks", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listNetworksCommand(); } });
networkSubMenu.addMenuItem("List Connections on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listConnectionsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsOnNetworkCommand(); } });
networkSubMenu.addMenuItem("List Exports below Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listExportsBelowNetworkCommand(); } });
networkSubMenu.addMenuItem("List Geometry on Network", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listGeometryOnNetworkCommand(); } });
networkSubMenu.addSeparator();
networkSubMenu.addMenuItem("Show Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { showPowerAndGround(); } });
networkSubMenu.addMenuItem("Validate Power and Ground", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { validatePowerAndGround(); } });
networkSubMenu.addMenuItem("Redo Network Numbering", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { redoNetworkNumberingCommand(); } });
//------------------- Logical Effort
Menu logEffortSubMenu = new Menu("Logical Effort", 'L');
logEffortSubMenu.addMenuItem("Optimize for Equal Gate Delays", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { optimizeEqualGateDelaysCommand(); }});
logEffortSubMenu.addMenuItem("Print Info for Selected Node", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { printLEInfoCommand(); }});
toolMenu.add(logEffortSubMenu);
//------------------- Routing
Menu routingSubMenu = new Menu("Routing", 'R');
toolMenu.add(routingSubMenu);
routingSubMenu.addCheckBox("Enable Auto-Stitching", Routing.isAutoStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableAutoStitching(e); } });
routingSubMenu.addMenuItem("Auto-Stitch Now", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(false, true); }});
routingSubMenu.addMenuItem("Auto-Stitch Highlighted Now", KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { AutoStitch.autoStitch(true, true); }});
routingSubMenu.addSeparator();
routingSubMenu.addCheckBox("Enable Mimic-Stitching", Routing.isMimicStitchOn(), null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.toggleEnableMimicStitching(e); }});
routingSubMenu.addMenuItem("Mimic-Stitch Now", KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { MimicStitch.mimicStitch(true); }});
routingSubMenu.addMenuItem("Mimic Selected", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { Routing.tool.mimicSelected(); }});
routingSubMenu.addSeparator();
routingSubMenu.addMenuItem("Get Unrouted Wire", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { getUnroutedArcCommand(); }});
m = routingSubMenu.addMenuItem("Copy Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
m = routingSubMenu.addMenuItem("Paste Routing Topology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { addMultiplierCommand(); }});
m.setEnabled(false);
//------------------- Generation
Menu generationSubMenu = new Menu("Generation", 'G');
toolMenu.add(generationSubMenu);
generationSubMenu.addMenuItem("Coverage Implants Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { implantGeneratorCommand(true, false); }});
generationSubMenu.addMenuItem("Pad Frame Generator", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { padFrameGeneratorCommand(); }});
toolMenu.addSeparator();
toolMenu.addMenuItem("Tool Options...",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { ToolOptions.toolOptionsCommand(); } });
toolMenu.addMenuItem("List Tools",null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listToolsCommand(); } });
Menu languagesSubMenu = new Menu("Languages");
languagesSubMenu.addMenuItem("Run Java Bean Shell Script", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { javaBshScriptCommand(); }});
toolMenu.add(languagesSubMenu);
/****************************** THE HELP MENU ******************************/
Menu helpMenu = new Menu("Help", 'H');
menuBar.add(helpMenu);
if (TopLevel.getOperatingSystem() != TopLevel.OS.MACINTOSH)
{
helpMenu.addMenuItem("About Electric...", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { aboutCommand(); } });
}
helpMenu.addMenuItem("Help Index", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { toolTipsCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Describe this Technology", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { describeTechnologyCommand(); } });
helpMenu.addSeparator();
helpMenu.addMenuItem("Make fake circuitry", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { makeFakeCircuitryCommand(); } });
helpMenu.addMenuItem("Make fake simulation window", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { WaveformWindow.makeFakeWaveformCommand(); }});
// helpMenu.addMenuItem("Whit Diffie's design...", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { whitDiffieCommand(); } });
/****************************** Russell's TEST MENU ******************************/
Menu russMenu = new Menu("Russell", 'R');
menuBar.add(russMenu);
russMenu.addMenuItem("Generate fill cells", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.FillLibGen();
}
});
russMenu.addMenuItem("Gate Generator Regression", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateRegression();
}
});
russMenu.addMenuItem("Generate gate layouts", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.GateLayoutGenerator();
}
});
russMenu.addMenuItem("create flat netlists for Ivan", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.IvanFlat();
}
});
russMenu.addMenuItem("layout flat", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.LayFlat();
}
});
russMenu.addMenuItem("Jemini", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.ncc.NccJob();
}
});
russMenu.addMenuItem("Random Test", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
new com.sun.electric.tool.generator.layout.Test();
}
});
/****************************** Jon's TEST MENU ******************************/
Menu jongMenu = new Menu("JonG", 'J');
menuBar.add(jongMenu);
jongMenu.addMenuItem("Describe Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(false); }});
jongMenu.addMenuItem("Describe Proto Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listVarsOnObject(true); }});
jongMenu.addMenuItem("Describe Current Library Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { listLibVars(); }});
jongMenu.addMenuItem("Eval Vars", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { evalVarsOnObject(); }});
jongMenu.addMenuItem("LE test1", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { LENetlister.test1(); }});
jongMenu.addMenuItem("Open Purple Lib", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { openP4libCommand(); }});
//jongMenu.addMenuItem("Check Exports", null,
// new ActionListener() { public void actionPerformed(ActionEvent e) { checkExports(); }});
/****************************** Gilda's TEST MENU ******************************/
Menu gildaMenu = new Menu("Gilda", 'G');
menuBar.add(gildaMenu);
gildaMenu.addMenuItem("Merge Polyons", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, true);}});
gildaMenu.addMenuItem("Covering Implants", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(true, false);}});
gildaMenu.addMenuItem("Covering Implants Old", null,
new ActionListener() { public void actionPerformed(ActionEvent e) {implantGeneratorCommand(false, false);}});
gildaMenu.addMenuItem("List Layer Coverage", null,
new ActionListener() { public void actionPerformed(ActionEvent e) { layerCoverageCommand(true); } });
/********************************* Hidden Menus *******************************/
Menu wiringShortcuts = new Menu("Circuit Editing");
menuBar.addHidden(wiringShortcuts);
wiringShortcuts.addMenuItem("Wire to Poly", KeyStroke.getKeyStroke(KeyEvent.VK_0, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(0); }});
wiringShortcuts.addMenuItem("Wire to M1", KeyStroke.getKeyStroke(KeyEvent.VK_1, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(1); }});
wiringShortcuts.addMenuItem("Wire to M2", KeyStroke.getKeyStroke(KeyEvent.VK_2, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(2); }});
wiringShortcuts.addMenuItem("Wire to M3", KeyStroke.getKeyStroke(KeyEvent.VK_3, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(3); }});
wiringShortcuts.addMenuItem("Wire to M4", KeyStroke.getKeyStroke(KeyEvent.VK_4, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(4); }});
wiringShortcuts.addMenuItem("Wire to M5", KeyStroke.getKeyStroke(KeyEvent.VK_5, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(5); }});
wiringShortcuts.addMenuItem("Wire to M6", KeyStroke.getKeyStroke(KeyEvent.VK_6, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.wireTo(6); }});
wiringShortcuts.addMenuItem("Switch Wiring Target", KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0),
new ActionListener() { public void actionPerformed(ActionEvent e) { ClickZoomWireListener.theOne.switchWiringTarget(); }});
// return the menu bar
return menuBar;
}
|
diff --git a/src/org/ukiuni/lighthttpserver/request/Request.java b/src/org/ukiuni/lighthttpserver/request/Request.java
index f6ff2a2..602e77a 100644
--- a/src/org/ukiuni/lighthttpserver/request/Request.java
+++ b/src/org/ukiuni/lighthttpserver/request/Request.java
@@ -1,376 +1,374 @@
package org.ukiuni.lighthttpserver.request;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
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 java.util.StringTokenizer;
import org.ukiuni.lighthttpserver.util.ByteReader;
import org.ukiuni.lighthttpserver.util.StreamUtil;
public class Request {
public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language";
public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset";
public static final String HEADER_USER_AGENT = "User-Agent";
public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
public static final String HEADER_ORIGIN = "Origin";
public static final String HEADER_HOST = "Host";
public static final String HEADER_COOKIE = "Cookie";
public static final Object HEADER_CONTENT_LENGTH = "Content-Length";
public static final Object HEADER_CONTENT_TYPE = "Content-Type";
private Map<String, String> headers = new HashMap<String, String>();
private Map<String, String> parameters = new HashMap<String, String>();
private Map<String, String> cookies = new HashMap<String, String>();
private Map<String, ParameterFile> parametersFile = new HashMap<String, ParameterFile>();
private Map<String, List<ParameterFile>> parametersFiles = new HashMap<String, List<ParameterFile>>();
private String protocol;
private String method;
private String path;
private String value;
private ByteReader byteReader;
private String charset;
public void dumpHeader(PrintStream out) {
Set<String> keySet = headers.keySet();
for (String key : keySet) {
out.println(key + ":" + headers.get(key));
}
}
public String getAbsoluteUrl() {
String origin = headers.get(HEADER_ORIGIN);
if (null == origin) {
String protocol = this.protocol.toLowerCase().startsWith("http") ? "http://" : "https://";
origin = protocol + headers.get(HEADER_HOST);
}
return origin + getPath();
}
public String getAbsoluteParentUrl() {
String absolutePath = getAbsoluteUrl();
return absolutePath.substring(0, absolutePath.lastIndexOf("/") + 1);
}
public Map<String, String> getHeaders() {
return headers;
}
public String getHeader(String key) {
return headers.get(key);
}
public Map<String, String> getParameters() {
return parameters;
}
public String getParameter(String key) {
return parameters.get(key);
}
public Map<String, ParameterFile> getParameterFile() {
return parametersFile;
}
public ParameterFile getParameterFile(String key) {
return parametersFile.get(key);
}
public Map<String, List<ParameterFile>> getParametersFiles() {
return parametersFiles;
}
public int getParameterFileLength(String key) {
return parametersFiles.get(key).size();
}
public ParameterFile getParameterFile(String key, int index) {
List<ParameterFile> parametersFile = parametersFiles.get(key);
if (null == parametersFile) {
return null;
}
if (index >= parametersFile.size()) {
return null;
}
return parametersFile.get(index);
}
public void saveParameterFile(String key, String filePath) throws IOException {
byte[] content = getParameterFile(key).content;
save(filePath, content);
}
public void saveParameterFile(String key, int index, String filePath) throws IOException {
byte[] content = getParameterFile(key, index).content;
save(filePath, content);
}
private void save(String filePath, byte[] content) throws FileNotFoundException, IOException {
FileOutputStream fout = null;
try {
File file = new File(filePath);
file.getParentFile().mkdirs();
fout = new FileOutputStream(file);
fout.write(content);
} finally {
StreamUtil.closeQuietry(fout);
}
}
public String getMethod() {
return method;
}
public String getValue() {
return value;
}
public String getPath() {
return path;
}
public List<String> parseAcceptCharset() {
String headerCharset = headers.get(HEADER_ACCEPT_CHARSET);
List<String> returnList = parseHeader(headerCharset);
return returnList;
}
public List<String> parseAcceptLanguage() {
String headerCharset = headers.get(HEADER_ACCEPT_LANGUAGE);
List<String> returnList = parseHeader(headerCharset);
return returnList;
}
private List<String> parseHeader(String headerCharset) {
if (null == headerCharset) {
return Collections.emptyList();
}
StringTokenizer token = new StringTokenizer(headerCharset, ",");
List<String> returnList = new ArrayList<String>();
while (token.hasMoreElements()) {
returnList.add(token.nextToken());
}
return returnList;
}
public static Request parseInput(InputStream inputStream, String charset) throws IOException {
Request request = new Request();
request.byteReader = new ByteReader(inputStream, charset, "\r\n".getBytes());
request.charset = charset;
return request.parseInput();
}
public void close() {
StreamUtil.closeQuietry(byteReader);
}
@Override
protected void finalize() throws Throwable {
super.finalize();
this.clone();
}
public Request parseInput() throws IOException {
String methodLine = this.byteReader.readLine();
if (null == methodLine) {
throw new IOException("no request input");
}
StringTokenizer urlParamToken = new StringTokenizer(methodLine, " ");
this.method = urlParamToken.nextToken();
String pathAndParam = urlParamToken.nextToken();
if (pathAndParam.contains("?")) {
int questIndex = pathAndParam.indexOf("?");
this.path = pathAndParam.substring(0, questIndex);
parseParameters(pathAndParam.substring(questIndex + 1), charset);
} else {
this.path = pathAndParam;
}
this.protocol = urlParamToken.nextToken();
String headerLine = this.byteReader.readLine();
int length = -1;
String contentType = null;
String boundary = null;
while (null != headerLine && !"".equals(headerLine)) {
int coronIndex = headerLine.indexOf(":");
if (coronIndex > 0) {
String key = headerLine.substring(0, coronIndex).trim();
String value = headerLine.substring(coronIndex + 1).trim();
this.headers.put(key, value);
if (HEADER_CONTENT_LENGTH.equals(key)) {
length = Integer.valueOf(value);
} else if (HEADER_CONTENT_TYPE.equals(key)) {
if (value.contains(";")) {
contentType = value.substring(0, value.indexOf(";"));
if (value.contains("-")) {
boundary = value.substring(value.lastIndexOf("=") + 1);
}
} else {
contentType = value;
}
} else if (HEADER_COOKIE.equals(key)) {
StringTokenizer token = new StringTokenizer(headerLine, ";,");
while (token.hasMoreTokens()) {
String keyValue = token.nextToken().trim();
int equalIndex = keyValue.indexOf("=");
if (0 < equalIndex) {
String cookieKey = keyValue.substring(0, equalIndex);
String cookieValue = keyValue.substring(equalIndex + 1);
this.cookies.put(cookieKey.trim(), cookieValue);
} else {
this.cookies.put(keyValue, null);
}
}
}
}
headerLine = this.byteReader.readLine();
}
if (-1 != length) {
if (null == contentType || "application/x-www-form-urlencoded".equals(contentType.trim())) {
- char[] valueChars = new char[length];
- for (int i = 0; i < valueChars.length; i++) {
- valueChars[i] = (char) this.byteReader.read();
- }
+ byte[] valueChars = new byte[length];
+ this.byteReader.read(valueChars);
String content = new String(valueChars);
this.parseParameters(content, charset);
this.value = content;
} else if ("multipart/form-data".equals(contentType.trim()) || "multipart/mixed".equals(contentType.trim())) {
String line = this.byteReader.readLine();
while (null != line && !line.equals("--" + boundary + "--")) {
if (line.equals("--" + boundary)) {
line = this.byteReader.readLine();
ParamHeader header = new ParamHeader();
while (!"".equals(line.trim())) {
decodeParamHeader(line, header);
line = this.byteReader.readLine();
}
if (null == header.paramContentType) {
line = this.byteReader.readLine();
this.parameters.put(header.contentDescriptionMap.get("name"), line);
line = this.byteReader.readLine();
} else if (header.paramContentType.toLowerCase().equals("multipart/mixed")) {
line = this.byteReader.readLine();
ParamHeader additionalHeader = new ParamHeader();
while (!"".equals(line.trim())) {
decodeParamHeader(line, additionalHeader);
line = this.byteReader.readLine();
}
byte[] data = this.byteReader.readTo(("\r\n--").getBytes());
String multiDataEndSeparator = "--" + header.paramAdditionalBoundary + "--";
List<ParameterFile> files = new ArrayList<ParameterFile>();
this.parametersFiles.put(header.contentDescriptionMap.get("name"), files);
line = "--" + this.byteReader.readLine();
while (!line.equals(multiDataEndSeparator)) {
ParameterFile parameterFile = new ParameterFile();
parameterFile.fileName = additionalHeader.contentDescriptionMap.get("filename");
parameterFile.contentType = additionalHeader.paramContentType;
parameterFile.content = data;
line = "--" + this.byteReader.readLine();
}
} else {
byte[] data = this.byteReader.readTo("\r\n--".getBytes());
ParameterFile parameterFile = new ParameterFile();
parameterFile.contentType = header.paramContentType;
parameterFile.fileName = header.contentDescriptionMap.get("filename");
parameterFile.content = data;
ParameterFile existFile = this.parametersFile.get(header.contentDescriptionMap.get("name"));
if (null != existFile) {
List<ParameterFile> parameterFiles = this.parametersFiles.get(header.contentDescriptionMap.get("name"));
if (null == parameterFiles) {
parameterFiles = new ArrayList<ParameterFile>();
this.parametersFiles.put(header.contentDescriptionMap.get("name"), parameterFiles);
parameterFiles.add(existFile);
}
parameterFiles.add(parameterFile);
} else {
this.parametersFile.put(header.contentDescriptionMap.get("name"), parameterFile);
}
// FileOutputStream fout = new FileOutputStream(new
// File("data/" +
// contentDescriptionMap.get("filename")));
// fout.write(data);
// fout.close();
line = "--" + this.byteReader.readLine();
}
}
}
}
}
return this;
}
private static void decodeParamHeader(String line, ParamHeader header) {
int colonIndex = line.indexOf(":");
String key = line.substring(0, colonIndex);
String value = line.substring(colonIndex + 1);
if (key.trim().toLowerCase().equals("content-disposition")) {
StringTokenizer tokenizer = new StringTokenizer(value, ";");
header.paramContentDescription = tokenizer.nextToken().trim();
while (tokenizer.hasMoreTokens()) {
String additionalParam = tokenizer.nextToken();
int equalIndex = additionalParam.indexOf("=");
if (equalIndex > 1) {
String contentDescriptionKey = additionalParam.substring(0, equalIndex).trim();
String valueWithDust = additionalParam.substring(equalIndex + 1).trim();
header.contentDescriptionMap.put(contentDescriptionKey, valueWithDust.substring(1, valueWithDust.length() - 1));
}
}
} else if (key.trim().toLowerCase().equals("content-type")) {
if (value.contains(",")) {
header.paramContentType = value.substring(0, value.indexOf(",")).trim().toLowerCase();
String boundarySrc = value.substring(value.indexOf(",") + 1);
header.paramAdditionalBoundary = boundarySrc.substring(boundarySrc.indexOf("=") + 1).trim();
} else {
header.paramContentType = value.trim();
}
}
}
private void parseParameters(String parameters, String charset) throws UnsupportedEncodingException {
StringTokenizer paramToken = new StringTokenizer(parameters, "&");
while (paramToken.hasMoreTokens()) {
String paramKeyAndValue = paramToken.nextToken();
int equalIndex = paramKeyAndValue.indexOf("=");
if (0 < equalIndex) {
String key = paramKeyAndValue.substring(0, equalIndex);
String value = paramKeyAndValue.substring(equalIndex + 1);
this.parameters.put(key, URLDecoder.decode(value, charset));
} else {
this.parameters.put(paramKeyAndValue, null);
}
}
}
public String getCookie(String key) {
return cookies.get(key);
}
public String getFileName() {
if (null == path) {
return null;
}
int lastSlash = path.lastIndexOf("/");
if (lastSlash < 0 || lastSlash + 1 >= path.length()) {
return null;
}
return path.substring(lastSlash + 1);
}
private static class ParamHeader {
String paramContentDescription;
String paramContentType;
String paramAdditionalBoundary;
Map<String, String> contentDescriptionMap = new HashMap<String, String>();
}
}
| true | true | public Request parseInput() throws IOException {
String methodLine = this.byteReader.readLine();
if (null == methodLine) {
throw new IOException("no request input");
}
StringTokenizer urlParamToken = new StringTokenizer(methodLine, " ");
this.method = urlParamToken.nextToken();
String pathAndParam = urlParamToken.nextToken();
if (pathAndParam.contains("?")) {
int questIndex = pathAndParam.indexOf("?");
this.path = pathAndParam.substring(0, questIndex);
parseParameters(pathAndParam.substring(questIndex + 1), charset);
} else {
this.path = pathAndParam;
}
this.protocol = urlParamToken.nextToken();
String headerLine = this.byteReader.readLine();
int length = -1;
String contentType = null;
String boundary = null;
while (null != headerLine && !"".equals(headerLine)) {
int coronIndex = headerLine.indexOf(":");
if (coronIndex > 0) {
String key = headerLine.substring(0, coronIndex).trim();
String value = headerLine.substring(coronIndex + 1).trim();
this.headers.put(key, value);
if (HEADER_CONTENT_LENGTH.equals(key)) {
length = Integer.valueOf(value);
} else if (HEADER_CONTENT_TYPE.equals(key)) {
if (value.contains(";")) {
contentType = value.substring(0, value.indexOf(";"));
if (value.contains("-")) {
boundary = value.substring(value.lastIndexOf("=") + 1);
}
} else {
contentType = value;
}
} else if (HEADER_COOKIE.equals(key)) {
StringTokenizer token = new StringTokenizer(headerLine, ";,");
while (token.hasMoreTokens()) {
String keyValue = token.nextToken().trim();
int equalIndex = keyValue.indexOf("=");
if (0 < equalIndex) {
String cookieKey = keyValue.substring(0, equalIndex);
String cookieValue = keyValue.substring(equalIndex + 1);
this.cookies.put(cookieKey.trim(), cookieValue);
} else {
this.cookies.put(keyValue, null);
}
}
}
}
headerLine = this.byteReader.readLine();
}
if (-1 != length) {
if (null == contentType || "application/x-www-form-urlencoded".equals(contentType.trim())) {
char[] valueChars = new char[length];
for (int i = 0; i < valueChars.length; i++) {
valueChars[i] = (char) this.byteReader.read();
}
String content = new String(valueChars);
this.parseParameters(content, charset);
this.value = content;
} else if ("multipart/form-data".equals(contentType.trim()) || "multipart/mixed".equals(contentType.trim())) {
String line = this.byteReader.readLine();
while (null != line && !line.equals("--" + boundary + "--")) {
if (line.equals("--" + boundary)) {
line = this.byteReader.readLine();
ParamHeader header = new ParamHeader();
while (!"".equals(line.trim())) {
decodeParamHeader(line, header);
line = this.byteReader.readLine();
}
if (null == header.paramContentType) {
line = this.byteReader.readLine();
this.parameters.put(header.contentDescriptionMap.get("name"), line);
line = this.byteReader.readLine();
} else if (header.paramContentType.toLowerCase().equals("multipart/mixed")) {
line = this.byteReader.readLine();
ParamHeader additionalHeader = new ParamHeader();
while (!"".equals(line.trim())) {
decodeParamHeader(line, additionalHeader);
line = this.byteReader.readLine();
}
byte[] data = this.byteReader.readTo(("\r\n--").getBytes());
String multiDataEndSeparator = "--" + header.paramAdditionalBoundary + "--";
List<ParameterFile> files = new ArrayList<ParameterFile>();
this.parametersFiles.put(header.contentDescriptionMap.get("name"), files);
line = "--" + this.byteReader.readLine();
while (!line.equals(multiDataEndSeparator)) {
ParameterFile parameterFile = new ParameterFile();
parameterFile.fileName = additionalHeader.contentDescriptionMap.get("filename");
parameterFile.contentType = additionalHeader.paramContentType;
parameterFile.content = data;
line = "--" + this.byteReader.readLine();
}
} else {
byte[] data = this.byteReader.readTo("\r\n--".getBytes());
ParameterFile parameterFile = new ParameterFile();
parameterFile.contentType = header.paramContentType;
parameterFile.fileName = header.contentDescriptionMap.get("filename");
parameterFile.content = data;
ParameterFile existFile = this.parametersFile.get(header.contentDescriptionMap.get("name"));
if (null != existFile) {
List<ParameterFile> parameterFiles = this.parametersFiles.get(header.contentDescriptionMap.get("name"));
if (null == parameterFiles) {
parameterFiles = new ArrayList<ParameterFile>();
this.parametersFiles.put(header.contentDescriptionMap.get("name"), parameterFiles);
parameterFiles.add(existFile);
}
parameterFiles.add(parameterFile);
} else {
this.parametersFile.put(header.contentDescriptionMap.get("name"), parameterFile);
}
// FileOutputStream fout = new FileOutputStream(new
// File("data/" +
// contentDescriptionMap.get("filename")));
// fout.write(data);
// fout.close();
line = "--" + this.byteReader.readLine();
}
}
}
}
}
return this;
}
| public Request parseInput() throws IOException {
String methodLine = this.byteReader.readLine();
if (null == methodLine) {
throw new IOException("no request input");
}
StringTokenizer urlParamToken = new StringTokenizer(methodLine, " ");
this.method = urlParamToken.nextToken();
String pathAndParam = urlParamToken.nextToken();
if (pathAndParam.contains("?")) {
int questIndex = pathAndParam.indexOf("?");
this.path = pathAndParam.substring(0, questIndex);
parseParameters(pathAndParam.substring(questIndex + 1), charset);
} else {
this.path = pathAndParam;
}
this.protocol = urlParamToken.nextToken();
String headerLine = this.byteReader.readLine();
int length = -1;
String contentType = null;
String boundary = null;
while (null != headerLine && !"".equals(headerLine)) {
int coronIndex = headerLine.indexOf(":");
if (coronIndex > 0) {
String key = headerLine.substring(0, coronIndex).trim();
String value = headerLine.substring(coronIndex + 1).trim();
this.headers.put(key, value);
if (HEADER_CONTENT_LENGTH.equals(key)) {
length = Integer.valueOf(value);
} else if (HEADER_CONTENT_TYPE.equals(key)) {
if (value.contains(";")) {
contentType = value.substring(0, value.indexOf(";"));
if (value.contains("-")) {
boundary = value.substring(value.lastIndexOf("=") + 1);
}
} else {
contentType = value;
}
} else if (HEADER_COOKIE.equals(key)) {
StringTokenizer token = new StringTokenizer(headerLine, ";,");
while (token.hasMoreTokens()) {
String keyValue = token.nextToken().trim();
int equalIndex = keyValue.indexOf("=");
if (0 < equalIndex) {
String cookieKey = keyValue.substring(0, equalIndex);
String cookieValue = keyValue.substring(equalIndex + 1);
this.cookies.put(cookieKey.trim(), cookieValue);
} else {
this.cookies.put(keyValue, null);
}
}
}
}
headerLine = this.byteReader.readLine();
}
if (-1 != length) {
if (null == contentType || "application/x-www-form-urlencoded".equals(contentType.trim())) {
byte[] valueChars = new byte[length];
this.byteReader.read(valueChars);
String content = new String(valueChars);
this.parseParameters(content, charset);
this.value = content;
} else if ("multipart/form-data".equals(contentType.trim()) || "multipart/mixed".equals(contentType.trim())) {
String line = this.byteReader.readLine();
while (null != line && !line.equals("--" + boundary + "--")) {
if (line.equals("--" + boundary)) {
line = this.byteReader.readLine();
ParamHeader header = new ParamHeader();
while (!"".equals(line.trim())) {
decodeParamHeader(line, header);
line = this.byteReader.readLine();
}
if (null == header.paramContentType) {
line = this.byteReader.readLine();
this.parameters.put(header.contentDescriptionMap.get("name"), line);
line = this.byteReader.readLine();
} else if (header.paramContentType.toLowerCase().equals("multipart/mixed")) {
line = this.byteReader.readLine();
ParamHeader additionalHeader = new ParamHeader();
while (!"".equals(line.trim())) {
decodeParamHeader(line, additionalHeader);
line = this.byteReader.readLine();
}
byte[] data = this.byteReader.readTo(("\r\n--").getBytes());
String multiDataEndSeparator = "--" + header.paramAdditionalBoundary + "--";
List<ParameterFile> files = new ArrayList<ParameterFile>();
this.parametersFiles.put(header.contentDescriptionMap.get("name"), files);
line = "--" + this.byteReader.readLine();
while (!line.equals(multiDataEndSeparator)) {
ParameterFile parameterFile = new ParameterFile();
parameterFile.fileName = additionalHeader.contentDescriptionMap.get("filename");
parameterFile.contentType = additionalHeader.paramContentType;
parameterFile.content = data;
line = "--" + this.byteReader.readLine();
}
} else {
byte[] data = this.byteReader.readTo("\r\n--".getBytes());
ParameterFile parameterFile = new ParameterFile();
parameterFile.contentType = header.paramContentType;
parameterFile.fileName = header.contentDescriptionMap.get("filename");
parameterFile.content = data;
ParameterFile existFile = this.parametersFile.get(header.contentDescriptionMap.get("name"));
if (null != existFile) {
List<ParameterFile> parameterFiles = this.parametersFiles.get(header.contentDescriptionMap.get("name"));
if (null == parameterFiles) {
parameterFiles = new ArrayList<ParameterFile>();
this.parametersFiles.put(header.contentDescriptionMap.get("name"), parameterFiles);
parameterFiles.add(existFile);
}
parameterFiles.add(parameterFile);
} else {
this.parametersFile.put(header.contentDescriptionMap.get("name"), parameterFile);
}
// FileOutputStream fout = new FileOutputStream(new
// File("data/" +
// contentDescriptionMap.get("filename")));
// fout.write(data);
// fout.close();
line = "--" + this.byteReader.readLine();
}
}
}
}
}
return this;
}
|
diff --git a/src/main/java/com/theminequest/common/quest/js/JsTask.java b/src/main/java/com/theminequest/common/quest/js/JsTask.java
index 6a6cb2b..152d79c 100644
--- a/src/main/java/com/theminequest/common/quest/js/JsTask.java
+++ b/src/main/java/com/theminequest/common/quest/js/JsTask.java
@@ -1,173 +1,173 @@
package com.theminequest.common.quest.js;
import static com.theminequest.common.util.I18NMessage._;
import java.util.Collection;
import java.util.LinkedList;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import com.theminequest.api.CompleteStatus;
import com.theminequest.api.Managers;
import com.theminequest.api.quest.Quest;
import com.theminequest.api.quest.QuestTask;
import com.theminequest.api.quest.event.QuestEvent;
public class JsTask implements QuestTask {
private static volatile ScriptableObject STD_OBJ = null;
private static final Object SYNCLOCK = new Object();
private JsQuest quest;
private Thread jsThread;
private JsObserver observer;
private CompleteStatus status;
private String taskDescription;
protected JsTask(JsQuest quest) {
this.quest = quest;
this.jsThread = null;
this.observer = new JsObserver();
this.status = null;
this.taskDescription = _("No description given - ask the quest maker to use util.setTaskDescription!");
}
@Override
public void start() {
if (jsThread != null)
return;
jsThread = new Thread(new Runnable() {
@Override
public void run() {
Context cx = Context.enter();
try {
synchronized(SYNCLOCK) {
if (STD_OBJ == null) {
STD_OBJ = cx.initStandardObjects(null, true);
STD_OBJ.sealObject();
}
}
Scriptable global = cx.newObject(STD_OBJ);
global.setPrototype(STD_OBJ);
global.setParentScope(null);
ScriptableObject.putConstProperty(global, "details", Context.toObject(quest.getDetails(), global));
ScriptableObject.putConstProperty(global, "color", Context.toObject(Managers.getPlatform().chatColor(), global));
ScriptableObject.putConstProperty(global, "util", Context.toObject(new JsQuestFunctions(JsTask.this, global), global));
cx.setDebugger(observer, new Integer(0));
cx.setGeneratingDebug(true);
cx.setOptimizationLevel(-1);
// FIXME we don't specify security for now
- Object result = cx.evaluateString(global, (String) quest.getDetails().getProperty(JsQuestDetails.JS_SOURCE), quest.getDetails().getName(), (int) quest.getDetails().getProperty(JsQuestDetails.JsQuestDetails.JS_LINESTART), null);
+ Object result = cx.evaluateString(global, (String) quest.getDetails().getProperty(JsQuestDetails.JS_SOURCE), quest.getDetails().getName(), (int) quest.getDetails().getProperty(JsQuestDetails.JS_LINESTART), null);
if (observer.isDisconnected()) {
Managers.getPlatform().scheduleSyncTask(new Runnable() {
@Override
public void run() {
status = CompleteStatus.CANCELED;
completed();
}
});
return;
}
status = CompleteStatus.ERROR;
if (result == null || result.equals(0))
status = CompleteStatus.SUCCESS;
else if (result.equals(1))
status = CompleteStatus.FAIL;
else if (result.equals(2))
status = CompleteStatus.WARNING;
else if (result.equals(-2))
status = CompleteStatus.IGNORE;
else if (result.equals(-1))
status = CompleteStatus.CANCELED;
Managers.getPlatform().scheduleSyncTask(new Runnable() {
@Override
public void run() {
completed();
}
});
} finally {
Context.exit();
}
}
});
jsThread.start();
}
private void completed() {
quest.completeTask(this, status, -1);
}
@Override
public CompleteStatus isComplete() {
return status;
}
@Override
public Quest getQuest() {
return quest;
}
@Override
public int getTaskID() {
return 0;
}
@Override
public String getTaskDescription() {
return taskDescription;
}
protected void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
@Override
public Collection<QuestEvent> getEvents() {
return new LinkedList<QuestEvent>();
}
@Override
public void checkTasks() {
// does nothing
}
@Override
public void cancelTask() {
// this will toggle the Js runtime to stop
// and will call (as above) completed(CANCELED)
observer.setDisconnected(true);
}
@Override
public void completeEvent(QuestEvent event, CompleteStatus status) {
// does nothing (but maybe it should?)
}
@Override
public void completeEvent(QuestEvent event, CompleteStatus status, int nextTask) {
// does nothing (but maybe it should?)
}
}
| true | true | public void start() {
if (jsThread != null)
return;
jsThread = new Thread(new Runnable() {
@Override
public void run() {
Context cx = Context.enter();
try {
synchronized(SYNCLOCK) {
if (STD_OBJ == null) {
STD_OBJ = cx.initStandardObjects(null, true);
STD_OBJ.sealObject();
}
}
Scriptable global = cx.newObject(STD_OBJ);
global.setPrototype(STD_OBJ);
global.setParentScope(null);
ScriptableObject.putConstProperty(global, "details", Context.toObject(quest.getDetails(), global));
ScriptableObject.putConstProperty(global, "color", Context.toObject(Managers.getPlatform().chatColor(), global));
ScriptableObject.putConstProperty(global, "util", Context.toObject(new JsQuestFunctions(JsTask.this, global), global));
cx.setDebugger(observer, new Integer(0));
cx.setGeneratingDebug(true);
cx.setOptimizationLevel(-1);
// FIXME we don't specify security for now
Object result = cx.evaluateString(global, (String) quest.getDetails().getProperty(JsQuestDetails.JS_SOURCE), quest.getDetails().getName(), (int) quest.getDetails().getProperty(JsQuestDetails.JsQuestDetails.JS_LINESTART), null);
if (observer.isDisconnected()) {
Managers.getPlatform().scheduleSyncTask(new Runnable() {
@Override
public void run() {
status = CompleteStatus.CANCELED;
completed();
}
});
return;
}
status = CompleteStatus.ERROR;
if (result == null || result.equals(0))
status = CompleteStatus.SUCCESS;
else if (result.equals(1))
status = CompleteStatus.FAIL;
else if (result.equals(2))
status = CompleteStatus.WARNING;
else if (result.equals(-2))
status = CompleteStatus.IGNORE;
else if (result.equals(-1))
status = CompleteStatus.CANCELED;
Managers.getPlatform().scheduleSyncTask(new Runnable() {
@Override
public void run() {
completed();
}
});
} finally {
Context.exit();
}
}
});
jsThread.start();
}
| public void start() {
if (jsThread != null)
return;
jsThread = new Thread(new Runnable() {
@Override
public void run() {
Context cx = Context.enter();
try {
synchronized(SYNCLOCK) {
if (STD_OBJ == null) {
STD_OBJ = cx.initStandardObjects(null, true);
STD_OBJ.sealObject();
}
}
Scriptable global = cx.newObject(STD_OBJ);
global.setPrototype(STD_OBJ);
global.setParentScope(null);
ScriptableObject.putConstProperty(global, "details", Context.toObject(quest.getDetails(), global));
ScriptableObject.putConstProperty(global, "color", Context.toObject(Managers.getPlatform().chatColor(), global));
ScriptableObject.putConstProperty(global, "util", Context.toObject(new JsQuestFunctions(JsTask.this, global), global));
cx.setDebugger(observer, new Integer(0));
cx.setGeneratingDebug(true);
cx.setOptimizationLevel(-1);
// FIXME we don't specify security for now
Object result = cx.evaluateString(global, (String) quest.getDetails().getProperty(JsQuestDetails.JS_SOURCE), quest.getDetails().getName(), (int) quest.getDetails().getProperty(JsQuestDetails.JS_LINESTART), null);
if (observer.isDisconnected()) {
Managers.getPlatform().scheduleSyncTask(new Runnable() {
@Override
public void run() {
status = CompleteStatus.CANCELED;
completed();
}
});
return;
}
status = CompleteStatus.ERROR;
if (result == null || result.equals(0))
status = CompleteStatus.SUCCESS;
else if (result.equals(1))
status = CompleteStatus.FAIL;
else if (result.equals(2))
status = CompleteStatus.WARNING;
else if (result.equals(-2))
status = CompleteStatus.IGNORE;
else if (result.equals(-1))
status = CompleteStatus.CANCELED;
Managers.getPlatform().scheduleSyncTask(new Runnable() {
@Override
public void run() {
completed();
}
});
} finally {
Context.exit();
}
}
});
jsThread.start();
}
|
diff --git a/crowd-store-aggregator/crowd-store-web/src/main/java/com/crowdstore/common/logging/LoggerInjector.java b/crowd-store-aggregator/crowd-store-web/src/main/java/com/crowdstore/common/logging/LoggerInjector.java
index e6c7a14..42eeb8a 100644
--- a/crowd-store-aggregator/crowd-store-web/src/main/java/com/crowdstore/common/logging/LoggerInjector.java
+++ b/crowd-store-aggregator/crowd-store-web/src/main/java/com/crowdstore/common/logging/LoggerInjector.java
@@ -1,36 +1,36 @@
package com.crowdstore.common.logging;
import com.crowdstore.common.annotations.InjectLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;
import java.lang.reflect.Field;
/**
* @author fcamblor
* Utility class which will inject SLF4J into @Log annotated fields
*/
@Component
public class LoggerInjector implements BeanPostProcessor {
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
// make the field accessible if defined private
ReflectionUtils.makeAccessible(field);
- if (field.getAnnotation(InjectLogger.class) != null && field.getDeclaringClass().isAssignableFrom(Logger.class)) {
+ if (field.getAnnotation(InjectLogger.class) != null && field.getType().isAssignableFrom(Logger.class)) {
Logger log = LoggerFactory.getLogger(bean.getClass());
field.set(bean, log);
}
}
});
return bean;
}
}
| true | true | public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
// make the field accessible if defined private
ReflectionUtils.makeAccessible(field);
if (field.getAnnotation(InjectLogger.class) != null && field.getDeclaringClass().isAssignableFrom(Logger.class)) {
Logger log = LoggerFactory.getLogger(bean.getClass());
field.set(bean, log);
}
}
});
return bean;
}
| public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
// make the field accessible if defined private
ReflectionUtils.makeAccessible(field);
if (field.getAnnotation(InjectLogger.class) != null && field.getType().isAssignableFrom(Logger.class)) {
Logger log = LoggerFactory.getLogger(bean.getClass());
field.set(bean, log);
}
}
});
return bean;
}
|
diff --git a/src/com/heavyplayer/util/ElasticThreadPoolExecutor.java b/src/com/heavyplayer/util/ElasticThreadPoolExecutor.java
index 3842a84..4817b64 100644
--- a/src/com/heavyplayer/util/ElasticThreadPoolExecutor.java
+++ b/src/com/heavyplayer/util/ElasticThreadPoolExecutor.java
@@ -1,56 +1,56 @@
package com.heavyplayer.util;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ElasticThreadPoolExecutor extends ThreadPoolExecutor {
private int mStartCorePoolSize;
private Object elasticityLock = new Object(); // Used to avoid decrementing too much
public ElasticThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
mStartCorePoolSize = corePoolSize;
}
public ElasticThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
mStartCorePoolSize = corePoolSize;
}
public ElasticThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory);
mStartCorePoolSize = corePoolSize;
}
public ElasticThreadPoolExecutor(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, handler);
mStartCorePoolSize = corePoolSize;
}
@Override
public void execute(Runnable command) {
synchronized(elasticityLock) {
- int count = getQueue().size() + getActiveCount();
- if(count >= getCorePoolSize() && count <= getMaximumPoolSize()) {
+ int count = getActiveCount() + getQueue().size();
+ if(count >= getCorePoolSize() && getCorePoolSize() < getMaximumPoolSize()) {
setCorePoolSize(getCorePoolSize() + 1);
}
}
super.execute(command);
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
synchronized(elasticityLock) {
if(getQueue().isEmpty() && getCorePoolSize() > mStartCorePoolSize) {
setCorePoolSize(getCorePoolSize() - 1);
}
}
};
}
| true | true | public void execute(Runnable command) {
synchronized(elasticityLock) {
int count = getQueue().size() + getActiveCount();
if(count >= getCorePoolSize() && count <= getMaximumPoolSize()) {
setCorePoolSize(getCorePoolSize() + 1);
}
}
super.execute(command);
}
| public void execute(Runnable command) {
synchronized(elasticityLock) {
int count = getActiveCount() + getQueue().size();
if(count >= getCorePoolSize() && getCorePoolSize() < getMaximumPoolSize()) {
setCorePoolSize(getCorePoolSize() + 1);
}
}
super.execute(command);
}
|
diff --git a/src/me/ibhh/xpShop/BottleManager.java b/src/me/ibhh/xpShop/BottleManager.java
index f6c69e4..fe23aae 100644
--- a/src/me/ibhh/xpShop/BottleManager.java
+++ b/src/me/ibhh/xpShop/BottleManager.java
@@ -1,149 +1,149 @@
package me.ibhh.xpShop;
import java.util.HashMap;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
/**
*
* @author ibhh
*/
public class BottleManager {
private xpShop plugin;
private HashMap<Player, Integer> Playermap = new HashMap<Player, Integer>();
public BottleManager(xpShop pl) {
plugin = pl;
}
public void removefromMap(Player player) {
Playermap.remove(player);
}
public void addinmap(Player player, int anzahl) {
Playermap.put(player, anzahl);
}
public boolean isinmap(Player player) {
if (Playermap.containsKey(player)) {
return true;
} else {
return false;
}
}
public boolean hasEnoughBottles(Player player, int anzahl) {
Inventory inv = player.getInventory();
boolean hasBottle = inv.contains(374, anzahl);
return hasBottle;
}
public boolean replaceBottles(Player player, int anzahl, int ID, int ID2) {
boolean ret = false;
Inventory inv = player.getInventory();
ItemStack[] stacks = inv.getContents();
int temp = anzahl;
for (ItemStack stack : stacks) {
if (stack != null) {
int stackanzahl = stack.getAmount();
if (stack.getTypeId() == ID) {
if (temp > 0) {
if (temp < stackanzahl) {
inv.remove(stack);
ItemStack rest = new ItemStack(ID, stackanzahl - temp);
inv.addItem(rest);
ItemStack XPBottles = new ItemStack(ID2, temp);
inv.addItem(XPBottles);
player.saveData();
temp = 0;
plugin.Logger("Filled " + stackanzahl + " Bottles of " + player.getName(), "Debug");
} else {
temp = temp - stackanzahl;
inv.remove(stack);
ItemStack XPBottles = new ItemStack(ID2, stackanzahl);
inv.addItem(XPBottles);
player.saveData();
plugin.Logger("Filled " + stackanzahl + " Bottles of " + player.getName(), "Debug");
}
}
}
}
}
return ret;
}
public boolean registerCommandXPBottles(final Player player, int anzahl) {
if (!Playermap.containsKey(player)) {
if (player.getTotalExperience() >= anzahl * plugin.getConfig().getInt("XPperBottle")) {
if (hasEnoughBottles(player, anzahl)) {
Playermap.put(player, anzahl);
plugin.Logger("Player: " + player.getName() + " has enough XP to fill " + anzahl + " Bottles (each " + plugin.getConfig().getInt("XPperBottle") + " XP)", "Debug");
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.Info." + plugin.config.language), anzahl * plugin.getConfig().getInt("XPperBottle"), anzahl, plugin.getConfig().getInt("XPperBottle")), "Warning");
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.PleaseConfirm1." + plugin.config.language), "");
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.PleaseConfirm2." + plugin.config.language), "");
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if (Playermap.containsKey(player)) {
plugin.Logger("Player: " + player.getName() + " Command (BottleFilling) timed out", "Debug");
Playermap.remove(player);
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.ConfirmTimeOut." + plugin.config.language), plugin.getConfig().getInt("CooldownofBottleFilling")), "Warning");
}
}
}, plugin.getConfig().getInt("CooldownofBottleFilling") * 20);
return true;
} else {
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.notenoughbottles." + plugin.config.language), anzahl), "Error");
return false;
}
} else {
- plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.NotEnoughXp." + plugin.config.language), anzahl * plugin.getConfig().getInt("XPperBottle"), anzahl, plugin.getConfig().getInt("XPperBottle")), "Error");
+ plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.NotEnoughXP." + plugin.config.language), anzahl * plugin.getConfig().getInt("XPperBottle"), anzahl, plugin.getConfig().getInt("XPperBottle")), "Error");
return false;
}
} else {
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.nocommand." + plugin.config.language), "");
return false;
}
}
public void cancelChange(Player player) {
if (Playermap.containsKey(player)) {
Playermap.remove(player);
}
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.canceled." + plugin.config.language), "");
}
public void confirmChange(Player player) {
int anzahl = Playermap.get(player);
if (player.getTotalExperience() >= anzahl * plugin.getConfig().getInt("XPperBottle")) {
if (hasEnoughBottles(player, anzahl)) {
plugin.UpdateXP(player, -anzahl * plugin.getConfig().getInt("XPperBottle"), "Bottle");
if (plugin.config.usedbtomanageXP) {
plugin.SQL.UpdateXP(player.getName(), ((int) (player.getTotalExperience() - anzahl * plugin.getConfig().getInt("XPperBottle"))));
}
executeCommandXPBottles(player, anzahl);
if (Playermap.containsKey(player)) {
Playermap.remove(player);
}
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.confirmed." + plugin.config.language), "");
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.executed." + plugin.config.language), anzahl * plugin.getConfig().getInt("XPperBottle"), anzahl, plugin.getConfig().getInt("XPperBottle")), "");
} else {
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.notenoughbottles." + plugin.config.language), anzahl), "Error");
}
} else {
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.NotEnoughXp." + plugin.config.language), anzahl * plugin.getConfig().getInt("XPperBottle"), anzahl, plugin.getConfig().getInt("XPperBottle")), "Error");
}
}
public boolean executeCommandXPBottles(Player player, int anzahl) {
if (hasEnoughBottles(player, anzahl)) {
replaceBottles(player, anzahl, 374, 384);
return true;
} else {
return false;
}
}
}
| true | true | public boolean registerCommandXPBottles(final Player player, int anzahl) {
if (!Playermap.containsKey(player)) {
if (player.getTotalExperience() >= anzahl * plugin.getConfig().getInt("XPperBottle")) {
if (hasEnoughBottles(player, anzahl)) {
Playermap.put(player, anzahl);
plugin.Logger("Player: " + player.getName() + " has enough XP to fill " + anzahl + " Bottles (each " + plugin.getConfig().getInt("XPperBottle") + " XP)", "Debug");
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.Info." + plugin.config.language), anzahl * plugin.getConfig().getInt("XPperBottle"), anzahl, plugin.getConfig().getInt("XPperBottle")), "Warning");
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.PleaseConfirm1." + plugin.config.language), "");
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.PleaseConfirm2." + plugin.config.language), "");
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if (Playermap.containsKey(player)) {
plugin.Logger("Player: " + player.getName() + " Command (BottleFilling) timed out", "Debug");
Playermap.remove(player);
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.ConfirmTimeOut." + plugin.config.language), plugin.getConfig().getInt("CooldownofBottleFilling")), "Warning");
}
}
}, plugin.getConfig().getInt("CooldownofBottleFilling") * 20);
return true;
} else {
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.notenoughbottles." + plugin.config.language), anzahl), "Error");
return false;
}
} else {
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.NotEnoughXp." + plugin.config.language), anzahl * plugin.getConfig().getInt("XPperBottle"), anzahl, plugin.getConfig().getInt("XPperBottle")), "Error");
return false;
}
} else {
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.nocommand." + plugin.config.language), "");
return false;
}
}
| public boolean registerCommandXPBottles(final Player player, int anzahl) {
if (!Playermap.containsKey(player)) {
if (player.getTotalExperience() >= anzahl * plugin.getConfig().getInt("XPperBottle")) {
if (hasEnoughBottles(player, anzahl)) {
Playermap.put(player, anzahl);
plugin.Logger("Player: " + player.getName() + " has enough XP to fill " + anzahl + " Bottles (each " + plugin.getConfig().getInt("XPperBottle") + " XP)", "Debug");
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.Info." + plugin.config.language), anzahl * plugin.getConfig().getInt("XPperBottle"), anzahl, plugin.getConfig().getInt("XPperBottle")), "Warning");
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.PleaseConfirm1." + plugin.config.language), "");
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.PleaseConfirm2." + plugin.config.language), "");
plugin.getServer().getScheduler().scheduleAsyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if (Playermap.containsKey(player)) {
plugin.Logger("Player: " + player.getName() + " Command (BottleFilling) timed out", "Debug");
Playermap.remove(player);
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.ConfirmTimeOut." + plugin.config.language), plugin.getConfig().getInt("CooldownofBottleFilling")), "Warning");
}
}
}, plugin.getConfig().getInt("CooldownofBottleFilling") * 20);
return true;
} else {
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.notenoughbottles." + plugin.config.language), anzahl), "Error");
return false;
}
} else {
plugin.PlayerLogger(player, String.format(plugin.getConfig().getString("BottleFilling.NotEnoughXP." + plugin.config.language), anzahl * plugin.getConfig().getInt("XPperBottle"), anzahl, plugin.getConfig().getInt("XPperBottle")), "Error");
return false;
}
} else {
plugin.PlayerLogger(player, plugin.getConfig().getString("BottleFilling.nocommand." + plugin.config.language), "");
return false;
}
}
|
diff --git a/amibe/src/org/jcae/mesh/MeshOEMMViewer3d.java b/amibe/src/org/jcae/mesh/MeshOEMMViewer3d.java
index c0f2c2de..4c923f53 100644
--- a/amibe/src/org/jcae/mesh/MeshOEMMViewer3d.java
+++ b/amibe/src/org/jcae/mesh/MeshOEMMViewer3d.java
@@ -1,166 +1,166 @@
/* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD
modeler, Finit element mesher, Plugin architecture.
Copyright (C) 2005
Jerome Robert <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
package org.jcae.mesh;
import org.jcae.mesh.oemm.OEMM;
import org.jcae.mesh.oemm.OEMMViewer;
import org.jcae.mesh.oemm.Storage;
import org.jcae.mesh.amibe.ds.Mesh;
import org.jcae.mesh.amibe.ds.MMesh3D;
import org.jcae.mesh.amibe.ds.Triangle;
import org.jcae.mesh.xmldata.MeshWriter;
import org.jcae.mesh.xmldata.MMesh3DReader;
import org.jcae.mesh.xmldata.UNVConverter;
import org.jcae.mesh.amibe.validation.*;
import org.apache.log4j.Logger;
import java.io.File;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Iterator;
import java.util.HashMap;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import org.jcae.viewer3d.bg.ViewableBG;
import org.jcae.viewer3d.fe.amibe.AmibeProvider;
import org.jcae.viewer3d.fe.ViewableFE;
import org.jcae.viewer3d.fe.FEDomain;
import org.jcae.viewer3d.View;
import gnu.trove.TIntHashSet;
/**
* This class illustrates how to perform quality checks.
*/
public class MeshOEMMViewer3d
{
private static Logger logger=Logger.getLogger(MeshOEMMViewer3d.class);
private static ViewableBG fineMesh;
private static ViewableFE decMesh;
private static TIntHashSet leaves = new TIntHashSet();
private static boolean showOctree = true;
private static boolean showAxis = true;
public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("Usage: MeshOEMMViewer3d dir");
System.exit(0);
}
String dir=args[0];
JFrame feFrame=new JFrame("jCAE Demo");
feFrame.setSize(800,600);
feFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final OEMM oemm = Storage.readOEMMStructure(dir);
- final View bgView=new View();
+ final View bgView=new View(feFrame);
final ViewableBG octree = new ViewableBG(OEMMViewer.bgOEMM(oemm, true));
try
{
bgView.add(octree);
bgView.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event)
{
if(event.getKeyChar()=='n')
{
if (fineMesh != null)
bgView.remove(fineMesh);
if (decMesh != null)
bgView.remove(decMesh);
fineMesh = new ViewableBG(OEMMViewer.meshOEMM(oemm, octree.getResultSet()));
octree.unselectAll();
bgView.add(fineMesh);
}
else if(event.getKeyChar()=='o')
{
showOctree = !showOctree;
if (showOctree)
bgView.add(octree);
else
bgView.remove(octree);
}
else if(event.getKeyChar()=='s')
{
Mesh amesh = Storage.loadNodes(oemm, octree.getResultSet(), false);
String xmlDir = "oemm-tmp";
String xmlFile = "jcae3d";
MeshWriter.writeObject3D(amesh, xmlDir, xmlFile, ".", "tmp.brep", 1);
new UNVConverter(xmlDir).writeMESH("oemm-tmp.mesh");
MMesh3D mesh3D = MMesh3DReader.readObject(xmlDir, xmlFile);
MinAngleFace qproc = new MinAngleFace();
QualityFloat data = new QualityFloat(1000);
data.setQualityProcedure(qproc);
for (Iterator itf = mesh3D.getFacesIterator(); itf.hasNext();)
{
Triangle f= (Triangle) itf.next();
data.compute(f);
}
data.finish();
data.setTarget((float) Math.PI/3.0f);
data.printMeshBB("oemm-tmp.bb");
}
else if(event.getKeyChar()=='d')
{
if (fineMesh != null)
bgView.remove(fineMesh);
if (decMesh != null)
bgView.remove(decMesh);
Mesh amesh = Storage.loadNodes(oemm, octree.getResultSet(), true);
HashMap opts = new HashMap();
opts.put("maxtriangles", Integer.toString(amesh.getTriangles().size() / 100));
new org.jcae.mesh.amibe.algos3d.DecimateHalfEdge(amesh, opts).compute();
String xmlDir = "dec-tmp";
String xmlFile = "jcae3d";
MeshWriter.writeObject3D(amesh, xmlDir, xmlFile, ".", "tmp.brep", 1);
octree.unselectAll();
try
{
AmibeProvider ap = new AmibeProvider(new File(xmlDir));
decMesh = new ViewableFE(ap);
logger.info("Nr. of triangles: "+((FEDomain)ap.getDomain(0)).getNumberOfTria3());
bgView.add(decMesh);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if(event.getKeyChar()=='a')
{
showAxis = !showAxis;
bgView.setOriginAxisVisible(showAxis);
}
else if(event.getKeyChar()=='q')
System.exit(0);
}
});
bgView.fitAll();
feFrame.getContentPane().add(bgView);
feFrame.setVisible(true);
bgView.setOriginAxisVisible(showAxis);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
| true | true | public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("Usage: MeshOEMMViewer3d dir");
System.exit(0);
}
String dir=args[0];
JFrame feFrame=new JFrame("jCAE Demo");
feFrame.setSize(800,600);
feFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final OEMM oemm = Storage.readOEMMStructure(dir);
final View bgView=new View();
final ViewableBG octree = new ViewableBG(OEMMViewer.bgOEMM(oemm, true));
try
{
bgView.add(octree);
bgView.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event)
{
if(event.getKeyChar()=='n')
{
if (fineMesh != null)
bgView.remove(fineMesh);
if (decMesh != null)
bgView.remove(decMesh);
fineMesh = new ViewableBG(OEMMViewer.meshOEMM(oemm, octree.getResultSet()));
octree.unselectAll();
bgView.add(fineMesh);
}
else if(event.getKeyChar()=='o')
{
showOctree = !showOctree;
if (showOctree)
bgView.add(octree);
else
bgView.remove(octree);
}
else if(event.getKeyChar()=='s')
{
Mesh amesh = Storage.loadNodes(oemm, octree.getResultSet(), false);
String xmlDir = "oemm-tmp";
String xmlFile = "jcae3d";
MeshWriter.writeObject3D(amesh, xmlDir, xmlFile, ".", "tmp.brep", 1);
new UNVConverter(xmlDir).writeMESH("oemm-tmp.mesh");
MMesh3D mesh3D = MMesh3DReader.readObject(xmlDir, xmlFile);
MinAngleFace qproc = new MinAngleFace();
QualityFloat data = new QualityFloat(1000);
data.setQualityProcedure(qproc);
for (Iterator itf = mesh3D.getFacesIterator(); itf.hasNext();)
{
Triangle f= (Triangle) itf.next();
data.compute(f);
}
data.finish();
data.setTarget((float) Math.PI/3.0f);
data.printMeshBB("oemm-tmp.bb");
}
else if(event.getKeyChar()=='d')
{
if (fineMesh != null)
bgView.remove(fineMesh);
if (decMesh != null)
bgView.remove(decMesh);
Mesh amesh = Storage.loadNodes(oemm, octree.getResultSet(), true);
HashMap opts = new HashMap();
opts.put("maxtriangles", Integer.toString(amesh.getTriangles().size() / 100));
new org.jcae.mesh.amibe.algos3d.DecimateHalfEdge(amesh, opts).compute();
String xmlDir = "dec-tmp";
String xmlFile = "jcae3d";
MeshWriter.writeObject3D(amesh, xmlDir, xmlFile, ".", "tmp.brep", 1);
octree.unselectAll();
try
{
AmibeProvider ap = new AmibeProvider(new File(xmlDir));
decMesh = new ViewableFE(ap);
logger.info("Nr. of triangles: "+((FEDomain)ap.getDomain(0)).getNumberOfTria3());
bgView.add(decMesh);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if(event.getKeyChar()=='a')
{
showAxis = !showAxis;
bgView.setOriginAxisVisible(showAxis);
}
else if(event.getKeyChar()=='q')
System.exit(0);
}
});
bgView.fitAll();
feFrame.getContentPane().add(bgView);
feFrame.setVisible(true);
bgView.setOriginAxisVisible(showAxis);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
| public static void main(String args[])
{
if (args.length < 1)
{
System.out.println("Usage: MeshOEMMViewer3d dir");
System.exit(0);
}
String dir=args[0];
JFrame feFrame=new JFrame("jCAE Demo");
feFrame.setSize(800,600);
feFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
final OEMM oemm = Storage.readOEMMStructure(dir);
final View bgView=new View(feFrame);
final ViewableBG octree = new ViewableBG(OEMMViewer.bgOEMM(oemm, true));
try
{
bgView.add(octree);
bgView.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent event)
{
if(event.getKeyChar()=='n')
{
if (fineMesh != null)
bgView.remove(fineMesh);
if (decMesh != null)
bgView.remove(decMesh);
fineMesh = new ViewableBG(OEMMViewer.meshOEMM(oemm, octree.getResultSet()));
octree.unselectAll();
bgView.add(fineMesh);
}
else if(event.getKeyChar()=='o')
{
showOctree = !showOctree;
if (showOctree)
bgView.add(octree);
else
bgView.remove(octree);
}
else if(event.getKeyChar()=='s')
{
Mesh amesh = Storage.loadNodes(oemm, octree.getResultSet(), false);
String xmlDir = "oemm-tmp";
String xmlFile = "jcae3d";
MeshWriter.writeObject3D(amesh, xmlDir, xmlFile, ".", "tmp.brep", 1);
new UNVConverter(xmlDir).writeMESH("oemm-tmp.mesh");
MMesh3D mesh3D = MMesh3DReader.readObject(xmlDir, xmlFile);
MinAngleFace qproc = new MinAngleFace();
QualityFloat data = new QualityFloat(1000);
data.setQualityProcedure(qproc);
for (Iterator itf = mesh3D.getFacesIterator(); itf.hasNext();)
{
Triangle f= (Triangle) itf.next();
data.compute(f);
}
data.finish();
data.setTarget((float) Math.PI/3.0f);
data.printMeshBB("oemm-tmp.bb");
}
else if(event.getKeyChar()=='d')
{
if (fineMesh != null)
bgView.remove(fineMesh);
if (decMesh != null)
bgView.remove(decMesh);
Mesh amesh = Storage.loadNodes(oemm, octree.getResultSet(), true);
HashMap opts = new HashMap();
opts.put("maxtriangles", Integer.toString(amesh.getTriangles().size() / 100));
new org.jcae.mesh.amibe.algos3d.DecimateHalfEdge(amesh, opts).compute();
String xmlDir = "dec-tmp";
String xmlFile = "jcae3d";
MeshWriter.writeObject3D(amesh, xmlDir, xmlFile, ".", "tmp.brep", 1);
octree.unselectAll();
try
{
AmibeProvider ap = new AmibeProvider(new File(xmlDir));
decMesh = new ViewableFE(ap);
logger.info("Nr. of triangles: "+((FEDomain)ap.getDomain(0)).getNumberOfTria3());
bgView.add(decMesh);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if(event.getKeyChar()=='a')
{
showAxis = !showAxis;
bgView.setOriginAxisVisible(showAxis);
}
else if(event.getKeyChar()=='q')
System.exit(0);
}
});
bgView.fitAll();
feFrame.getContentPane().add(bgView);
feFrame.setVisible(true);
bgView.setOriginAxisVisible(showAxis);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
|
diff --git a/interop-lab/demo-apps/src/main/java/org/mdpnp/apps/testapp/vital/VitalModelImpl.java b/interop-lab/demo-apps/src/main/java/org/mdpnp/apps/testapp/vital/VitalModelImpl.java
index 51707238..bc69d06b 100644
--- a/interop-lab/demo-apps/src/main/java/org/mdpnp/apps/testapp/vital/VitalModelImpl.java
+++ b/interop-lab/demo-apps/src/main/java/org/mdpnp/apps/testapp/vital/VitalModelImpl.java
@@ -1,577 +1,576 @@
package org.mdpnp.apps.testapp.vital;
import ice.DeviceConnectivity;
import ice.DeviceConnectivityDataReader;
import ice.DeviceConnectivitySeq;
import ice.DeviceConnectivityTopic;
import ice.DeviceConnectivityTypeSupport;
import ice.DeviceIdentity;
import ice.DeviceIdentityDataReader;
import ice.DeviceIdentitySeq;
import ice.DeviceIdentityTopic;
import ice.DeviceIdentityTypeSupport;
import ice.Numeric;
import ice.NumericDataReader;
import ice.NumericSeq;
import ice.NumericTopic;
import ice.NumericTypeSupport;
import java.lang.ref.SoftReference;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import org.mdpnp.apps.testapp.DeviceIcon;
import org.mdpnp.apps.testapp.pca.PCAConfig;
import org.mdpnp.devices.EventLoop;
import org.mdpnp.devices.EventLoopHandler;
import org.mdpnp.devices.TopicUtil;
import org.mdpnp.rti.dds.DDS;
import com.rti.dds.domain.DomainParticipant;
import com.rti.dds.domain.DomainParticipantFactory;
import com.rti.dds.infrastructure.Condition;
import com.rti.dds.infrastructure.InstanceHandle_t;
import com.rti.dds.infrastructure.RETCODE_NO_DATA;
import com.rti.dds.infrastructure.ResourceLimitsQosPolicy;
import com.rti.dds.infrastructure.StatusKind;
import com.rti.dds.infrastructure.StringSeq;
import com.rti.dds.subscription.InstanceStateKind;
import com.rti.dds.subscription.QueryCondition;
import com.rti.dds.subscription.SampleInfo;
import com.rti.dds.subscription.SampleInfoSeq;
import com.rti.dds.subscription.SampleStateKind;
import com.rti.dds.subscription.Subscriber;
import com.rti.dds.subscription.ViewStateKind;
import com.rti.dds.topic.TopicDescription;
public class VitalModelImpl implements VitalModel {
private final List<Vital> vitals = Collections.synchronizedList(new ArrayList<Vital>());
private VitalModelListener[] listeners = new VitalModelListener[0];
private DeviceIdentityDataReader deviceIdentityReader;
private DeviceConnectivityDataReader deviceConnectivityReader;
protected NumericDataReader numericReader;
private final Map<Vital, Set<QueryCondition>> queryConditions = new HashMap<Vital, Set<QueryCondition>>();
private Subscriber subscriber;
private EventLoop eventLoop;
private State state = State.Normal;
private final EventLoop.ConditionHandler numericHandler = new EventLoop.ConditionHandler() {
private final NumericSeq num_seq = new NumericSeq();
private final SampleInfoSeq info_seq = new SampleInfoSeq();
@Override
public void conditionChanged(Condition condition) {
try {
for (;;) {
try {
numericReader.read_w_condition(num_seq, info_seq, ResourceLimitsQosPolicy.LENGTH_UNLIMITED,
(QueryCondition) condition);
for (int i = 0; i < info_seq.size(); i++) {
SampleInfo sampleInfo = (SampleInfo) info_seq.get(i);
if (0 != (sampleInfo.instance_state & InstanceStateKind.NOT_ALIVE_INSTANCE_STATE)) {
Numeric keyHolder = new Numeric();
numericReader.get_key_value(keyHolder, sampleInfo.instance_handle);
removeNumeric(keyHolder.universal_device_identifier, keyHolder.name);
} else {
if (sampleInfo.valid_data) {
Numeric n = (Numeric) num_seq.get(i);
updateNumeric(n, sampleInfo);
}
}
}
} finally {
numericReader.return_loan(num_seq, info_seq);
}
}
} catch (RETCODE_NO_DATA noData) {
} finally {
}
}
};
protected void removeNumeric(String udi, int name) {
Vital[] vitals = vitalBuffer.get();
vitals = this.vitals.toArray(vitals);
vitalBuffer.set(vitals);
for (Vital v : vitals) {
boolean updated = false;
if(v != null) {
for (int x : v.getNames()) {
if (x == name) {
ListIterator<Value> li = v.getValues().listIterator();
while (li.hasNext()) {
Value va = li.next();
if (va.getUniversalDeviceIdentifier().equals(udi)) {
li.remove();
updated = true;
}
}
}
}
if (updated) {
fireVitalChanged(v);
}
}
}
}
ThreadLocal<Vital[]> vitalBuffer = new ThreadLocal<Vital[]>() {
@Override
protected Vital[] initialValue() {
return new Vital[0];
}
};
protected void updateNumeric(Numeric n, SampleInfo si) {
Vital[] vitals = vitalBuffer.get();
vitals = this.vitals.toArray(vitals);
vitalBuffer.set(vitals);
// TODO linear search? Query Condition should be vital specific
// or maybe these should be hashed because creating myriad QueryConditions is not advisable
for (Vital v : vitals) {
if(v != null) {
for (int x : v.getNames()) {
// Change to this vital from a source
if (x == n.name) {
boolean updated = false;
for (Value va : v.getValues()) {
if (va.getName() == n.name && va.getUniversalDeviceIdentifier().equals(n.universal_device_identifier)) {
va.updateFrom(n, si);
updated = true;
}
}
if (!updated) {
v.getValues().add(new ValueImpl(n.universal_device_identifier, n.name, v));
}
fireVitalChanged(v);
}
}
}
}
}
@Override
public int getCount() {
return vitals.size();
}
@Override
public Vital getVital(int i) {
return vitals.get(i);
}
@Override
public Vital addVital(String label, String units, int[] names, Float low, Float high, Float criticalLow, Float criticalHigh, float minimum, float maximum, Long valueMsWarningLow, Long valueMsWarningHigh) {
Vital v = new VitalImpl(this, label, units, names, low, high, criticalLow, criticalHigh, minimum, maximum, valueMsWarningLow, valueMsWarningHigh);
vitals.add(v);
addQueryConditions(v);
fireVitalAdded(v);
return v;
}
@Override
public boolean removeVital(Vital vital) {
boolean r = vitals.remove(vital);
if (r) {
removeQueryConditions(vital);
fireVitalRemoved(vital);
}
return r;
}
@Override
public Vital removeVital(int i) {
Vital v = vitals.remove(i);
if (v != null) {
removeQueryConditions(v);
fireVitalRemoved(v);
}
return v;
}
@Override
public synchronized void addListener(VitalModelListener vitalModelListener) {
VitalModelListener[] oldListeners = this.listeners;
VitalModelListener[] newListeners = new VitalModelListener[oldListeners.length + 1];
System.arraycopy(oldListeners, 0, newListeners, 0, oldListeners.length);
newListeners[newListeners.length - 1] = vitalModelListener;
this.listeners = newListeners;
}
@Override
public synchronized boolean removeListener(VitalModelListener vitalModelListener) {
VitalModelListener[] oldListeners = this.listeners;
List<VitalModelListener> newListeners = new ArrayList<VitalModelListener>();
boolean found = false;
for (VitalModelListener vml : oldListeners) {
if (vitalModelListener.equals(vml)) {
found = true;
} else {
newListeners.add(vml);
}
}
this.listeners = newListeners.toArray(new VitalModelListener[0]);
return found;
}
protected void fireVitalAdded(Vital v) {
updateState();
VitalModelListener[] listeners = this.listeners;
for (VitalModelListener vml : listeners) {
vml.vitalAdded(this, v);
}
}
protected void fireVitalRemoved(Vital v) {
updateState();
VitalModelListener[] listeners = this.listeners;
for (VitalModelListener vml : listeners) {
vml.vitalRemoved(this, v);
}
}
protected void fireVitalChanged(Vital v) {
updateState();
VitalModelListener[] listeners = this.listeners;
for (VitalModelListener vml : listeners) {
vml.vitalChanged(this, v);
}
}
private final DeviceIdentitySeq di_data_seq = new DeviceIdentitySeq();
private final DeviceConnectivitySeq dc_data_seq = new DeviceConnectivitySeq();
private final SampleInfoSeq info_seq = new SampleInfoSeq();
private final DeviceIdentity diKeyHolder = new DeviceIdentity();
private final DeviceConnectivity dcKeyHolder = new DeviceConnectivity();
private final Map<String,SoftReference<DeviceIdentity>> udiToDeviceIdentity = Collections.synchronizedMap(new HashMap<String, SoftReference<DeviceIdentity>>());
private final Map<String,SoftReference<DeviceIcon>> udiToDeviceIcon = Collections.synchronizedMap(new HashMap<String, SoftReference<DeviceIcon>>());
public DeviceIcon getDeviceIcon(String udi) {
SoftReference<DeviceIcon> ref2 = udiToDeviceIcon.get(udi);
DeviceIcon dicon = null == ref2 ? null : ref2.get();
if(null == dicon) {
ice.DeviceIdentity di = getDeviceIdentity(udi);
if(null != di) {
dicon = new DeviceIcon(di.icon, 0.75);
dicon.setConnected(true);
udiToDeviceIcon.put(udi, new SoftReference<DeviceIcon>(dicon));
}
}
return dicon;
}
@Override
public DeviceIdentity getDeviceIdentity(String udi) {
SoftReference<DeviceIdentity> ref = udiToDeviceIdentity.get(udi);
DeviceIdentity di = null == ref ? null : ref.get();
if(null != di) {
return di;
}
synchronized(info_seq) {
diKeyHolder.universal_device_identifier = udi;
InstanceHandle_t handle = deviceIdentityReader.lookup_instance(diKeyHolder);
if(InstanceHandle_t.HANDLE_NIL.equals(handle)) {
return null;
}
try {
deviceIdentityReader.read_instance(di_data_seq, info_seq, 1, handle, SampleStateKind.ANY_SAMPLE_STATE,
ViewStateKind.ANY_VIEW_STATE, InstanceStateKind.ALIVE_INSTANCE_STATE);
di = new DeviceIdentity((DeviceIdentity) di_data_seq.get(0));
udiToDeviceIdentity.put(udi, new SoftReference<DeviceIdentity>(di));
return di;
} catch (RETCODE_NO_DATA noData) {
return null;
} finally {
deviceIdentityReader.return_loan(di_data_seq, info_seq);
}
}
}
@Override
public DeviceConnectivity getDeviceConnectivity(String udi) {
synchronized(info_seq) {
dcKeyHolder.universal_device_identifier = udi;
InstanceHandle_t handle = deviceConnectivityReader.lookup_instance(dcKeyHolder);
try {
deviceConnectivityReader.read_instance(dc_data_seq, info_seq, 1, handle, SampleStateKind.ANY_SAMPLE_STATE,
ViewStateKind.ANY_VIEW_STATE, InstanceStateKind.ALIVE_INSTANCE_STATE);
return new DeviceConnectivity((DeviceConnectivity) dc_data_seq.get(0));
} catch(RETCODE_NO_DATA noData) {
return null;
} finally {
deviceConnectivityReader.return_loan(dc_data_seq, info_seq);
}
}
}
private void removeQueryConditions(final Vital v) {
final NumericDataReader numericReader = this.numericReader;
final EventLoop eventLoop = this.eventLoop;
if (null != numericReader && null != eventLoop) {
Set<QueryCondition> set = queryConditions.get(v);
if (null != set) {
for (QueryCondition qc : set) {
eventLoop.removeHandler(qc);
set.remove(qc);
numericReader.delete_readcondition(qc);
}
queryConditions.remove(v);
}
}
}
private void addQueryConditions(final Vital v) {
final NumericDataReader numericReader = this.numericReader;
final EventLoop eventLoop = this.eventLoop;
if (null != numericReader && null != eventLoop) {
// TODO this should probably be a ContentFilteredTopic to allow the
// writer to do the filtering
Set<QueryCondition> set = queryConditions.get(v);
set = null == set ? new HashSet<QueryCondition>() : set;
for (int x : v.getNames()) {
StringSeq params = new StringSeq();
params.add(Integer.toString(x));
QueryCondition qc = numericReader.create_querycondition(SampleStateKind.NOT_READ_SAMPLE_STATE,
ViewStateKind.ANY_VIEW_STATE, InstanceStateKind.ANY_INSTANCE_STATE, "name = %0", params);
set.add(qc);
eventLoop.addHandler(qc, numericHandler);
}
}
}
@Override
public void start(Subscriber subscriber, EventLoop eventLoop) {
this.subscriber = subscriber;
this.eventLoop = eventLoop;
DomainParticipant participant = subscriber.get_participant();
DeviceIdentityTypeSupport.register_type(participant, DeviceIdentityTypeSupport.get_type_name());
TopicDescription diTopic = TopicUtil.lookupOrCreateTopic(participant, DeviceIdentityTopic.VALUE,
DeviceIdentityTypeSupport.class);
deviceIdentityReader = (DeviceIdentityDataReader) subscriber.create_datareader(diTopic,
Subscriber.DATAREADER_QOS_DEFAULT, null, StatusKind.STATUS_MASK_NONE);
DeviceConnectivityTypeSupport.register_type(participant, DeviceConnectivityTypeSupport.get_type_name());
TopicDescription dcTopic = TopicUtil.lookupOrCreateTopic(participant, DeviceConnectivityTopic.VALUE,
DeviceConnectivityTypeSupport.class);
deviceConnectivityReader = (DeviceConnectivityDataReader) subscriber.create_datareader(dcTopic,
Subscriber.DATAREADER_QOS_DEFAULT, null, StatusKind.STATUS_MASK_NONE);
NumericTypeSupport.register_type(participant, NumericTypeSupport.get_type_name());
TopicDescription nTopic = TopicUtil.lookupOrCreateTopic(participant, NumericTopic.VALUE,
NumericTypeSupport.class);
numericReader = (NumericDataReader) subscriber.create_datareader(nTopic, Subscriber.DATAREADER_QOS_DEFAULT,
null, StatusKind.STATUS_MASK_NONE);
for (Vital v : vitals) {
addQueryConditions(v);
}
}
@Override
public void stop() {
for (Vital v : queryConditions.keySet()) {
removeQueryConditions(v);
}
queryConditions.clear();
numericReader.delete_contained_entities();
subscriber.delete_datareader(numericReader);
deviceIdentityReader.delete_contained_entities();
subscriber.delete_datareader(deviceIdentityReader);
deviceConnectivityReader.delete_contained_entities();
subscriber.delete_datareader(deviceConnectivityReader);
this.subscriber = null;
this.eventLoop = null;
}
public static void main(String[] args) {
DDS.init(false);
DomainParticipant p = DomainParticipantFactory.get_instance().create_participant(0,
DomainParticipantFactory.PARTICIPANT_QOS_DEFAULT, null, StatusKind.STATUS_MASK_NONE);
Subscriber s = p.create_subscriber(DomainParticipant.SUBSCRIBER_QOS_DEFAULT, null, StatusKind.STATUS_MASK_NONE);
VitalModel vm = new VitalModelImpl();
vm.addListener(new VitalModelListener() {
@Override
public void vitalRemoved(VitalModel model, Vital vital) {
System.out.println("Removed:" + vital);
}
@Override
public void vitalChanged(VitalModel model, Vital vital) {
System.out.println(new Date() + " Changed:" + vital);
}
@Override
public void vitalAdded(VitalModel model, Vital vital) {
System.out.println("Added:" + vital);
}
});
// vm.addVital("Heart Rate", "bpm", new int[] { ice.MDC_PULS_OXIM_PULS_RATE.VALUE }, 20, 200, 10, 210, 0, 200);
EventLoop eventLoop = new EventLoop();
// EventLoopHandler eventLoopHandler =
new EventLoopHandler(eventLoop);
vm.start(s, eventLoop);
}
private static final String DEFAULT_INTERLOCK_TEXT = "Drug: Morphine\r\nRate: 4cc / hour";
private static final DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
private String[] advisories = new String[0];
private final Date now = new Date();
private final StringBuilder warningTextBuilder = new StringBuilder();
private String warningText = "", interlockText = DEFAULT_INTERLOCK_TEXT;
private boolean interlock = false;
// TODO I synchronized this because I saw a transient concurrent mod exception
// but it's unclear to me which thread other than the EventLoopHandler should be calling it
// am I mixing AWT and ELH calls?
private final synchronized void updateState() {
int N = getCount();
while (advisories.length < N) {
advisories = new String[2 * N + 1];
}
now.setTime(System.currentTimeMillis());
String time = timeFormat.format(now);
int countWarnings = 0;
for (int i = 0; i < N; i++) {
Vital vital = getVital(i);
advisories[i] = null;
if (vital.isNoValueWarning() && vital.getValues().isEmpty()) {
countWarnings++;
advisories[i] = "- no source of " + vital.getLabel() + "\r\n";
} else {
for (Value val : vital.getValues()) {
if (val.isAtOrBelowLow()) {
countWarnings++;
advisories[i] = "- low " + vital.getLabel() + " " + val.getNumeric().value + " "
+ vital.getUnits() + "\r\n";
}
if (val.isAtOrAboveHigh()) {
countWarnings++;
advisories[i] = "- high " + vital.getLabel() + " " + val.getNumeric().value + " "
+ vital.getUnits() + "\r\n";
}
}
}
}
// Advisory processing
if (countWarnings>0) {
warningTextBuilder.delete(0, warningTextBuilder.length());
for (int i = 0; i < N; i++) {
if (null != advisories[i]) {
warningTextBuilder.append(advisories[i]);
}
}
warningTextBuilder.append("at ").append(time);
warningText = warningTextBuilder.toString();
state = State.Warning;
} else {
warningText = "";
state = State.Normal;
}
if (countWarnings >= countWarningsBecomeAlarm) {
state = State.Alarm;
- stopInfusion("Stopped\r\n" + warningText + "at " + time + "\r\nnurse alerted");
+ stopInfusion("Stopped\r\n" + warningText + "\r\nnurse alerted");
} else {
for (int i = 0; i < N; i++) {
Vital vital = getVital(i);
for (Value val : vital.getValues()) {
if (val.isAtOrBelowCriticalLow()) {
state = State.Alarm;
- stopInfusion("Stopped - " + vital.getLabel() + " outside of critical range ("
- + val.getNumeric().value + " " + vital.getUnits() + ")\r\nat " + time
+ stopInfusion("Stopped\r\n- low " + vital.getLabel() + " " + val.getNumeric().value + " " + vital.getUnits() + "\r\nat " + time
+ "\r\nnurse alerted");
break;
} else if (val.isAtOrAboveCriticalHigh()) {
state = State.Alarm;
- stopInfusion("Stopped - " + vital.getLabel() + " outside of critical range ("
- + val.getNumeric().value + " " + vital.getUnits() + ")\r\nat " + time
+ stopInfusion("Stopped\r\n- high " + vital.getLabel() + " " +
+ + val.getNumeric().value + " " + vital.getUnits() + "\r\nat " + time
+ "\r\nnurse alerted");
break;
}
}
}
}
}
private final void stopInfusion(String str) {
if (!interlock) {
interlock = true;
interlockText = str;
}
}
@Override
public State getState() {
return state;
}
@Override
public String getInterlockText() {
return interlockText;
}
@Override
public String getWarningText() {
return warningText;
}
@Override
public void resetInfusion() {
interlock = false;
interlockText = DEFAULT_INTERLOCK_TEXT;
fireVitalChanged(null);
}
@Override
public boolean isInfusionStopped() {
return interlock;
}
private int countWarningsBecomeAlarm = 2;
@Override
public void setCountWarningsBecomeAlarm(int countWarningsBecomeAlarm) {
this.countWarningsBecomeAlarm = countWarningsBecomeAlarm;
fireVitalChanged(null);
}
@Override
public int getCountWarningsBecomeAlarm() {
return countWarningsBecomeAlarm;
}
}
| false | true | private final synchronized void updateState() {
int N = getCount();
while (advisories.length < N) {
advisories = new String[2 * N + 1];
}
now.setTime(System.currentTimeMillis());
String time = timeFormat.format(now);
int countWarnings = 0;
for (int i = 0; i < N; i++) {
Vital vital = getVital(i);
advisories[i] = null;
if (vital.isNoValueWarning() && vital.getValues().isEmpty()) {
countWarnings++;
advisories[i] = "- no source of " + vital.getLabel() + "\r\n";
} else {
for (Value val : vital.getValues()) {
if (val.isAtOrBelowLow()) {
countWarnings++;
advisories[i] = "- low " + vital.getLabel() + " " + val.getNumeric().value + " "
+ vital.getUnits() + "\r\n";
}
if (val.isAtOrAboveHigh()) {
countWarnings++;
advisories[i] = "- high " + vital.getLabel() + " " + val.getNumeric().value + " "
+ vital.getUnits() + "\r\n";
}
}
}
}
// Advisory processing
if (countWarnings>0) {
warningTextBuilder.delete(0, warningTextBuilder.length());
for (int i = 0; i < N; i++) {
if (null != advisories[i]) {
warningTextBuilder.append(advisories[i]);
}
}
warningTextBuilder.append("at ").append(time);
warningText = warningTextBuilder.toString();
state = State.Warning;
} else {
warningText = "";
state = State.Normal;
}
if (countWarnings >= countWarningsBecomeAlarm) {
state = State.Alarm;
stopInfusion("Stopped\r\n" + warningText + "at " + time + "\r\nnurse alerted");
} else {
for (int i = 0; i < N; i++) {
Vital vital = getVital(i);
for (Value val : vital.getValues()) {
if (val.isAtOrBelowCriticalLow()) {
state = State.Alarm;
stopInfusion("Stopped - " + vital.getLabel() + " outside of critical range ("
+ val.getNumeric().value + " " + vital.getUnits() + ")\r\nat " + time
+ "\r\nnurse alerted");
break;
} else if (val.isAtOrAboveCriticalHigh()) {
state = State.Alarm;
stopInfusion("Stopped - " + vital.getLabel() + " outside of critical range ("
+ val.getNumeric().value + " " + vital.getUnits() + ")\r\nat " + time
+ "\r\nnurse alerted");
break;
}
}
}
}
}
| private final synchronized void updateState() {
int N = getCount();
while (advisories.length < N) {
advisories = new String[2 * N + 1];
}
now.setTime(System.currentTimeMillis());
String time = timeFormat.format(now);
int countWarnings = 0;
for (int i = 0; i < N; i++) {
Vital vital = getVital(i);
advisories[i] = null;
if (vital.isNoValueWarning() && vital.getValues().isEmpty()) {
countWarnings++;
advisories[i] = "- no source of " + vital.getLabel() + "\r\n";
} else {
for (Value val : vital.getValues()) {
if (val.isAtOrBelowLow()) {
countWarnings++;
advisories[i] = "- low " + vital.getLabel() + " " + val.getNumeric().value + " "
+ vital.getUnits() + "\r\n";
}
if (val.isAtOrAboveHigh()) {
countWarnings++;
advisories[i] = "- high " + vital.getLabel() + " " + val.getNumeric().value + " "
+ vital.getUnits() + "\r\n";
}
}
}
}
// Advisory processing
if (countWarnings>0) {
warningTextBuilder.delete(0, warningTextBuilder.length());
for (int i = 0; i < N; i++) {
if (null != advisories[i]) {
warningTextBuilder.append(advisories[i]);
}
}
warningTextBuilder.append("at ").append(time);
warningText = warningTextBuilder.toString();
state = State.Warning;
} else {
warningText = "";
state = State.Normal;
}
if (countWarnings >= countWarningsBecomeAlarm) {
state = State.Alarm;
stopInfusion("Stopped\r\n" + warningText + "\r\nnurse alerted");
} else {
for (int i = 0; i < N; i++) {
Vital vital = getVital(i);
for (Value val : vital.getValues()) {
if (val.isAtOrBelowCriticalLow()) {
state = State.Alarm;
stopInfusion("Stopped\r\n- low " + vital.getLabel() + " " + val.getNumeric().value + " " + vital.getUnits() + "\r\nat " + time
+ "\r\nnurse alerted");
break;
} else if (val.isAtOrAboveCriticalHigh()) {
state = State.Alarm;
stopInfusion("Stopped\r\n- high " + vital.getLabel() + " " +
+ val.getNumeric().value + " " + vital.getUnits() + "\r\nat " + time
+ "\r\nnurse alerted");
break;
}
}
}
}
}
|
diff --git a/src/org/python/core/PyObject.java b/src/org/python/core/PyObject.java
index 00e5157d..e7bbcb19 100644
--- a/src/org/python/core/PyObject.java
+++ b/src/org/python/core/PyObject.java
@@ -1,4075 +1,4075 @@
// Copyright (c) Corporation for National Research Initiatives
package org.python.core;
import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.python.expose.ExposedDelete;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedSet;
import org.python.expose.ExposedType;
import org.python.util.Generic;
/**
* All objects known to the Jython runtime system are represented by an instance
* of the class <code>PyObject</code> or one of its subclasses.
*/
@ExposedType(name = "object")
public class PyObject implements Serializable {
public static final PyType TYPE = PyType.fromClass(PyObject.class);
//XXX: in CPython object.__new__ has a doc string...
@ExposedNew
@ExposedMethod(doc = BuiltinDocs.object___init___doc)
final void object___init__(PyObject[] args, String[] keywords) {
// XXX: attempted fix for object(foo=1), etc
// XXX: this doesn't work for metaclasses, for some reason
// if (args.length > 0) {
// throw Py.TypeError("default __new__ takes no parameters");
// }
}
/**
* An underlying Java instance that this object is wrapping or is a subclass of. Anything
* attempting to use the proxy should go through {@link #getJavaProxy()} which ensures that it's
* initialized.
*/
protected Object javaProxy;
PyType objtype;
@ExposedGet(name = "__class__")
public PyType getType() {
return objtype;
}
@ExposedSet(name = "__class__")
public void setType(PyType type) {
if (type.builtin || getType().builtin) {
throw Py.TypeError("__class__ assignment: only for heap types");
}
type.compatibleForAssignment(getType(), "__class__");
objtype = type;
}
@ExposedDelete(name = "__class__")
public void delType() {
throw Py.TypeError("can't delete __class__ attribute");
}
// xxx
public PyObject fastGetClass() {
return objtype;
}
//XXX: needs doc
@ExposedGet(name = "__doc__")
public PyObject getDoc() {
PyObject d = fastGetDict();
if (d != null) {
PyObject doc = d.__finditem__("__doc__");
if(doc != null) {
return doc;
}
}
return Py.None;
}
public PyObject(PyType objtype) {
this.objtype = objtype;
}
/**
* Creates the PyObject for the base type. The argument only exists to make the constructor
* distinct.
*/
PyObject(boolean ignored) {
objtype = (PyType)this;
}
/**
* The standard constructor for a <code>PyObject</code>. It will set the <code>objtype</code>
* field to correspond to the specific subclass of <code>PyObject</code> being instantiated.
**/
public PyObject() {
objtype = PyType.fromClass(getClass());
}
/**
* Dispatch __init__ behavior
*/
public void dispatch__init__(PyType type, PyObject[] args, String[] keywords) {}
/**
* Attempts to automatically initialize our Java proxy if we have one and it wasn't initialized
* by our __init__.
*/
protected void proxyInit() {
Class<?> c = getType().getProxyType();
if (javaProxy != null || c == null) {
return;
}
if (!PyProxy.class.isAssignableFrom(c)) {
throw Py.SystemError("Automatic proxy initialization should only occur on proxy classes");
}
PyProxy proxy;
ThreadState ts = Py.getThreadState();
try {
ts.pushInitializingProxy(this);
try {
proxy = (PyProxy)c.newInstance();
} catch (java.lang.InstantiationException e) {
Class<?> sup = c.getSuperclass();
String msg = "Default constructor failed for Java superclass";
if (sup != null) {
msg += " " + sup.getName();
}
throw Py.TypeError(msg);
} catch (NoSuchMethodError nsme) {
throw Py.TypeError("constructor requires arguments");
} catch (Exception exc) {
throw Py.JavaError(exc);
}
} finally {
ts.popInitializingProxy();
}
if (javaProxy != null && javaProxy != proxy) {
throw Py.TypeError("Proxy instance already initialized");
}
PyObject proxyInstance = proxy._getPyInstance();
if (proxyInstance != null && proxyInstance != this) {
throw Py.TypeError("Proxy initialized with another instance");
}
javaProxy = proxy;
}
/**
* Equivalent to the standard Python __repr__ method. This method
* should not typically need to be overrriden. The easiest way to
* configure the string representation of a <code>PyObject</code> is to
* override the standard Java <code>toString</code> method.
**/
// counter-intuitively exposing this as __str__, otherwise stack overflow
// occurs during regression testing. XXX: more detail for this comment
// is needed.
@ExposedMethod(names = "__str__", doc = BuiltinDocs.object___str___doc)
public PyString __repr__() {
return new PyString(toString());
}
public String toString() {
return object_toString();
}
@ExposedMethod(names = "__repr__", doc = BuiltinDocs.object___repr___doc)
final String object_toString() {
if (getType() == null) {
return "unknown object";
}
String name = getType().getName();
if (name == null) {
return "unknown object";
}
PyObject module = getType().getModule();
if (module instanceof PyString && !module.toString().equals("__builtin__")) {
return String.format("<%s.%s object at %s>", module.toString(), name, Py.idstr(this));
}
return String.format("<%s object at %s>", name, Py.idstr(this));
}
/**
* Equivalent to the standard Python __str__ method. This method
* should not typically need to be overridden. The easiest way to
* configure the string representation of a <code>PyObject</code> is to
* override the standard Java <code>toString</code> method.
**/
public PyString __str__() {
return __repr__();
}
public PyUnicode __unicode__() {
return new PyUnicode(__str__());
}
/**
* Equivalent to the standard Python __hash__ method. This method can
* not be overridden. Instead, you should override the standard Java
* <code>hashCode</code> method to return an appropriate hash code for
* the <code>PyObject</code>.
**/
public final PyInteger __hash__() {
return new PyInteger(hashCode());
}
public int hashCode() {
return object___hash__();
}
@ExposedMethod(doc = BuiltinDocs.object___hash___doc)
final int object___hash__() {
return System.identityHashCode(this);
}
/**
* Should almost never be overridden.
* If overridden, it is the subclasses responsibility to ensure that
* <code>a.equals(b) == true</code> iff <code>cmp(a,b) == 0</code>
**/
public boolean equals(Object ob_other) {
if(ob_other == this) {
return true;
}
return (ob_other instanceof PyObject) && _eq((PyObject)ob_other).__nonzero__();
}
/**
* Equivalent to the standard Python __nonzero__ method. Returns whether of
* not a given <code>PyObject</code> is considered true.
*/
public boolean __nonzero__() {
return true;
}
/**
* Equivalent to the Jython __tojava__ method.
* Tries to coerce this object to an instance of the requested Java class.
* Returns the special object <code>Py.NoConversion</code>
* if this <code>PyObject</code> can not be converted to the
* desired Java class.
*
* @param c the Class to convert this <code>PyObject</code> to.
**/
public Object __tojava__(Class<?> c) {
if ((c == Object.class || c == Serializable.class) && getJavaProxy() != null) {
return javaProxy;
}
if (c.isInstance(this)) {
return this;
}
if (c.isPrimitive()) {
Class<?> tmp = primitiveMap.get(c);
if (tmp != null) {
c = tmp;
}
}
if (c.isInstance(getJavaProxy())) {
return javaProxy;
}
return Py.NoConversion;
}
protected Object getJavaProxy() {
if (javaProxy == null) {
proxyInit();
}
return javaProxy;
}
private static final Map<Class<?>, Class<?>> primitiveMap = Generic.map();
static {
primitiveMap.put(Character.TYPE, Character.class);
primitiveMap.put(Boolean.TYPE, Boolean.class);
primitiveMap.put(Byte.TYPE, Byte.class);
primitiveMap.put(Short.TYPE, Short.class);
primitiveMap.put(Integer.TYPE, Integer.class);
primitiveMap.put(Long.TYPE, Long.class);
primitiveMap.put(Float.TYPE, Float.class);
primitiveMap.put(Double.TYPE, Double.class);
}
/**
* The basic method to override when implementing a callable object.
*
* The first len(args)-len(keywords) members of args[] are plain
* arguments. The last len(keywords) arguments are the values of the
* keyword arguments.
*
* @param args all arguments to the function (including
* keyword arguments).
* @param keywords the keywords used for all keyword arguments.
**/
public PyObject __call__(PyObject args[], String keywords[]) {
throw Py.TypeError(String.format("'%s' object is not callable", getType().fastGetName()));
}
/**
* A variant of the __call__ method with one extra initial argument.
* This variant is used to allow method invocations to be performed
* efficiently.
*
* The default behavior is to invoke <code>__call__(args,
* keywords)</code> with the appropriate arguments. The only reason to
* override this function would be for improved performance.
*
* @param arg1 the first argument to the function.
* @param args the last arguments to the function (including
* keyword arguments).
* @param keywords the keywords used for all keyword arguments.
**/
public PyObject __call__(
PyObject arg1,
PyObject args[],
String keywords[]) {
PyObject[] newArgs = new PyObject[args.length + 1];
System.arraycopy(args, 0, newArgs, 1, args.length);
newArgs[0] = arg1;
return __call__(newArgs, keywords);
}
/**
* A variant of the __call__ method when no keywords are passed. The
* default behavior is to invoke <code>__call__(args, keywords)</code>
* with the appropriate arguments. The only reason to override this
* function would be for improved performance.
*
* @param args all arguments to the function.
**/
public PyObject __call__(PyObject args[]) {
return __call__(args, Py.NoKeywords);
}
/**
* A variant of the __call__ method with no arguments. The default
* behavior is to invoke <code>__call__(args, keywords)</code> with the
* appropriate arguments. The only reason to override this function
* would be for improved performance.
**/
public PyObject __call__() {
return __call__(Py.EmptyObjects, Py.NoKeywords);
}
/**
* A variant of the __call__ method with one argument. The default
* behavior is to invoke <code>__call__(args, keywords)</code> with the
* appropriate arguments. The only reason to override this function
* would be for improved performance.
*
* @param arg0 the single argument to the function.
**/
public PyObject __call__(PyObject arg0) {
return __call__(new PyObject[] { arg0 }, Py.NoKeywords);
}
/**
* A variant of the __call__ method with two arguments. The default
* behavior is to invoke <code>__call__(args, keywords)</code> with the
* appropriate arguments. The only reason to override this function
* would be for improved performance.
*
* @param arg0 the first argument to the function.
* @param arg1 the second argument to the function.
**/
public PyObject __call__(PyObject arg0, PyObject arg1) {
return __call__(new PyObject[] { arg0, arg1 }, Py.NoKeywords);
}
/**
* A variant of the __call__ method with three arguments. The default
* behavior is to invoke <code>__call__(args, keywords)</code> with the
* appropriate arguments. The only reason to override this function
* would be for improved performance.
*
* @param arg0 the first argument to the function.
* @param arg1 the second argument to the function.
* @param arg2 the third argument to the function.
**/
public PyObject __call__(PyObject arg0, PyObject arg1, PyObject arg2) {
return __call__(new PyObject[] { arg0, arg1, arg2 }, Py.NoKeywords);
}
/**
* A variant of the __call__ method with four arguments. The default
* behavior is to invoke <code>__call__(args, keywords)</code> with the
* appropriate arguments. The only reason to override this function
* would be for improved performance.
*
* @param arg0 the first argument to the function.
* @param arg1 the second argument to the function.
* @param arg2 the third argument to the function.
* @param arg3 the fourth argument to the function.
**/
public PyObject __call__(
PyObject arg0,
PyObject arg1,
PyObject arg2,
PyObject arg3) {
return __call__(
new PyObject[] { arg0, arg1, arg2, arg3 },
Py.NoKeywords);
}
/** @deprecated **/
public PyObject _callextra(PyObject[] args,
String[] keywords,
PyObject starargs,
PyObject kwargs) {
int argslen = args.length;
String name;
if (this instanceof PyFunction) {
name = ((PyFunction) this).__name__ + "() ";
} else if (this instanceof PyBuiltinCallable) {
name = ((PyBuiltinCallable)this).fastGetName().toString() + "() ";
} else {
name = getType().fastGetName() + " ";
}
if (kwargs != null) {
PyObject keys = kwargs.__findattr__("keys");
if(keys == null)
throw Py.TypeError(name
+ "argument after ** must be a mapping");
for (String keyword : keywords)
if (kwargs.__finditem__(keyword) != null)
throw Py.TypeError(
name
+ "got multiple values for "
+ "keyword argument '"
+ keyword
+ "'");
argslen += kwargs.__len__();
}
List<PyObject> starObjs = null;
if (starargs != null) {
starObjs = new ArrayList<PyObject>();
PyObject iter = Py.iter(starargs, name + "argument after * must be a sequence");
for (PyObject cur = null; ((cur = iter.__iternext__()) != null); ) {
starObjs.add(cur);
}
argslen += starObjs.size();
}
PyObject[] newargs = new PyObject[argslen];
int argidx = args.length - keywords.length;
System.arraycopy(args, 0, newargs, 0, argidx);
if(starObjs != null) {
Iterator<PyObject> it = starObjs.iterator();
while(it.hasNext()) {
newargs[argidx++] = it.next();
}
}
System.arraycopy(args,
args.length - keywords.length,
newargs,
argidx,
keywords.length);
argidx += keywords.length;
if (kwargs != null) {
String[] newkeywords =
new String[keywords.length + kwargs.__len__()];
System.arraycopy(keywords, 0, newkeywords, 0, keywords.length);
PyObject keys = kwargs.invoke("keys");
PyObject key;
for (int i = 0;(key = keys.__finditem__(i)) != null; i++) {
if (!(key instanceof PyString))
throw Py.TypeError(name + "keywords must be strings");
newkeywords[keywords.length + i] =
((PyString) key).internedString();
newargs[argidx++] = kwargs.__finditem__(key);
}
keywords = newkeywords;
}
if (newargs.length != argidx) {
args = new PyObject[argidx];
System.arraycopy(newargs, 0, args, 0, argidx);
} else
args = newargs;
return __call__(args, keywords);
}
/* xxx fix these around */
public boolean isCallable() {
return getType().lookup("__call__") != null;
}
public boolean isMappingType() {
return true;
}
public boolean isNumberType() {
return true;
}
public boolean isSequenceType() {
return true;
}
/**
* Determine if this object can act as an index (implements __index__).
*
* @return true if the object can act as an index
*/
public boolean isIndex() {
return getType().lookup("__index__") != null;
}
/* The basic functions to implement a mapping */
/**
* Equivalent to the standard Python __len__ method.
* Part of the mapping discipline.
*
* @return the length of the object
**/
public int __len__() {
throw Py.AttributeError("__len__");
}
/**
* Very similar to the standard Python __getitem__ method.
* Instead of throwing a KeyError if the item isn't found,
* this just returns null.
*
* Classes that wish to implement __getitem__ should
* override this method instead (with the appropriate
* semantics.
*
* @param key the key to lookup in this container
*
* @return the value corresponding to key or null if key is not found
**/
public PyObject __finditem__(PyObject key) {
throw Py.TypeError(String.format("'%.200s' object is unsubscriptable",
getType().fastGetName()));
}
/**
* A variant of the __finditem__ method which accepts a primitive
* <code>int</code> as the key. By default, this method will call
* <code>__finditem__(PyObject key)</code> with the appropriate args.
* The only reason to override this method is for performance.
*
* @param key the key to lookup in this sequence.
* @return the value corresponding to key or null if key is not found.
*
* @see #__finditem__(PyObject)
**/
public PyObject __finditem__(int key) {
return __finditem__(new PyInteger(key));
}
/**
* A variant of the __finditem__ method which accepts a Java
* <code>String</code> as the key. By default, this method will call
* <code>__finditem__(PyObject key)</code> with the appropriate args.
* The only reason to override this method is for performance.
*
* <b>Warning: key must be an interned string!!!!!!!!</b>
*
* @param key the key to lookup in this sequence -
* <b> must be an interned string </b>.
* @return the value corresponding to key or null if key is not found.
*
* @see #__finditem__(PyObject)
**/
public PyObject __finditem__(String key) {
return __finditem__(new PyString(key));
}
/**
* Equivalent to the standard Python __getitem__ method.
* This variant takes a primitive <code>int</code> as the key.
* This method should not be overridden.
* Override the <code>__finditem__</code> method instead.
*
* @param key the key to lookup in this container.
* @return the value corresponding to that key.
* @exception Py.KeyError if the key is not found.
*
* @see #__finditem__(int)
**/
public PyObject __getitem__(int key) {
PyObject ret = __finditem__(key);
if (ret == null)
throw Py.KeyError("" + key);
return ret;
}
/**
* Equivalent to the standard Python __getitem__ method.
* This method should not be overridden.
* Override the <code>__finditem__</code> method instead.
*
* @param key the key to lookup in this container.
* @return the value corresponding to that key.
* @exception Py.KeyError if the key is not found.
*
* @see #__finditem__(PyObject)
**/
public PyObject __getitem__(PyObject key) {
PyObject ret = __finditem__(key);
if (ret == null) {
throw Py.KeyError(key);
}
return ret;
}
/**
* Equivalent to the standard Python __setitem__ method.
*
* @param key the key whose value will be set
* @param value the value to set this key to
**/
public void __setitem__(PyObject key, PyObject value) {
throw Py.TypeError(String.format("'%.200s' object does not support item assignment",
getType().fastGetName()));
}
/**
* A variant of the __setitem__ method which accepts a String
* as the key. <b>This String must be interned</b>.
* By default, this will call
* <code>__setitem__(PyObject key, PyObject value)</code>
* with the appropriate args.
* The only reason to override this method is for performance.
*
* @param key the key whose value will be set -
* <b> must be an interned string </b>.
* @param value the value to set this key to
*
* @see #__setitem__(PyObject, PyObject)
**/
public void __setitem__(String key, PyObject value) {
__setitem__(new PyString(key), value);
}
/**
* A variant of the __setitem__ method which accepts a primitive
* <code>int</code> as the key.
* By default, this will call
* <code>__setitem__(PyObject key, PyObject value)</code>
* with the appropriate args.
* The only reason to override this method is for performance.
*
* @param key the key whose value will be set
* @param value the value to set this key to
*
* @see #__setitem__(PyObject, PyObject)
**/
public void __setitem__(int key, PyObject value) {
__setitem__(new PyInteger(key), value);
}
/**
* Equivalent to the standard Python __delitem__ method.
*
* @param key the key to be removed from the container
* @exception Py.KeyError if the key is not found in the container
**/
public void __delitem__(PyObject key) {
throw Py.TypeError(String.format("'%.200s' object doesn't support item deletion",
getType().fastGetName()));
}
/**
* A variant of the __delitem__ method which accepts a String
* as the key. <b>This String must be interned</b>.
* By default, this will call
* <code>__delitem__(PyObject key)</code>
* with the appropriate args.
* The only reason to override this method is for performance.
*
* @param key the key who will be removed -
* <b> must be an interned string </b>.
* @exception Py.KeyError if the key is not found in the container
*
* @see #__delitem__(PyObject)
**/
public void __delitem__(String key) {
__delitem__(new PyString(key));
}
public PyObject __getslice__(
PyObject s_start,
PyObject s_stop,
PyObject s_step) {
PySlice s = new PySlice(s_start, s_stop, s_step);
return __getitem__(s);
}
public void __setslice__(
PyObject s_start,
PyObject s_stop,
PyObject s_step,
PyObject value) {
PySlice s = new PySlice(s_start, s_stop, s_step);
__setitem__(s, value);
}
public void __delslice__(
PyObject s_start,
PyObject s_stop,
PyObject s_step) {
PySlice s = new PySlice(s_start, s_stop, s_step);
__delitem__(s);
}
public PyObject __getslice__(PyObject start, PyObject stop) {
return __getslice__(start, stop, null);
}
public void __setslice__(PyObject start, PyObject stop, PyObject value) {
__setslice__(start, stop, null, value);
}
public void __delslice__(PyObject start, PyObject stop) {
__delslice__(start, stop, null);
}
/*The basic functions to implement an iterator */
/**
* Return an iterator that is used to iterate the element of this sequence. From version 2.2,
* this method is the primary protocol for looping over sequences.
* <p>
* If a PyObject subclass should support iteration based in the __finditem__() method, it must
* supply an implementation of __iter__() like this:
*
* <pre>
* public PyObject __iter__() {
* return new PySequenceIter(this);
* }
* </pre>
*
* When iterating over a python sequence from java code, it should be done with code like this:
*
* <pre>
* for (PyObject item : seq.asIterable()) {
* // Do somting with item
* }
* </pre>
*
* @since 2.2
*/
public PyObject __iter__() {
throw Py.TypeError(String.format("'%.200s' object is not iterable",
getType().fastGetName()));
}
/**
* Returns an Iterable over the Python iterator returned by __iter__ on this object. If this
* object doesn't support __iter__, a TypeException will be raised when iterator is called on
* the returned Iterable.
*/
public Iterable<PyObject> asIterable() {
return new Iterable<PyObject>() {
public Iterator<PyObject> iterator() {
return new WrappedIterIterator<PyObject>(__iter__()) {
public PyObject next() {
return getNext();
}
};
}
};
}
/**
* Return the next element of the sequence that this is an iterator
* for. Returns null when the end of the sequence is reached.
*
* @since 2.2
*/
public PyObject __iternext__() {
return null;
}
/*The basic functions to implement a namespace*/
/**
* Very similar to the standard Python __getattr__ method. Instead of
* throwing a AttributeError if the item isn't found, this just returns
* null.
*
* By default, this method will call
* <code>__findattr__(name.internedString)</code> with the appropriate
* args.
*
* @param name the name to lookup in this namespace
*
* @return the value corresponding to name or null if name is not found
*/
public final PyObject __findattr__(PyString name) {
if (name == null) {
return null;
}
return __findattr__(name.internedString());
}
/**
* A variant of the __findattr__ method which accepts a Java
* <code>String</code> as the name.
*
* <b>Warning: name must be an interned string!</b>
*
* @param name the name to lookup in this namespace
* <b> must be an interned string </b>.
* @return the value corresponding to name or null if name is not found
**/
public final PyObject __findattr__(String name) {
try {
return __findattr_ex__(name);
} catch (PyException exc) {
if (Py.matchException(exc, Py.AttributeError)) {
return null;
}
throw exc;
}
}
/**
* Attribute lookup hook. If the attribute is not found, null may be
* returned or a Py.AttributeError can be thrown, whatever is more
* correct, efficient and/or convenient for the implementing class.
*
* Client code should use {@link #__getattr__(String)} or
* {@link #__findattr__(String)}. Both methods have a clear policy for
* failed lookups.
*
* @return The looked up value. May return null if the attribute is not found
* @throws PyException(AttributeError) if the attribute is not found. This
* is not mandatory, null can be returned if it fits the implementation
* better, or for performance reasons.
*/
public PyObject __findattr_ex__(String name) {
return object___findattr__(name);
}
/**
* Equivalent to the standard Python __getattr__ method.
*
* By default, this method will call
* <code>__getattr__(name.internedString)</code> with the appropriate
* args.
*
* @param name the name to lookup in this namespace
* @return the value corresponding to name
* @exception Py.AttributeError if the name is not found.
*
* @see #__findattr_ex__(PyString)
**/
public final PyObject __getattr__(PyString name) {
return __getattr__(name.internedString());
}
/**
* A variant of the __getattr__ method which accepts a Java
* <code>String</code> as the name.
* This method can not be overridden.
* Override the <code>__findattr_ex__</code> method instead.
*
* <b>Warning: name must be an interned string!!!!!!!!</b>
*
* @param name the name to lookup in this namespace
* <b> must be an interned string </b>.
* @return the value corresponding to name
* @exception Py.AttributeError if the name is not found.
*
* @see #__findattr__(java.lang.String)
**/
public final PyObject __getattr__(String name) {
PyObject ret = __findattr_ex__(name);
if (ret == null)
noAttributeError(name);
return ret;
}
public void noAttributeError(String name) {
throw Py.AttributeError(String.format("'%.50s' object has no attribute '%.400s'",
getType().fastGetName(), name));
}
public void readonlyAttributeError(String name) {
// XXX: Should be an AttributeError but CPython throws TypeError for read only
// member descriptors (in structmember.c::PyMember_SetOne), which is expected by a
// few tests. fixed in py3k: http://bugs.python.org/issue1687163
throw Py.TypeError("readonly attribute");
}
/**
* Equivalent to the standard Python __setattr__ method.
* This method can not be overridden.
*
* @param name the name to lookup in this namespace
* @exception Py.AttributeError if the name is not found.
*
* @see #__setattr__(java.lang.String, PyObject)
**/
public final void __setattr__(PyString name, PyObject value) {
__setattr__(name.internedString(), value);
}
/**
* A variant of the __setattr__ method which accepts a String
* as the key. <b>This String must be interned</b>.
*
* @param name the name whose value will be set -
* <b> must be an interned string </b>.
* @param value the value to set this name to
*
* @see #__setattr__(PyString, PyObject)
**/
public void __setattr__(String name, PyObject value) {
object___setattr__(name, value);
}
/**
* Equivalent to the standard Python __delattr__ method.
* This method can not be overridden.
*
* @param name the name to which will be removed
* @exception Py.AttributeError if the name doesn't exist
*
* @see #__delattr__(java.lang.String)
**/
public final void __delattr__(PyString name) {
__delattr__(name.internedString());
}
/**
* A variant of the __delattr__ method which accepts a String
* as the key. <b>This String must be interned</b>.
* By default, this will call
* <code>__delattr__(PyString name)</code>
* with the appropriate args.
* The only reason to override this method is for performance.
*
* @param name the name which will be removed -
* <b> must be an interned string </b>.
* @exception Py.AttributeError if the name doesn't exist
*
* @see #__delattr__(PyString)
**/
public void __delattr__(String name) {
object___delattr__(name);
}
// Used by import logic.
protected PyObject impAttr(String name) {
return __findattr__(name);
}
protected void mergeListAttr(PyDictionary accum, String attr) {
PyObject obj = __findattr__(attr);
if (obj == null) {
return;
}
if (obj instanceof PyList) {
for (PyObject name : obj.asIterable()) {
accum.__setitem__(name, Py.None);
}
}
}
protected void mergeDictAttr(PyDictionary accum, String attr) {
PyObject obj = __findattr__(attr);
if (obj == null) {
return;
}
if (obj instanceof PyDictionary || obj instanceof PyStringMap
|| obj instanceof PyDictProxy) {
accum.update(obj);
}
}
protected void mergeClassDict(PyDictionary accum, PyObject aClass) {
// Merge in the type's dict (if any)
aClass.mergeDictAttr(accum, "__dict__");
// Recursively merge in the base types' (if any) dicts
PyObject bases = aClass.__findattr__("__bases__");
if (bases == null) {
return;
}
// We have no guarantee that bases is a real tuple
int len = bases.__len__();
for (int i = 0; i < len; i++) {
mergeClassDict(accum, bases.__getitem__(i));
}
}
protected void __rawdir__(PyDictionary accum) {
mergeDictAttr(accum, "__dict__");
mergeListAttr(accum, "__methods__");
mergeListAttr(accum, "__members__");
// Class dict is a slower, more manual merge to match CPython
PyObject itsClass = __findattr__("__class__");
if (itsClass != null) {
mergeClassDict(accum, itsClass);
}
}
/**
* Equivalent to the standard Python __dir__ method.
*
* @return a list of names defined by this object.
**/
public PyObject __dir__() {
PyDictionary accum = new PyDictionary();
__rawdir__(accum);
PyList ret = accum.keys();
ret.sort();
return ret;
}
public PyObject _doget(PyObject container) {
return this;
}
public PyObject _doget(PyObject container, PyObject wherefound) {
return _doget(container);
}
public boolean _doset(PyObject container, PyObject value) {
return false;
}
boolean jdontdel() {
return false;
}
/* Numeric coercion */
/**
* Implements numeric coercion
*
* @param o the other object involved in the coercion
* @return null if coercion is not implemented
* Py.None if coercion was not possible
* a single PyObject to use to replace o if this is unchanged;
* or a PyObject[2] consisting of replacements for this and o.
**/
public Object __coerce_ex__(PyObject o) {
return null;
}
/**
* Implements coerce(this,other), result as PyObject[]
* @param other
* @return PyObject[]
*/
PyObject[] _coerce(PyObject other) {
Object result;
if (this.getType() == other.getType() &&
!(this instanceof PyInstance)) {
return new PyObject[] {this, other};
}
result = this.__coerce_ex__(other);
if (result != null && result != Py.None) {
if (result instanceof PyObject[]) {
return (PyObject[])result;
} else {
return new PyObject[] {this, (PyObject)result};
}
}
result = other.__coerce_ex__(this);
if (result != null && result != Py.None) {
if (result instanceof PyObject[]) {
return (PyObject[])result;
} else {
return new PyObject[] {(PyObject)result, other};
}
}
return null;
}
/**
* Equivalent to the standard Python __coerce__ method.
*
* This method can not be overridden.
* To implement __coerce__ functionality, override __coerce_ex__ instead.
*
* Also, <b>do not</b> call this method from exposed 'coerce' methods.
* Instead, Use adaptToCoerceTuple over the result of the overriden
* __coerce_ex__.
*
* @param pyo the other object involved in the coercion.
* @return a tuple of this object and pyo coerced to the same type
* or Py.NotImplemented if no coercion is possible.
* @see org.python.core.PyObject#__coerce_ex__(org.python.core.PyObject)
**/
public final PyObject __coerce__(PyObject pyo) {
Object o = __coerce_ex__(pyo);
if (o == null) {
throw Py.AttributeError("__coerce__");
}
return adaptToCoerceTuple(o);
}
/**
* Adapts the result of __coerce_ex__ to a tuple of two elements, with the
* resulting coerced values, or to Py.NotImplemented, if o is Py.None.
*
* This is safe to be used from subclasses exposing '__coerce__'
* (as opposed to {@link #__coerce__(PyObject)}, which calls the virtual
* method {@link #__coerce_ex__(PyObject)})
*
* @param o either a PyObject[2] or a PyObject, as given by
* {@link #__coerce_ex__(PyObject)}.
*/
protected final PyObject adaptToCoerceTuple(Object o) {
if (o == Py.None) {
return Py.NotImplemented;
}
if (o instanceof PyObject[]) {
return new PyTuple((PyObject[]) o);
} else {
return new PyTuple(this, (PyObject) o );
}
}
/* The basic comparision operations */
/**
* Equivalent to the standard Python __cmp__ method.
*
* @param other the object to compare this with.
* @return -1 if this < o; 0 if this == o; +1 if this > o; -2 if no
* comparison is implemented
**/
public int __cmp__(PyObject other) {
return -2;
}
/**
* Equivalent to the standard Python __eq__ method.
*
* @param other the object to compare this with.
* @return the result of the comparison.
**/
public PyObject __eq__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __ne__ method.
*
* @param other the object to compare this with.
* @return the result of the comparison.
**/
public PyObject __ne__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __le__ method.
*
* @param other the object to compare this with.
* @return the result of the comparison.
**/
public PyObject __le__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __lt__ method.
*
* @param other the object to compare this with.
* @return the result of the comparison.
**/
public PyObject __lt__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __ge__ method.
*
* @param other the object to compare this with.
* @return the result of the comparison.
**/
public PyObject __ge__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __gt__ method.
*
* @param other the object to compare this with.
* @return the result of the comparison.
**/
public PyObject __gt__(PyObject other) {
return null;
}
/**
* Implements cmp(this, other)
*
* @param o the object to compare this with.
* @return -1 if this < 0; 0 if this == o; +1 if this > o
**/
public final int _cmp(PyObject o) {
PyObject token = null;
ThreadState ts = Py.getThreadState();
try {
if (++ts.compareStateNesting > 500) {
if ((token = check_recursion(ts, this, o)) == null)
return 0;
}
PyObject r;
r = __eq__(o);
if (r != null && r.__nonzero__())
return 0;
r = o.__eq__(this);
if (r != null && r.__nonzero__())
return 0;
r = __lt__(o);
if (r != null && r.__nonzero__())
return -1;
r = o.__gt__(this);
if (r != null && r.__nonzero__())
return -1;
r = __gt__(o);
if (r != null && r.__nonzero__())
return 1;
r = o.__lt__(this);
if (r != null && r.__nonzero__())
return 1;
return _cmp_unsafe(o);
} finally {
delete_token(ts, token);
ts.compareStateNesting--;
}
}
private PyObject make_pair(PyObject o) {
if (System.identityHashCode(this) < System.identityHashCode(o))
return new PyIdentityTuple(new PyObject[] { this, o });
else
return new PyIdentityTuple(new PyObject[] { o, this });
}
private final int _default_cmp(PyObject other) {
int result;
if (this._is(other).__nonzero__())
return 0;
/* None is smaller than anything */
if (this == Py.None)
return -1;
if (other == Py.None)
return 1;
// No rational way to compare these, so ask their classes to compare
PyType this_type = this.getType();
PyType other_type = other.getType();
if (this_type == other_type) {
return Py.id(this) < Py.id(other)? -1: 1;
}
result = this_type.fastGetName().compareTo(other_type.fastGetName());
if (result == 0)
return Py.id(this_type)<Py.id(other_type)? -1: 1;
return result < 0? -1: 1;
}
private final int _cmp_unsafe(PyObject other) {
// Shortcut for equal objects
if (this == other)
return 0;
int result = _try__cmp__(other);
if (result != -2) {
return result;
}
return this._default_cmp(other);
}
/*
* Like _cmp_unsafe but limited to ==/!= as 0/!=0,
* thus it avoids to invoke _default_cmp.
*/
private final int _cmpeq_unsafe(PyObject other) {
// Shortcut for equal objects
if (this == other)
return 0;
int result = _try__cmp__(other);
if (result != -2) {
return result;
}
return this._is(other).__nonzero__()?0:1;
}
/**
* Tries a 3-way comparison, using __cmp__. It tries the following
* operations until one of them succeed:<ul>
* <li>this.__cmp__(other)
* <li>other.__cmp__(this)
* <li>this._coerce(other) followed by coerced_this.__cmp__(coerced_other)</ul>
*
* @return -1, 0, -1 or -2, according to the {@link #__cmp__} protocol.
*/
private int _try__cmp__(PyObject other) {
int result;
result = this.__cmp__(other);
if (result != -2)
return result;
if (!(this instanceof PyInstance)) {
result = other.__cmp__(this);
if (result != -2)
return -result;
}
// Final attempt: coerce both arguments and compare that. We are doing
// this the same point where CPython 2.5 does. (See
// <http://svn.python.org/projects/python/tags/r252/Objects/object.c> at
// the end of try_3way_compare).
//
// This is not exactly was is specified on
// <http://docs.python.org/ref/coercion-rules.html>, where coercion is
// supposed to happen before trying __cmp__.
PyObject[] coerced = _coerce(other);
if (coerced != null) {
result = coerced[0].__cmp__(coerced[1]);
if (result != -2) {
return result;
}
}
return -2;
}
private final static PyObject check_recursion(
ThreadState ts,
PyObject o1,
PyObject o2) {
PyDictionary stateDict = ts.getCompareStateDict();
PyObject pair = o1.make_pair(o2);
if (stateDict.__finditem__(pair) != null)
return null;
stateDict.__setitem__(pair, pair);
return pair;
}
private final static void delete_token(ThreadState ts, PyObject token) {
if (token == null)
return;
PyDictionary stateDict = ts.getCompareStateDict();
stateDict.__delitem__(token);
}
/**
* Implements the Python expression <code>this == other</code>.
*
* @param o the object to compare this with.
* @return the result of the comparison
**/
public final PyObject _eq(PyObject o) {
PyObject token = null;
PyType t1 = this.getType();
PyType t2 = o.getType();
if (t1 != t2 && t2.isSubType(t1)) {
return o._eq(this);
}
ThreadState ts = Py.getThreadState();
try {
if (++ts.compareStateNesting > 10) {
if ((token = check_recursion(ts, this, o)) == null)
return Py.True;
}
PyObject res = __eq__(o);
if (res != null)
return res;
res = o.__eq__(this);
if (res != null)
return res;
return _cmpeq_unsafe(o) == 0 ? Py.True : Py.False;
} catch (PyException e) {
if (Py.matchException(e, Py.AttributeError)) {
return Py.False;
}
throw e;
} finally {
delete_token(ts, token);
ts.compareStateNesting--;
}
}
/**
* Implements the Python expression <code>this != other</code>.
*
* @param o the object to compare this with.
* @return the result of the comparison
**/
public final PyObject _ne(PyObject o) {
PyObject token = null;
PyType t1 = this.getType();
PyType t2 = o.getType();
if (t1 != t2 && t2.isSubType(t1)) {
return o._ne(this);
}
ThreadState ts = Py.getThreadState();
try {
if (++ts.compareStateNesting > 10) {
if ((token = check_recursion(ts, this, o)) == null)
return Py.False;
}
PyObject res = __ne__(o);
if (res != null)
return res;
res = o.__ne__(this);
if (res != null)
return res;
return _cmpeq_unsafe(o) != 0 ? Py.True : Py.False;
} finally {
delete_token(ts, token);
ts.compareStateNesting--;
}
}
/**
* Implements the Python expression <code>this <= other</code>.
*
* @param o the object to compare this with.
* @return the result of the comparison
**/
public final PyObject _le(PyObject o) {
PyObject token = null;
PyType t1 = this.getType();
PyType t2 = o.getType();
if (t1 != t2 && t2.isSubType(t1)) {
return o._ge(this);
}
ThreadState ts = Py.getThreadState();
try {
if (++ts.compareStateNesting > 10) {
if ((token = check_recursion(ts, this, o)) == null)
throw Py.ValueError("can't order recursive values");
}
PyObject res = __le__(o);
if (res != null)
return res;
res = o.__ge__(this);
if (res != null)
return res;
return _cmp_unsafe(o) <= 0 ? Py.True : Py.False;
} finally {
delete_token(ts, token);
ts.compareStateNesting--;
}
}
/**
* Implements the Python expression <code>this < other</code>.
*
* @param o the object to compare this with.
* @return the result of the comparison
**/
public final PyObject _lt(PyObject o) {
PyObject token = null;
PyType t1 = this.getType();
PyType t2 = o.getType();
if (t1 != t2 && t2.isSubType(t1)) {
return o._gt(this);
}
ThreadState ts = Py.getThreadState();
try {
if (++ts.compareStateNesting > 10) {
if ((token = check_recursion(ts, this, o)) == null)
throw Py.ValueError("can't order recursive values");
}
PyObject res = __lt__(o);
if (res != null)
return res;
res = o.__gt__(this);
if (res != null)
return res;
return _cmp_unsafe(o) < 0 ? Py.True : Py.False;
} finally {
delete_token(ts, token);
ts.compareStateNesting--;
}
}
/**
* Implements the Python expression <code>this >= other</code>.
*
* @param o the object to compare this with.
* @return the result of the comparison
**/
public final PyObject _ge(PyObject o) {
PyObject token = null;
PyType t1 = this.getType();
PyType t2 = o.getType();
if (t1 != t2 && t2.isSubType(t1)) {
return o._le(this);
}
ThreadState ts = Py.getThreadState();
try {
if (++ts.compareStateNesting > 10) {
if ((token = check_recursion(ts, this, o)) == null)
throw Py.ValueError("can't order recursive values");
}
PyObject res = __ge__(o);
if (res != null)
return res;
res = o.__le__(this);
if (res != null)
return res;
return _cmp_unsafe(o) >= 0 ? Py.True : Py.False;
} finally {
delete_token(ts, token);
ts.compareStateNesting--;
}
}
/**
* Implements the Python expression <code>this > other</code>.
*
* @param o the object to compare this with.
* @return the result of the comparison
**/
public final PyObject _gt(PyObject o) {
PyObject token = null;
PyType t1 = this.getType();
PyType t2 = o.getType();
if (t1 != t2 && t2.isSubType(t1)) {
return o._lt(this);
}
ThreadState ts = Py.getThreadState();
try {
if (++ts.compareStateNesting > 10) {
if ((token = check_recursion(ts, this, o)) == null)
throw Py.ValueError("can't order recursive values");
}
PyObject res = __gt__(o);
if (res != null)
return res;
res = o.__lt__(this);
if (res != null)
return res;
return _cmp_unsafe(o) > 0 ? Py.True : Py.False;
} finally {
delete_token(ts, token);
ts.compareStateNesting--;
}
}
/**
* Implements <code>is</code> operator.
*
* @param o the object to compare this with.
* @return the result of the comparison
**/
public PyObject _is(PyObject o) {
// Access javaProxy directly here as is is for object identity, and at best getJavaProxy
// will initialize a new object with a different identity
return this == o || (javaProxy != null && javaProxy == o.javaProxy) ? Py.True : Py.False;
}
/**
* Implements <code>is not</code> operator.
*
* @param o the object to compare this with.
* @return the result of the comparison
**/
public PyObject _isnot(PyObject o) {
// Access javaProxy directly here as is is for object identity, and at best getJavaProxy
// will initialize a new object with a different identity
return this != o || javaProxy != o.javaProxy ? Py.True : Py.False;
}
/**
* Implements <code>in</code> operator.
*
* @param o the container to search for this element.
* @return the result of the search.
**/
public final PyObject _in(PyObject o) {
return Py.newBoolean(o.__contains__(this));
}
/**
* Implements <code>not in</code> operator.
*
* @param o the container to search for this element.
* @return the result of the search.
**/
public final PyObject _notin(PyObject o) {
return Py.newBoolean(!o.__contains__(this));
}
/**
* Equivalent to the standard Python __contains__ method.
*
* @param o the element to search for in this container.
* @return the result of the search.
**/
public boolean __contains__(PyObject o) {
return object___contains__(o);
}
final boolean object___contains__(PyObject o) {
for (PyObject item : asIterable()) {
if (o._eq(item).__nonzero__()) {
return true;
}
}
return false;
}
/**
* Implements boolean not
*
* @return not this.
**/
public PyObject __not__() {
return __nonzero__() ? Py.False : Py.True;
}
/* The basic numeric operations */
/**
* Equivalent to the standard Python __hex__ method
* Should only be overridden by numeric objects that can be
* reasonably represented as a hexadecimal string.
*
* @return a string representing this object as a hexadecimal number.
**/
public PyString __hex__() {
throw Py.TypeError("hex() argument can't be converted to hex");
}
/**
* Equivalent to the standard Python __oct__ method.
* Should only be overridden by numeric objects that can be
* reasonably represented as an octal string.
*
* @return a string representing this object as an octal number.
**/
public PyString __oct__() {
throw Py.TypeError("oct() argument can't be converted to oct");
}
/**
* Equivalent to the standard Python __int__ method.
* Should only be overridden by numeric objects that can be
* reasonably coerced into an integer.
*
* @return an integer corresponding to the value of this object.
**/
public PyObject __int__() {
throw Py.AttributeError("__int__");
}
/**
* Equivalent to the standard Python __long__ method.
* Should only be overridden by numeric objects that can be
* reasonably coerced into a python long.
*
* @return a PyLong or PyInteger corresponding to the value of this object.
**/
public PyObject __long__() {
throw Py.AttributeError("__long__");
}
/**
* Equivalent to the standard Python __float__ method.
* Should only be overridden by numeric objects that can be
* reasonably coerced into a python float.
*
* @return a float corresponding to the value of this object.
**/
public PyFloat __float__() {
throw Py.AttributeError("__float__");
}
/**
* Equivalent to the standard Python __complex__ method.
* Should only be overridden by numeric objects that can be
* reasonably coerced into a python complex number.
*
* @return a complex number corresponding to the value of this object.
**/
public PyComplex __complex__() {
throw Py.AttributeError("__complex__");
}
/**
* Equivalent to the standard Python __pos__ method.
*
* @return +this.
**/
public PyObject __pos__() {
throw Py.TypeError(String.format("bad operand type for unary +: '%.200s'",
getType().fastGetName()));
}
/**
* Equivalent to the standard Python __neg__ method.
*
* @return -this.
**/
public PyObject __neg__() {
throw Py.TypeError(String.format("bad operand type for unary -: '%.200s'",
getType().fastGetName()));
}
/**
* Equivalent to the standard Python __abs__ method.
*
* @return abs(this).
**/
public PyObject __abs__() {
throw Py.TypeError(String.format("bad operand type for abs(): '%.200s'",
getType().fastGetName()));
}
/**
* Equivalent to the standard Python __invert__ method.
*
* @return ~this.
**/
public PyObject __invert__() {
throw Py.TypeError(String.format("bad operand type for unary ~: '%.200s'",
getType().fastGetName()));
}
/**
* Equivalent to the standard Python __index__ method.
*
* @return a PyInteger or PyLong
* @throws a Py.TypeError if not supported
**/
public PyObject __index__() {
throw Py.TypeError(String.format("'%.200s' object cannot be interpreted as an index",
getType().fastGetName()));
}
/**
* @param op the String form of the op (e.g. "+")
* @param o2 the right operand
*/
protected final String _unsupportedop(String op, PyObject o2) {
Object[] args = {op, getType().fastGetName(), o2.getType().fastGetName()};
String msg = unsupportedopMessage(op, o2);
if (msg == null) {
msg = o2.runsupportedopMessage(op, o2);
}
if (msg == null) {
msg = "unsupported operand type(s) for {0}: ''{1}'' and ''{2}''";
}
return MessageFormat.format(msg, args);
}
/**
* Should return an error message suitable for substitution where.
*
* {0} is the op name.
* {1} is the left operand type.
* {2} is the right operand type.
*/
protected String unsupportedopMessage(String op, PyObject o2) {
return null;
}
/**
* Should return an error message suitable for substitution where.
*
* {0} is the op name.
* {1} is the left operand type.
* {2} is the right operand type.
*/
protected String runsupportedopMessage(String op, PyObject o2) {
return null;
}
/**
* Implements the three argument power function.
*
* @param o2 the power to raise this number to.
* @param o3 the modulus to perform this operation in or null if no
* modulo is to be used
* @return this object raised to the given power in the given modulus
**/
public PyObject __pow__(PyObject o2, PyObject o3) {
return null;
}
/**
* Determine if the binary op on types t1 and t2 is an add
* operation dealing with a str/unicode and a str/unicode
* subclass.
*
* This operation is special cased in _binop_rule to match
* CPython's handling; CPython uses tp_as_number and
* tp_as_sequence to allow string/unicode subclasses to override
* the left side's __add__ when that left side is an actual str or
* unicode object (see test_concat_jy for examples).
*
* @param t1 left side PyType
* @param t2 right side PyType
* @param op the binary operation's String
* @return true if this is a special case
*/
private boolean isStrUnicodeSpecialCase(PyType t1, PyType t2, String op) {
// XXX: We may need to generalize this rule to apply to other
// situations
// XXX: This method isn't expensive but could (and maybe
// should?) be optimized for worst case scenarios
return op == "+" && (t1 == PyString.TYPE || t1 == PyUnicode.TYPE) &&
(t2.isSubType(PyString.TYPE) || t2.isSubType(PyUnicode.TYPE));
}
private PyObject _binop_rule(PyType t1, PyObject o2, PyType t2,
String left, String right, String op) {
/*
* this is the general rule for binary operation dispatching try first
* __xxx__ with this and then __rxxx__ with o2 unless o2 is an instance
* of subclass of the type of this, and further __xxx__ and __rxxx__ are
* unrelated ( checked here by looking at where in the hierarchy they
* are defined), in that case try them in the reverse order. This is the
* same formulation as used by PyPy, see also
* test_descr.subclass_right_op.
*/
PyObject o1 = this;
PyObject[] where = new PyObject[1];
PyObject where1 = null, where2 = null;
PyObject impl1 = t1.lookup_where(left, where);
where1 = where[0];
PyObject impl2 = t2.lookup_where(right, where);
where2 = where[0];
if (impl2 != null && impl1 != null && where1 != where2 &&
(t2.isSubType(t1) && !Py.isSubClass(where1, where2)
&& !Py.isSubClass(t1, where2) ||
isStrUnicodeSpecialCase(t1, t2, op))) {
PyObject tmp = o1;
o1 = o2;
o2 = tmp;
tmp = impl1;
impl1 = impl2;
impl2 = tmp;
PyType ttmp;
ttmp = t1;
t1 = t2;
t2 = ttmp;
}
PyObject res = null;
if (impl1 != null) {
res = impl1.__get__(o1, t1).__call__(o2);
if (res != Py.NotImplemented) {
return res;
}
}
if (impl2 != null) {
res = impl2.__get__(o2, t2).__call__(o1);
if (res != Py.NotImplemented) {
return res;
}
}
throw Py.TypeError(_unsupportedop(op, o2));
}
// Generated by make_binops.py (Begin)
/**
* Equivalent to the standard Python __add__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the add, or null if this operation
* is not defined
**/
public PyObject __add__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __radd__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the add, or null if this operation
* is not defined.
**/
public PyObject __radd__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __iadd__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the iadd, or null if this operation
* is not defined
**/
public PyObject __iadd__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this + o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the add.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _add(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_add(o2);
}
return _binop_rule(t1,o2,t2,"__add__","__radd__","+");
}
/**
* Implements the Python expression <code>this + o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the add.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_add(PyObject o2) {
PyObject x=__add__(o2);
if (x!=null) {
return x;
}
x=o2.__radd__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("+",o2));
}
/**
* Implements the Python expression <code>this += o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the iadd.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _iadd(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_iadd(o2);
}
PyObject impl=t1.lookup("__iadd__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__add__","__radd__","+");
}
/**
* Implements the Python expression <code>this += o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the iadd.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_iadd(PyObject o2) {
PyObject x=__iadd__(o2);
if (x!=null) {
return x;
}
return this._basic_add(o2);
}
/**
* Equivalent to the standard Python __sub__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the sub, or null if this operation
* is not defined
**/
public PyObject __sub__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rsub__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the sub, or null if this operation
* is not defined.
**/
public PyObject __rsub__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __isub__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the isub, or null if this operation
* is not defined
**/
public PyObject __isub__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this - o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the sub.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _sub(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_sub(o2);
}
return _binop_rule(t1,o2,t2,"__sub__","__rsub__","-");
}
/**
* Implements the Python expression <code>this - o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the sub.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_sub(PyObject o2) {
PyObject x=__sub__(o2);
if (x!=null) {
return x;
}
x=o2.__rsub__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("-",o2));
}
/**
* Implements the Python expression <code>this -= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the isub.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _isub(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_isub(o2);
}
PyObject impl=t1.lookup("__isub__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__sub__","__rsub__","-");
}
/**
* Implements the Python expression <code>this -= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the isub.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_isub(PyObject o2) {
PyObject x=__isub__(o2);
if (x!=null) {
return x;
}
return this._basic_sub(o2);
}
/**
* Equivalent to the standard Python __mul__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the mul, or null if this operation
* is not defined
**/
public PyObject __mul__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rmul__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the mul, or null if this operation
* is not defined.
**/
public PyObject __rmul__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __imul__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the imul, or null if this operation
* is not defined
**/
public PyObject __imul__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this * o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the mul.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _mul(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_mul(o2);
}
return _binop_rule(t1,o2,t2,"__mul__","__rmul__","*");
}
/**
* Implements the Python expression <code>this * o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the mul.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_mul(PyObject o2) {
PyObject x=__mul__(o2);
if (x!=null) {
return x;
}
x=o2.__rmul__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("*",o2));
}
/**
* Implements the Python expression <code>this *= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the imul.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _imul(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_imul(o2);
}
PyObject impl=t1.lookup("__imul__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__mul__","__rmul__","*");
}
/**
* Implements the Python expression <code>this *= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the imul.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_imul(PyObject o2) {
PyObject x=__imul__(o2);
if (x!=null) {
return x;
}
return this._basic_mul(o2);
}
/**
* Equivalent to the standard Python __div__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the div, or null if this operation
* is not defined
**/
public PyObject __div__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rdiv__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the div, or null if this operation
* is not defined.
**/
public PyObject __rdiv__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __idiv__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the idiv, or null if this operation
* is not defined
**/
public PyObject __idiv__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this / o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the div.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _div(PyObject o2) {
if (Options.Qnew)
return _truediv(o2);
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_div(o2);
}
return _binop_rule(t1,o2,t2,"__div__","__rdiv__","/");
}
/**
* Implements the Python expression <code>this / o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the div.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_div(PyObject o2) {
PyObject x=__div__(o2);
if (x!=null) {
return x;
}
x=o2.__rdiv__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("/",o2));
}
/**
* Implements the Python expression <code>this /= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the idiv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _idiv(PyObject o2) {
if (Options.Qnew)
return _itruediv(o2);
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_idiv(o2);
}
PyObject impl=t1.lookup("__idiv__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__div__","__rdiv__","/");
}
/**
* Implements the Python expression <code>this /= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the idiv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_idiv(PyObject o2) {
PyObject x=__idiv__(o2);
if (x!=null) {
return x;
}
return this._basic_div(o2);
}
/**
* Equivalent to the standard Python __floordiv__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the floordiv, or null if this operation
* is not defined
**/
public PyObject __floordiv__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rfloordiv__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the floordiv, or null if this operation
* is not defined.
**/
public PyObject __rfloordiv__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __ifloordiv__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the ifloordiv, or null if this operation
* is not defined
**/
public PyObject __ifloordiv__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this // o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the floordiv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _floordiv(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_floordiv(o2);
}
return _binop_rule(t1,o2,t2,"__floordiv__","__rfloordiv__","//");
}
/**
* Implements the Python expression <code>this // o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the floordiv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_floordiv(PyObject o2) {
PyObject x=__floordiv__(o2);
if (x!=null) {
return x;
}
x=o2.__rfloordiv__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("//",o2));
}
/**
* Implements the Python expression <code>this //= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ifloordiv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _ifloordiv(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_ifloordiv(o2);
}
PyObject impl=t1.lookup("__ifloordiv__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__floordiv__","__rfloordiv__","//");
}
/**
* Implements the Python expression <code>this //= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ifloordiv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_ifloordiv(PyObject o2) {
PyObject x=__ifloordiv__(o2);
if (x!=null) {
return x;
}
return this._basic_floordiv(o2);
}
/**
* Equivalent to the standard Python __truediv__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the truediv, or null if this operation
* is not defined
**/
public PyObject __truediv__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rtruediv__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the truediv, or null if this operation
* is not defined.
**/
public PyObject __rtruediv__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __itruediv__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the itruediv, or null if this operation
* is not defined
**/
public PyObject __itruediv__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this / o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the truediv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _truediv(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_truediv(o2);
}
return _binop_rule(t1,o2,t2,"__truediv__","__rtruediv__","/");
}
/**
* Implements the Python expression <code>this / o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the truediv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_truediv(PyObject o2) {
PyObject x=__truediv__(o2);
if (x!=null) {
return x;
}
x=o2.__rtruediv__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("/",o2));
}
/**
* Implements the Python expression <code>this /= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the itruediv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _itruediv(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_itruediv(o2);
}
PyObject impl=t1.lookup("__itruediv__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__truediv__","__rtruediv__","/");
}
/**
* Implements the Python expression <code>this /= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the itruediv.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_itruediv(PyObject o2) {
PyObject x=__itruediv__(o2);
if (x!=null) {
return x;
}
return this._basic_truediv(o2);
}
/**
* Equivalent to the standard Python __mod__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the mod, or null if this operation
* is not defined
**/
public PyObject __mod__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rmod__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the mod, or null if this operation
* is not defined.
**/
public PyObject __rmod__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __imod__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the imod, or null if this operation
* is not defined
**/
public PyObject __imod__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this % o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the mod.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _mod(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_mod(o2);
}
return _binop_rule(t1,o2,t2,"__mod__","__rmod__","%");
}
/**
* Implements the Python expression <code>this % o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the mod.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_mod(PyObject o2) {
PyObject x=__mod__(o2);
if (x!=null) {
return x;
}
x=o2.__rmod__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("%",o2));
}
/**
* Implements the Python expression <code>this %= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the imod.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _imod(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_imod(o2);
}
PyObject impl=t1.lookup("__imod__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__mod__","__rmod__","%");
}
/**
* Implements the Python expression <code>this %= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the imod.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_imod(PyObject o2) {
PyObject x=__imod__(o2);
if (x!=null) {
return x;
}
return this._basic_mod(o2);
}
/**
* Equivalent to the standard Python __divmod__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the divmod, or null if this operation
* is not defined
**/
public PyObject __divmod__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rdivmod__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the divmod, or null if this operation
* is not defined.
**/
public PyObject __rdivmod__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __idivmod__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the idivmod, or null if this operation
* is not defined
**/
public PyObject __idivmod__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this divmod o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the divmod.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _divmod(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_divmod(o2);
}
return _binop_rule(t1,o2,t2,"__divmod__","__rdivmod__","divmod");
}
/**
* Implements the Python expression <code>this divmod o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the divmod.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_divmod(PyObject o2) {
PyObject x=__divmod__(o2);
if (x!=null) {
return x;
}
x=o2.__rdivmod__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("divmod",o2));
}
/**
* Implements the Python expression <code>this divmod= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the idivmod.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _idivmod(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_idivmod(o2);
}
PyObject impl=t1.lookup("__idivmod__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__divmod__","__rdivmod__","divmod");
}
/**
* Implements the Python expression <code>this divmod= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the idivmod.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_idivmod(PyObject o2) {
PyObject x=__idivmod__(o2);
if (x!=null) {
return x;
}
return this._basic_divmod(o2);
}
/**
* Equivalent to the standard Python __pow__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the pow, or null if this operation
* is not defined
**/
public PyObject __pow__(PyObject other) {
return __pow__(other,null);
}
/**
* Equivalent to the standard Python __rpow__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the pow, or null if this operation
* is not defined.
**/
public PyObject __rpow__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __ipow__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the ipow, or null if this operation
* is not defined
**/
public PyObject __ipow__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this ** o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the pow.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _pow(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_pow(o2);
}
return _binop_rule(t1,o2,t2,"__pow__","__rpow__","**");
}
/**
* Implements the Python expression <code>this ** o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the pow.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_pow(PyObject o2) {
PyObject x=__pow__(o2);
if (x!=null) {
return x;
}
x=o2.__rpow__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("**",o2));
}
/**
* Implements the Python expression <code>this **= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ipow.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _ipow(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_ipow(o2);
}
PyObject impl=t1.lookup("__ipow__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__pow__","__rpow__","**");
}
/**
* Implements the Python expression <code>this **= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ipow.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_ipow(PyObject o2) {
PyObject x=__ipow__(o2);
if (x!=null) {
return x;
}
return this._basic_pow(o2);
}
/**
* Equivalent to the standard Python __lshift__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the lshift, or null if this operation
* is not defined
**/
public PyObject __lshift__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rlshift__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the lshift, or null if this operation
* is not defined.
**/
public PyObject __rlshift__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __ilshift__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the ilshift, or null if this operation
* is not defined
**/
public PyObject __ilshift__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this << o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the lshift.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _lshift(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_lshift(o2);
}
return _binop_rule(t1,o2,t2,"__lshift__","__rlshift__","<<");
}
/**
* Implements the Python expression <code>this << o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the lshift.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_lshift(PyObject o2) {
PyObject x=__lshift__(o2);
if (x!=null) {
return x;
}
x=o2.__rlshift__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("<<",o2));
}
/**
* Implements the Python expression <code>this <<= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ilshift.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _ilshift(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_ilshift(o2);
}
PyObject impl=t1.lookup("__ilshift__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__lshift__","__rlshift__","<<");
}
/**
* Implements the Python expression <code>this <<= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ilshift.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_ilshift(PyObject o2) {
PyObject x=__ilshift__(o2);
if (x!=null) {
return x;
}
return this._basic_lshift(o2);
}
/**
* Equivalent to the standard Python __rshift__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the rshift, or null if this operation
* is not defined
**/
public PyObject __rshift__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rrshift__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the rshift, or null if this operation
* is not defined.
**/
public PyObject __rrshift__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __irshift__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the irshift, or null if this operation
* is not defined
**/
public PyObject __irshift__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this >> o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the rshift.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _rshift(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_rshift(o2);
}
return _binop_rule(t1,o2,t2,"__rshift__","__rrshift__",">>");
}
/**
* Implements the Python expression <code>this >> o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the rshift.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_rshift(PyObject o2) {
PyObject x=__rshift__(o2);
if (x!=null) {
return x;
}
x=o2.__rrshift__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop(">>",o2));
}
/**
* Implements the Python expression <code>this >>= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the irshift.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _irshift(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_irshift(o2);
}
PyObject impl=t1.lookup("__irshift__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__rshift__","__rrshift__",">>");
}
/**
* Implements the Python expression <code>this >>= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the irshift.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_irshift(PyObject o2) {
PyObject x=__irshift__(o2);
if (x!=null) {
return x;
}
return this._basic_rshift(o2);
}
/**
* Equivalent to the standard Python __and__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the and, or null if this operation
* is not defined
**/
public PyObject __and__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rand__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the and, or null if this operation
* is not defined.
**/
public PyObject __rand__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __iand__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the iand, or null if this operation
* is not defined
**/
public PyObject __iand__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this & o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the and.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _and(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_and(o2);
}
return _binop_rule(t1,o2,t2,"__and__","__rand__","&");
}
/**
* Implements the Python expression <code>this & o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the and.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_and(PyObject o2) {
PyObject x=__and__(o2);
if (x!=null) {
return x;
}
x=o2.__rand__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("&",o2));
}
/**
* Implements the Python expression <code>this &= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the iand.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _iand(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_iand(o2);
}
PyObject impl=t1.lookup("__iand__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__and__","__rand__","&");
}
/**
* Implements the Python expression <code>this &= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the iand.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_iand(PyObject o2) {
PyObject x=__iand__(o2);
if (x!=null) {
return x;
}
return this._basic_and(o2);
}
/**
* Equivalent to the standard Python __or__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the or, or null if this operation
* is not defined
**/
public PyObject __or__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __ror__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the or, or null if this operation
* is not defined.
**/
public PyObject __ror__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __ior__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the ior, or null if this operation
* is not defined
**/
public PyObject __ior__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this | o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the or.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _or(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_or(o2);
}
return _binop_rule(t1,o2,t2,"__or__","__ror__","|");
}
/**
* Implements the Python expression <code>this | o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the or.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_or(PyObject o2) {
PyObject x=__or__(o2);
if (x!=null) {
return x;
}
x=o2.__ror__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("|",o2));
}
/**
* Implements the Python expression <code>this |= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ior.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _ior(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_ior(o2);
}
PyObject impl=t1.lookup("__ior__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__or__","__ror__","|");
}
/**
* Implements the Python expression <code>this |= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ior.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_ior(PyObject o2) {
PyObject x=__ior__(o2);
if (x!=null) {
return x;
}
return this._basic_or(o2);
}
/**
* Equivalent to the standard Python __xor__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the xor, or null if this operation
* is not defined
**/
public PyObject __xor__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __rxor__ method
* @param other the object to perform this binary operation with
* (the left-hand operand).
* @return the result of the xor, or null if this operation
* is not defined.
**/
public PyObject __rxor__(PyObject other) {
return null;
}
/**
* Equivalent to the standard Python __ixor__ method
* @param other the object to perform this binary operation with
* (the right-hand operand).
* @return the result of the ixor, or null if this operation
* is not defined
**/
public PyObject __ixor__(PyObject other) {
return null;
}
/**
* Implements the Python expression <code>this ^ o2</code>
* @param o2 the object to perform this binary operation with.
* @return the result of the xor.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _xor(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_xor(o2);
}
return _binop_rule(t1,o2,t2,"__xor__","__rxor__","^");
}
/**
* Implements the Python expression <code>this ^ o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this binary operation with.
* @return the result of the xor.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_xor(PyObject o2) {
PyObject x=__xor__(o2);
if (x!=null) {
return x;
}
x=o2.__rxor__(this);
if (x!=null) {
return x;
}
throw Py.TypeError(_unsupportedop("^",o2));
}
/**
* Implements the Python expression <code>this ^= o2</code>
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ixor.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
public final PyObject _ixor(PyObject o2) {
PyType t1=this.getType();
PyType t2=o2.getType();
if (t1==t2||t1.builtin&&t2.builtin) {
return this._basic_ixor(o2);
}
PyObject impl=t1.lookup("__ixor__");
if (impl!=null) {
PyObject res=impl.__get__(this,t1).__call__(o2);
if (res!=Py.NotImplemented) {
return res;
}
}
return _binop_rule(t1,o2,t2,"__xor__","__rxor__","^");
}
/**
* Implements the Python expression <code>this ^= o2</code>
* when this and o2 have the same type or are builtin types.
* @param o2 the object to perform this inplace binary
* operation with.
* @return the result of the ixor.
* @exception Py.TypeError if this operation can't be performed
* with these operands.
**/
final PyObject _basic_ixor(PyObject o2) {
PyObject x=__ixor__(o2);
if (x!=null) {
return x;
}
return this._basic_xor(o2);
}
// Generated by make_binops.py (End)
/**
* A convenience function for PyProxys.
*/
public PyObject _jcallexc(Object[] args) throws Throwable {
PyObject[] pargs = new PyObject[args.length];
try {
for (int i = 0; i < args.length; i++) {
pargs[i] = Py.java2py(args[i]);
}
return __call__(pargs);
} catch (PyException e) {
if (e.value.getJavaProxy() != null) {
Object t = e.value.__tojava__(Throwable.class);
if (t != null && t != Py.NoConversion) {
throw (Throwable) t;
}
} else {
ThreadState ts = Py.getThreadState();
if (ts.frame == null) {
Py.maybeSystemExit(e);
}
if (Options.showPythonProxyExceptions) {
Py.stderr.println(
"Exception in Python proxy returning to Java:");
Py.printException(e);
}
}
throw e;
}
}
public void _jthrow(Throwable t) {
if (t instanceof RuntimeException)
throw (RuntimeException) t;
if (t instanceof Error)
throw (Error) t;
throw Py.JavaError(t);
}
public PyObject _jcall(Object[] args) {
try {
return _jcallexc(args);
} catch (Throwable t) {
_jthrow(t);
return null;
}
}
/* Shortcut methods for calling methods from Java */
/**
* Shortcut for calling a method on a PyObject from Java.
* This form is equivalent to o.__getattr__(name).__call__(args, keywords)
*
* @param name the name of the method to call. This must be an
* interned string!
* @param args an array of the arguments to the call.
* @param keywords the keywords to use in the call.
* @return the result of calling the method name with args and keywords.
**/
public PyObject invoke(String name, PyObject[] args, String[] keywords) {
PyObject f = __getattr__(name);
return f.__call__(args, keywords);
}
public PyObject invoke(String name, PyObject[] args) {
PyObject f = __getattr__(name);
return f.__call__(args);
}
/**
* Shortcut for calling a method on a PyObject with no args.
*
* @param name the name of the method to call. This must be an
* interned string!
* @return the result of calling the method name with no args
**/
public PyObject invoke(String name) {
PyObject f = __getattr__(name);
return f.__call__();
}
/**
* Shortcut for calling a method on a PyObject with one arg.
*
* @param name the name of the method to call. This must be an
* interned string!
* @param arg1 the one argument of the method.
* @return the result of calling the method name with arg1
**/
public PyObject invoke(String name, PyObject arg1) {
PyObject f = __getattr__(name);
return f.__call__(arg1);
}
/**
* Shortcut for calling a method on a PyObject with two args.
*
* @param name the name of the method to call. This must be an
* interned string!
* @param arg1 the first argument of the method.
* @param arg2 the second argument of the method.
* @return the result of calling the method name with arg1 and arg2
**/
public PyObject invoke(String name, PyObject arg1, PyObject arg2) {
PyObject f = __getattr__(name);
return f.__call__(arg1, arg2);
}
/**
* Shortcut for calling a method on a PyObject with one extra
* initial argument.
*
* @param name the name of the method to call. This must be an
* interned string!
* @param arg1 the first argument of the method.
* @param args an array of the arguments to the call.
* @param keywords the keywords to use in the call.
* @return the result of calling the method name with arg1 args
* and keywords
**/
public PyObject invoke(String name, PyObject arg1, PyObject[] args, String[] keywords) {
PyObject f = __getattr__(name);
return f.__call__(arg1, args, keywords);
}
/* descriptors and lookup protocols */
/** xxx implements where meaningful
* @return internal object per instance dict or null
*/
public PyObject fastGetDict() {
return null;
}
/** xxx implements where meaningful
* @return internal object __dict__ or null
*/
public PyObject getDict() {
return null;
}
public void setDict(PyObject newDict) {
// fallback if setDict not implemented in subclass
throw Py.TypeError("can't set attribute '__dict__' of instance of " + getType().fastGetName());
}
public void delDict() {
// fallback to error
throw Py.TypeError("can't delete attribute '__dict__' of instance of '" + getType().fastGetName()+ "'");
}
public boolean implementsDescrSet() {
return objtype.has_set;
}
public boolean implementsDescrDelete() {
return objtype.has_delete;
}
public boolean isDataDescr() { // implements either __set__ or __delete__
return objtype.has_set || objtype.has_delete;
}
// doc & xxx ok this way?
// can return null meaning set-only or throw exception
// backward comp impls.
/**
* Get descriptor for this PyObject.
*
* @param obj -
* the instance accessing this descriptor. Can be null if this is
* being accessed by a type.
* @param type -
* the type accessing this descriptor. Will be null if obj exists
* as obj is of the type accessing the descriptor.
* @return - the object defined for this descriptor for the given obj and
* type.
*/
public PyObject __get__(PyObject obj, PyObject type) {
return _doget(obj, type);
}
public void __set__(PyObject obj, PyObject value) {
if (!_doset(obj, value)) {
throw Py.AttributeError("object internal __set__ impl is abstract");
}
}
public void __delete__(PyObject obj) {
throw Py.AttributeError("object internal __delete__ impl is abstract");
}
@ExposedMethod(doc = BuiltinDocs.object___getattribute___doc)
final PyObject object___getattribute__(PyObject arg0) {
String name = asName(arg0);
PyObject ret = object___findattr__(name);
if(ret == null)
noAttributeError(name);
return ret;
}
// name must be interned
final PyObject object___findattr__(String name) {
PyObject descr = objtype.lookup(name);
PyObject res;
if (descr != null) {
if (descr.isDataDescr()) {
res = descr.__get__(this, objtype);
if (res != null)
return res;
}
}
PyObject obj_dict = fastGetDict();
if (obj_dict != null) {
res = obj_dict.__finditem__(name);
if (res != null)
return res;
}
if (descr != null) {
return descr.__get__(this, objtype);
}
return null;
}
@ExposedMethod(doc = BuiltinDocs.object___setattr___doc)
final void object___setattr__(PyObject name, PyObject value) {
hackCheck("__setattr__");
object___setattr__(asName(name), value);
}
final void object___setattr__(String name, PyObject value) {
PyObject descr = objtype.lookup(name);
boolean set = false;
if (descr != null) {
set = descr.implementsDescrSet();
if (set && descr.isDataDescr()) {
descr.__set__(this, value);
return;
}
}
PyObject obj_dict = fastGetDict();
if (obj_dict != null) {
obj_dict.__setitem__(name, value);
return;
}
if (set) {
descr.__set__(this, value);
}
if (descr != null) {
readonlyAttributeError(name);
}
noAttributeError(name);
}
@ExposedMethod(doc = BuiltinDocs.object___delattr___doc)
final void object___delattr__(PyObject name) {
hackCheck("__delattr__");
object___delattr__(asName(name));
}
public static final String asName(PyObject obj) {
try {
return obj.asName(0);
} catch(PyObject.ConversionException e) {
throw Py.TypeError("attribute name must be a string");
}
}
final void object___delattr__(String name) {
PyObject descr = objtype.lookup(name);
boolean delete = false;
if (descr != null) {
delete = descr.implementsDescrDelete();
if (delete && descr.isDataDescr()) {
descr.__delete__(this);
return;
}
}
PyObject obj_dict = fastGetDict();
if (obj_dict != null) {
try {
obj_dict.__delitem__(name);
} catch (PyException exc) {
if (Py.matchException(exc, Py.KeyError))
noAttributeError(name);
else
throw exc;
}
return;
}
if (delete) {
descr.__delete__(this);
}
if (descr != null) {
readonlyAttributeError(name);
}
noAttributeError(name);
}
/**
* Helper to check for object.__setattr__ or __delattr__ applied to a type (The Carlo
* Verre hack).
*
* @param what String method name to check for
*/
private void hackCheck(String what) {
if (this instanceof PyType && ((PyType)this).builtin) {
throw Py.TypeError(String.format("can't apply this %s to %s object", what,
objtype.fastGetName()));
}
}
/**
* Used for pickling. Default implementation calls object___reduce__.
*
* @return a tuple of (class, tuple)
*/
public PyObject __reduce__() {
return object___reduce__();
}
@ExposedMethod(doc = BuiltinDocs.object___reduce___doc)
final PyObject object___reduce__() {
return object___reduce_ex__(0);
}
/** Used for pickling. If the subclass specifies __reduce__, it will
* override __reduce_ex__ in the base-class, even if __reduce_ex__ was
* called with an argument.
*
* @param arg PyInteger specifying reduce algorithm (method without this
* argument defaults to 0).
* @return a tuple of (class, tuple)
*/
public PyObject __reduce_ex__(int arg) {
return object___reduce_ex__(arg);
}
public PyObject __reduce_ex__() {
return object___reduce_ex__(0);
}
@ExposedMethod(defaults = "0", doc = BuiltinDocs.object___reduce___doc)
final PyObject object___reduce_ex__(int arg) {
PyObject res;
PyObject clsreduce = this.getType().__findattr__("__reduce__");
PyObject objreduce = (new PyObject()).getType().__findattr__("__reduce__");
if (clsreduce != objreduce) {
res = this.__reduce__();
} else if (arg >= 2) {
res = reduce_2();
} else {
PyObject copyreg = __builtin__.__import__("copy_reg", null, null, Py.EmptyTuple);
PyObject copyreg_reduce = copyreg.__findattr__("_reduce_ex");
res = copyreg_reduce.__call__(this, new PyInteger(arg));
}
return res;
}
private static PyObject slotnames(PyObject cls) {
PyObject slotnames;
slotnames = cls.fastGetDict().__finditem__("__slotnames__");
if (null != slotnames) {
return slotnames;
}
PyObject copyreg = __builtin__.__import__("copy_reg", null, null, Py.EmptyTuple);
PyObject copyreg_slotnames = copyreg.__findattr__("_slotnames");
slotnames = copyreg_slotnames.__call__(cls);
if (null != slotnames && Py.None != slotnames && (!(slotnames instanceof PyList))) {
throw Py.TypeError("copy_reg._slotnames didn't return a list or None");
}
return slotnames;
}
private PyObject reduce_2() {
PyObject args, state;
PyObject res = null;
int n,i;
PyObject cls = this.__findattr__("__class__");
PyObject getnewargs = this.__findattr__("__getnewargs__");
if (null != getnewargs) {
args = getnewargs.__call__();
if (null != args && !(args instanceof PyTuple)) {
throw Py.TypeError("__getnewargs__ should return a tuple");
}
} else {
args = Py.EmptyTuple;
}
PyObject getstate = this.__findattr__("__getstate__");
if (null != getstate) {
state = getstate.__call__();
if (null == state) {
return res;
}
} else {
state = this.__findattr__("__dict__");
if (null == state) {
state = Py.None;
}
PyObject names = slotnames(cls);
if (null == names) {
return res;
}
if (names != Py.None) {
if (!(names instanceof PyList)) {
throw Py.AssertionError("slots not a list");
}
PyObject slots = new PyDictionary();
n = 0;
for (i = 0; i < ((PyList)names).size(); i++) {
PyObject name = ((PyList)names).pyget(i);
PyObject value = this.__findattr__(name.toString());
if (null == value) {
// do nothing
} else {
slots.__setitem__(name, value);
n++;
}
}
if (n > 0) {
state = new PyTuple(state, slots);
}
}
}
PyObject listitems;
PyObject dictitems;
if (!(this instanceof PyList)) {
listitems = Py.None;
} else {
listitems = ((PyList)this).__iter__();
}
if (!(this instanceof PyDictionary)) {
dictitems = Py.None;
} else {
- dictitems = ((PyDictionary)this).iteritems();
+ dictitems = invoke("iteritems");
}
PyObject copyreg = __builtin__.__import__("copy_reg", null, null, Py.EmptyTuple);
PyObject newobj = copyreg.__findattr__("__newobj__");
n = ((PyTuple)args).size();
PyObject args2[] = new PyObject[n+1];
args2[0] = cls;
for(i = 0; i < n; i++) {
args2[i+1] = ((PyTuple)args).pyget(i);
}
return new PyTuple(newobj, new PyTuple(args2), state, listitems, dictitems);
}
public PyTuple __getnewargs__() {
//default is empty tuple
return new PyTuple();
}
/* arguments' conversion helpers */
public static class ConversionException extends Exception {
public int index;
public ConversionException(int index) {
this.index = index;
}
}
public String asString(int index) throws ConversionException {
throw new ConversionException(index);
}
public String asString(){
throw Py.TypeError("expected a str");
}
public String asStringOrNull(int index) throws ConversionException {
return asString(index);
}
public String asStringOrNull(){
return asString();
}
// TODO - remove when all asName users are moved to the @Exposed annotation
public String asName(int index) throws ConversionException {
throw new ConversionException(index);
}
// TODO - remove when all generated users are migrated to @Exposed and asInt()
public int asInt(int index) throws ConversionException {
throw new ConversionException(index);
}
public int asInt() {
PyObject intObj;
try {
intObj = __int__();
} catch (PyException pye) {
if (Py.matchException(pye, Py.AttributeError)) {
throw Py.TypeError("an integer is required");
}
throw pye;
}
if (!(intObj instanceof PyInteger) && !(intObj instanceof PyLong)) {
// Shouldn't happen except with buggy builtin types
throw Py.TypeError("nb_int should return int object");
}
return intObj.asInt();
}
public long asLong(int index) throws ConversionException {
throw new ConversionException(index);
}
/**
* Convert this object into a double. Throws a PyException on failure.
*
* @return a double value
*/
public double asDouble() {
PyFloat floatObj;
try {
floatObj = __float__();
} catch (PyException pye) {
if (Py.matchException(pye, Py.AttributeError)) {
throw Py.TypeError("a float is required");
}
throw pye;
}
return floatObj.asDouble();
}
/**
* Convert this object into an index-sized integer. Throws a PyException on failure.
*
* @return an index-sized int
*/
public int asIndex() {
return asIndex(null);
}
/**
* Convert this object into an index-sized integer.
*
* Throws a Python exception on Overflow if specified an exception type for err.
*
* @param err the Python exception to raise on OverflowErrors
* @return an index-sized int
*/
public int asIndex(PyObject err) {
// OverflowErrors are handled in PyLong.asIndex
return __index__().asInt();
}
static {
for (Class<?> unbootstrapped : Py.BOOTSTRAP_TYPES) {
Py.writeWarning("init", "Bootstrap type wasn't encountered in bootstrapping[class="
+ unbootstrapped + "]");
}
}
}
/*
* A very specialized tuple-like class used when detecting cycles during
* object comparisons. This classes is different from an normal tuple
* by hashing and comparing its elements by identity.
*/
class PyIdentityTuple extends PyObject {
PyObject[] list;
public PyIdentityTuple(PyObject elements[]) {
list = elements;
}
public int hashCode() {
int x, y;
int len = list.length;
x = 0x345678;
for (len--; len >= 0; len--) {
y = System.identityHashCode(list[len]);
x = (x + x + x) ^ y;
}
x ^= list.length;
return x;
}
public boolean equals(Object o) {
if (!(o instanceof PyIdentityTuple))
return false;
PyIdentityTuple that = (PyIdentityTuple) o;
if (list.length != that.list.length)
return false;
for (int i = 0; i < list.length; i++) {
if (list[i] != that.list[i])
return false;
}
return true;
}
}
| true | true | private PyObject reduce_2() {
PyObject args, state;
PyObject res = null;
int n,i;
PyObject cls = this.__findattr__("__class__");
PyObject getnewargs = this.__findattr__("__getnewargs__");
if (null != getnewargs) {
args = getnewargs.__call__();
if (null != args && !(args instanceof PyTuple)) {
throw Py.TypeError("__getnewargs__ should return a tuple");
}
} else {
args = Py.EmptyTuple;
}
PyObject getstate = this.__findattr__("__getstate__");
if (null != getstate) {
state = getstate.__call__();
if (null == state) {
return res;
}
} else {
state = this.__findattr__("__dict__");
if (null == state) {
state = Py.None;
}
PyObject names = slotnames(cls);
if (null == names) {
return res;
}
if (names != Py.None) {
if (!(names instanceof PyList)) {
throw Py.AssertionError("slots not a list");
}
PyObject slots = new PyDictionary();
n = 0;
for (i = 0; i < ((PyList)names).size(); i++) {
PyObject name = ((PyList)names).pyget(i);
PyObject value = this.__findattr__(name.toString());
if (null == value) {
// do nothing
} else {
slots.__setitem__(name, value);
n++;
}
}
if (n > 0) {
state = new PyTuple(state, slots);
}
}
}
PyObject listitems;
PyObject dictitems;
if (!(this instanceof PyList)) {
listitems = Py.None;
} else {
listitems = ((PyList)this).__iter__();
}
if (!(this instanceof PyDictionary)) {
dictitems = Py.None;
} else {
dictitems = ((PyDictionary)this).iteritems();
}
PyObject copyreg = __builtin__.__import__("copy_reg", null, null, Py.EmptyTuple);
PyObject newobj = copyreg.__findattr__("__newobj__");
n = ((PyTuple)args).size();
PyObject args2[] = new PyObject[n+1];
args2[0] = cls;
for(i = 0; i < n; i++) {
args2[i+1] = ((PyTuple)args).pyget(i);
}
return new PyTuple(newobj, new PyTuple(args2), state, listitems, dictitems);
}
| private PyObject reduce_2() {
PyObject args, state;
PyObject res = null;
int n,i;
PyObject cls = this.__findattr__("__class__");
PyObject getnewargs = this.__findattr__("__getnewargs__");
if (null != getnewargs) {
args = getnewargs.__call__();
if (null != args && !(args instanceof PyTuple)) {
throw Py.TypeError("__getnewargs__ should return a tuple");
}
} else {
args = Py.EmptyTuple;
}
PyObject getstate = this.__findattr__("__getstate__");
if (null != getstate) {
state = getstate.__call__();
if (null == state) {
return res;
}
} else {
state = this.__findattr__("__dict__");
if (null == state) {
state = Py.None;
}
PyObject names = slotnames(cls);
if (null == names) {
return res;
}
if (names != Py.None) {
if (!(names instanceof PyList)) {
throw Py.AssertionError("slots not a list");
}
PyObject slots = new PyDictionary();
n = 0;
for (i = 0; i < ((PyList)names).size(); i++) {
PyObject name = ((PyList)names).pyget(i);
PyObject value = this.__findattr__(name.toString());
if (null == value) {
// do nothing
} else {
slots.__setitem__(name, value);
n++;
}
}
if (n > 0) {
state = new PyTuple(state, slots);
}
}
}
PyObject listitems;
PyObject dictitems;
if (!(this instanceof PyList)) {
listitems = Py.None;
} else {
listitems = ((PyList)this).__iter__();
}
if (!(this instanceof PyDictionary)) {
dictitems = Py.None;
} else {
dictitems = invoke("iteritems");
}
PyObject copyreg = __builtin__.__import__("copy_reg", null, null, Py.EmptyTuple);
PyObject newobj = copyreg.__findattr__("__newobj__");
n = ((PyTuple)args).size();
PyObject args2[] = new PyObject[n+1];
args2[0] = cls;
for(i = 0; i < n; i++) {
args2[i+1] = ((PyTuple)args).pyget(i);
}
return new PyTuple(newobj, new PyTuple(args2), state, listitems, dictitems);
}
|
diff --git a/ServerAPP/src/Actions/CreateGame.java b/ServerAPP/src/Actions/CreateGame.java
index 037bc96..7bdd97b 100644
--- a/ServerAPP/src/Actions/CreateGame.java
+++ b/ServerAPP/src/Actions/CreateGame.java
@@ -1,293 +1,293 @@
package Actions;
import java.io.*;
import java.sql.*;
import java.util.logging.Logger;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import javax.sql.DataSource;
@WebServlet(urlPatterns={"/CreateGame"})
//Note: This takes in a UserID. It can be changed to take a Username
// just add the following lines of code to query and get the UserID.
//
// Resultset rs5;
// Statement stmt5;
//
// stmt5 = connection.createStatement();
// //Query to get User�s friend ID
// rs5 = stmt.executeQuery("SELECT UserID FROM tblUsers WHERE Username = '" + User + "';");
// if(rs5.next())
// }
// UserID = rs.getInt(1);
// }
public class CreateGame extends HttpServlet implements DataSource {
private String User = null;
private String PlayerHand = null;
private int UserID, GameID;
private int rounds = -1;
//private String qryRandomDeck = "SELECT CardID FROM tblCards WHERE CardType = 1 ORDER BY RAND() LIMIT 60;";
private String GameDeck = null;
private String BlackCards = null;
Connection connection = null;
public String getUser() {
return User;
}
public void setUser(String user) {
User = user;
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("User") != null){
this.setUser((String) request.getParameter("User").toString());
UserID = Integer.parseInt(User);
}
if(request.getParameter("rounds") != null){
this.setRounds(Integer.parseInt((String) request.getParameter("rounds").toString()));
}
PrintWriter out = response.getWriter();
try {
System.out.println("Loading driver...");
Class.forName("com.mysql.jdbc.Driver");
//Check if user exists in database
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
CreateGame ds = new CreateGame();
try {
connection = ds.getConnection();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(User!= null){
Statement stmt, stmt2, stmt3, stmt4, stmt5;
ResultSet rs,rs4, rs5;
int rs2, rs3;
try {
stmt = connection.createStatement();
stmt2 = connection.createStatement();
stmt3 = connection.createStatement();
stmt4 = connection.createStatement();
stmt5 = connection.createStatement();
// get random deck of 60 cards
rs = stmt.executeQuery("SELECT CardID FROM tblCards WHERE CardType = 1 ORDER BY RAND() LIMIT 60;");
//rs5.next();
//out.print("First Card: " + rs5.getInt(1));
// comma separate 60 cards
if(!rs.isBeforeFirst()){
//No cards in query
}
else{
GameDeck = "";
//Create comma separated string with card deck
//out.println("Before Deck: "+ GameDeck);
while(rs.next()){
GameDeck = GameDeck + rs.getInt(1) + ";";
}
//strip last comma off of game deck
if(GameDeck.endsWith(";")){
GameDeck = GameDeck.substring(0, GameDeck.length()-1);
}
//System.out.println("Game Deck: " + GameDeck);
//out.println("After Deck: "+ GameDeck);
//out.println("Deck Created");
}
//Code to grab first 5 from gameDeck - rebuild game deck and UserHand
String UserHand = "";
String[] Temp = GameDeck.split(";");
GameDeck = "";
for(int i = 0; i<(Temp.length); i++){
if(i<=4){
UserHand = UserHand + Temp[i] + ";";
}
else{
GameDeck = GameDeck + Temp[i] + ";";
}
}
if(GameDeck.endsWith(";")){
GameDeck = GameDeck.substring(0, GameDeck.length()-1);
}
if(UserHand.endsWith(";")){
UserHand = UserHand.substring(0, UserHand.length()-1);
}
//out.println(UserHand);
//out.println(GameDeck);
// Get 5 random black CardIDs
rs5 = stmt5.executeQuery("SELECT CardID FROM tblCards WHERE CardType = 0 ORDER BY RAND() LIMIT 5;");
if(rs5.isBeforeFirst())
{
BlackCards = "";
//Create string for black card IDs
while(rs5.next())
{
BlackCards = BlackCards + rs5.getInt(1) + ";";
}
// Strip last comma off of game deck
if(BlackCards.endsWith(";"))
{
BlackCards = BlackCards.substring(0, BlackCards.length()-1);
}
}
//out.println(BlackCards);
//out.print("Before Game creation");
//Create game record
//System.out.println("INSERT INTO tblGames (GameRounds, GameJudge, GameCurRound, GameDeck) VALUES (" + rounds + "," + UserID +"," + 0 + ",'"+ GameDeck +"');");
rs2 = stmt2.executeUpdate("INSERT INTO tblGames (GameRounds, GameJudge, GameCurRound, GameDeck, GameBlackCards) VALUES (" + rounds + "," + UserID +"," + 0 + ",'"+ GameDeck +"','"+ BlackCards +"');");
System.out.println(rs2);
if(rs2!=0){
- out.println("Game Created!\n");
+ //out.println("Game Created!\n");
}
else{
out.println("Unable to create game!");
return;
}
//Get game ID
rs4 = stmt4.executeQuery("SELECT * FROM tblGames ORDER BY GameID DESC LIMIT 1;");
//Ensure record set has record
if(rs4.next()){
//out.print("Success "+ rs4.getInt(1) +"\n");
GameID = rs4.getInt(1);
}
//Add user that created game into players table -- 'tblPlayers'
rs3 = stmt3.executeUpdate("INSERT INTO tblPlayers (PlayerGameID, PlayerUserID, PlayerStatus, PlayerHand) VALUES (" + GameID + "," + UserID +",1,'"+ UserHand +"');");
System.out.println(rs3);
if(rs3!=0){
out.println("Game:"+ GameID);
}
else{
out.println("Unable to add user to game!");
}
//Close record sets and connection
rs.close();
rs4.close();
rs5.close();
stmt5.close();
stmt.close();
stmt2.close();
stmt3.close();
stmt4.close();
connection.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
@Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub
}
@Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
}
@Override
public Connection getConnection() throws SQLException {
if (connection != null) {
System.out.println("Cant craete a Connection");
} else {
connection = DriverManager.getConnection(
"jdbc:mysql://ourdbinstance.cbvrc3frdaal.us-east-1.rds.amazonaws.com:3306/dbAppData", "AWSCards", "Cards9876");
}
return connection;
}
@Override
public Connection getConnection(String username, String password)
throws SQLException {
// TODO Auto-generated method stub
if (connection != null) {
System.out.println("Cant create a Connection");
} else {
connection = DriverManager.getConnection(
"jdbc:mysql://ourdbinstance.cbvrc3frdaal.us-east-1.rds.amazonaws.com:3306/dbAppData", username, password);
}
return connection;
}
public int getRounds() {
return rounds;
}
public void setRounds(int rounds) {
this.rounds = rounds;
}
}
| true | true | public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("User") != null){
this.setUser((String) request.getParameter("User").toString());
UserID = Integer.parseInt(User);
}
if(request.getParameter("rounds") != null){
this.setRounds(Integer.parseInt((String) request.getParameter("rounds").toString()));
}
PrintWriter out = response.getWriter();
try {
System.out.println("Loading driver...");
Class.forName("com.mysql.jdbc.Driver");
//Check if user exists in database
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
CreateGame ds = new CreateGame();
try {
connection = ds.getConnection();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(User!= null){
Statement stmt, stmt2, stmt3, stmt4, stmt5;
ResultSet rs,rs4, rs5;
int rs2, rs3;
try {
stmt = connection.createStatement();
stmt2 = connection.createStatement();
stmt3 = connection.createStatement();
stmt4 = connection.createStatement();
stmt5 = connection.createStatement();
// get random deck of 60 cards
rs = stmt.executeQuery("SELECT CardID FROM tblCards WHERE CardType = 1 ORDER BY RAND() LIMIT 60;");
//rs5.next();
//out.print("First Card: " + rs5.getInt(1));
// comma separate 60 cards
if(!rs.isBeforeFirst()){
//No cards in query
}
else{
GameDeck = "";
//Create comma separated string with card deck
//out.println("Before Deck: "+ GameDeck);
while(rs.next()){
GameDeck = GameDeck + rs.getInt(1) + ";";
}
//strip last comma off of game deck
if(GameDeck.endsWith(";")){
GameDeck = GameDeck.substring(0, GameDeck.length()-1);
}
//System.out.println("Game Deck: " + GameDeck);
//out.println("After Deck: "+ GameDeck);
//out.println("Deck Created");
}
//Code to grab first 5 from gameDeck - rebuild game deck and UserHand
String UserHand = "";
String[] Temp = GameDeck.split(";");
GameDeck = "";
for(int i = 0; i<(Temp.length); i++){
if(i<=4){
UserHand = UserHand + Temp[i] + ";";
}
else{
GameDeck = GameDeck + Temp[i] + ";";
}
}
if(GameDeck.endsWith(";")){
GameDeck = GameDeck.substring(0, GameDeck.length()-1);
}
if(UserHand.endsWith(";")){
UserHand = UserHand.substring(0, UserHand.length()-1);
}
//out.println(UserHand);
//out.println(GameDeck);
// Get 5 random black CardIDs
rs5 = stmt5.executeQuery("SELECT CardID FROM tblCards WHERE CardType = 0 ORDER BY RAND() LIMIT 5;");
if(rs5.isBeforeFirst())
{
BlackCards = "";
//Create string for black card IDs
while(rs5.next())
{
BlackCards = BlackCards + rs5.getInt(1) + ";";
}
// Strip last comma off of game deck
if(BlackCards.endsWith(";"))
{
BlackCards = BlackCards.substring(0, BlackCards.length()-1);
}
}
//out.println(BlackCards);
//out.print("Before Game creation");
//Create game record
//System.out.println("INSERT INTO tblGames (GameRounds, GameJudge, GameCurRound, GameDeck) VALUES (" + rounds + "," + UserID +"," + 0 + ",'"+ GameDeck +"');");
rs2 = stmt2.executeUpdate("INSERT INTO tblGames (GameRounds, GameJudge, GameCurRound, GameDeck, GameBlackCards) VALUES (" + rounds + "," + UserID +"," + 0 + ",'"+ GameDeck +"','"+ BlackCards +"');");
System.out.println(rs2);
if(rs2!=0){
out.println("Game Created!\n");
}
else{
out.println("Unable to create game!");
return;
}
//Get game ID
rs4 = stmt4.executeQuery("SELECT * FROM tblGames ORDER BY GameID DESC LIMIT 1;");
//Ensure record set has record
if(rs4.next()){
//out.print("Success "+ rs4.getInt(1) +"\n");
GameID = rs4.getInt(1);
}
//Add user that created game into players table -- 'tblPlayers'
rs3 = stmt3.executeUpdate("INSERT INTO tblPlayers (PlayerGameID, PlayerUserID, PlayerStatus, PlayerHand) VALUES (" + GameID + "," + UserID +",1,'"+ UserHand +"');");
System.out.println(rs3);
if(rs3!=0){
out.println("Game:"+ GameID);
}
else{
out.println("Unable to add user to game!");
}
//Close record sets and connection
rs.close();
rs4.close();
rs5.close();
stmt5.close();
stmt.close();
stmt2.close();
stmt3.close();
stmt4.close();
connection.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
| public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("User") != null){
this.setUser((String) request.getParameter("User").toString());
UserID = Integer.parseInt(User);
}
if(request.getParameter("rounds") != null){
this.setRounds(Integer.parseInt((String) request.getParameter("rounds").toString()));
}
PrintWriter out = response.getWriter();
try {
System.out.println("Loading driver...");
Class.forName("com.mysql.jdbc.Driver");
//Check if user exists in database
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
CreateGame ds = new CreateGame();
try {
connection = ds.getConnection();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(User!= null){
Statement stmt, stmt2, stmt3, stmt4, stmt5;
ResultSet rs,rs4, rs5;
int rs2, rs3;
try {
stmt = connection.createStatement();
stmt2 = connection.createStatement();
stmt3 = connection.createStatement();
stmt4 = connection.createStatement();
stmt5 = connection.createStatement();
// get random deck of 60 cards
rs = stmt.executeQuery("SELECT CardID FROM tblCards WHERE CardType = 1 ORDER BY RAND() LIMIT 60;");
//rs5.next();
//out.print("First Card: " + rs5.getInt(1));
// comma separate 60 cards
if(!rs.isBeforeFirst()){
//No cards in query
}
else{
GameDeck = "";
//Create comma separated string with card deck
//out.println("Before Deck: "+ GameDeck);
while(rs.next()){
GameDeck = GameDeck + rs.getInt(1) + ";";
}
//strip last comma off of game deck
if(GameDeck.endsWith(";")){
GameDeck = GameDeck.substring(0, GameDeck.length()-1);
}
//System.out.println("Game Deck: " + GameDeck);
//out.println("After Deck: "+ GameDeck);
//out.println("Deck Created");
}
//Code to grab first 5 from gameDeck - rebuild game deck and UserHand
String UserHand = "";
String[] Temp = GameDeck.split(";");
GameDeck = "";
for(int i = 0; i<(Temp.length); i++){
if(i<=4){
UserHand = UserHand + Temp[i] + ";";
}
else{
GameDeck = GameDeck + Temp[i] + ";";
}
}
if(GameDeck.endsWith(";")){
GameDeck = GameDeck.substring(0, GameDeck.length()-1);
}
if(UserHand.endsWith(";")){
UserHand = UserHand.substring(0, UserHand.length()-1);
}
//out.println(UserHand);
//out.println(GameDeck);
// Get 5 random black CardIDs
rs5 = stmt5.executeQuery("SELECT CardID FROM tblCards WHERE CardType = 0 ORDER BY RAND() LIMIT 5;");
if(rs5.isBeforeFirst())
{
BlackCards = "";
//Create string for black card IDs
while(rs5.next())
{
BlackCards = BlackCards + rs5.getInt(1) + ";";
}
// Strip last comma off of game deck
if(BlackCards.endsWith(";"))
{
BlackCards = BlackCards.substring(0, BlackCards.length()-1);
}
}
//out.println(BlackCards);
//out.print("Before Game creation");
//Create game record
//System.out.println("INSERT INTO tblGames (GameRounds, GameJudge, GameCurRound, GameDeck) VALUES (" + rounds + "," + UserID +"," + 0 + ",'"+ GameDeck +"');");
rs2 = stmt2.executeUpdate("INSERT INTO tblGames (GameRounds, GameJudge, GameCurRound, GameDeck, GameBlackCards) VALUES (" + rounds + "," + UserID +"," + 0 + ",'"+ GameDeck +"','"+ BlackCards +"');");
System.out.println(rs2);
if(rs2!=0){
//out.println("Game Created!\n");
}
else{
out.println("Unable to create game!");
return;
}
//Get game ID
rs4 = stmt4.executeQuery("SELECT * FROM tblGames ORDER BY GameID DESC LIMIT 1;");
//Ensure record set has record
if(rs4.next()){
//out.print("Success "+ rs4.getInt(1) +"\n");
GameID = rs4.getInt(1);
}
//Add user that created game into players table -- 'tblPlayers'
rs3 = stmt3.executeUpdate("INSERT INTO tblPlayers (PlayerGameID, PlayerUserID, PlayerStatus, PlayerHand) VALUES (" + GameID + "," + UserID +",1,'"+ UserHand +"');");
System.out.println(rs3);
if(rs3!=0){
out.println("Game:"+ GameID);
}
else{
out.println("Unable to add user to game!");
}
//Close record sets and connection
rs.close();
rs4.close();
rs5.close();
stmt5.close();
stmt.close();
stmt2.close();
stmt3.close();
stmt4.close();
connection.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
|
diff --git a/src/com/endlessloopsoftware/ego/client/statistics/models/InterviewSummaryModel.java b/src/com/endlessloopsoftware/ego/client/statistics/models/InterviewSummaryModel.java
index 8daf155..897c0ef 100644
--- a/src/com/endlessloopsoftware/ego/client/statistics/models/InterviewSummaryModel.java
+++ b/src/com/endlessloopsoftware/ego/client/statistics/models/InterviewSummaryModel.java
@@ -1,128 +1,128 @@
/***
* Copyright (c) 2008, Endless Loop Software, Inc.
*
* This file is part of EgoNet.
*
* EgoNet 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.
*
* EgoNet 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 com.endlessloopsoftware.ego.client.statistics.models;
import javax.swing.JTable;
import com.endlessloopsoftware.ego.client.statistics.Statistics;
public class InterviewSummaryModel extends StatTableModel
{
public InterviewSummaryModel(Statistics stats)
{
super(stats);
}
public int getColumnCount()
{
if (stats.adjacencyMatrix.length > 0)
{
return 3;
}
else
{
return 1;
}
}
public Object getValueAt(int rowIndex, int columnIndex)
{
switch (columnIndex)
{
case 0 :
switch (rowIndex)
{
case 0 :
return ("Degree Centrality Maximum");
case 1 :
- return ("Closeness Centrality Minimum");
+ return ("Closeness Centrality Maximum");
case 2 :
return ("Betweenness Centrality Maximum");
case 3 :
return ("Number of Cliques");
case 4 :
return ("Number of Components");
default :
return (null);
}
case 1 :
switch (rowIndex)
{
case 0 :
return (stats.mostCentralDegreeAlterName);
case 1 :
return (stats.mostCentralClosenessAlterName);
case 2 :
return (stats.mostCentralBetweenAlterName);
case 3 :
return (new Integer(stats.cliqueSet.size()));
case 4 :
return (new Integer(stats.componentSet.size()));
default :
return (null);
}
case 2 :
switch (rowIndex)
{
case 0 :
return (new Integer(stats.mostCentralDegreeAlterValue));
case 1 :
return (new Float(stats.mostCentralClosenessAlterValue));
case 2 :
return (new Float(stats.mostCentralBetweenAlterValue));
default :
return (null);
}
default :
return (null);
}
}
public int getRowCount()
{
if (stats.adjacencyMatrix.length > 0)
{
return 5;
}
else
{
return 0;
}
}
public String getColumnName(int column)
{
if (stats.adjacencyMatrix.length > 0)
{
return null;
}
else
{
return ("No Structural Measures question specified in study");
}
}
public int getResizeMode()
{
return JTable.AUTO_RESIZE_ALL_COLUMNS;
}
}
| true | true | public Object getValueAt(int rowIndex, int columnIndex)
{
switch (columnIndex)
{
case 0 :
switch (rowIndex)
{
case 0 :
return ("Degree Centrality Maximum");
case 1 :
return ("Closeness Centrality Minimum");
case 2 :
return ("Betweenness Centrality Maximum");
case 3 :
return ("Number of Cliques");
case 4 :
return ("Number of Components");
default :
return (null);
}
case 1 :
switch (rowIndex)
{
case 0 :
return (stats.mostCentralDegreeAlterName);
case 1 :
return (stats.mostCentralClosenessAlterName);
case 2 :
return (stats.mostCentralBetweenAlterName);
case 3 :
return (new Integer(stats.cliqueSet.size()));
case 4 :
return (new Integer(stats.componentSet.size()));
default :
return (null);
}
case 2 :
switch (rowIndex)
{
case 0 :
return (new Integer(stats.mostCentralDegreeAlterValue));
case 1 :
return (new Float(stats.mostCentralClosenessAlterValue));
case 2 :
return (new Float(stats.mostCentralBetweenAlterValue));
default :
return (null);
}
default :
return (null);
}
}
| public Object getValueAt(int rowIndex, int columnIndex)
{
switch (columnIndex)
{
case 0 :
switch (rowIndex)
{
case 0 :
return ("Degree Centrality Maximum");
case 1 :
return ("Closeness Centrality Maximum");
case 2 :
return ("Betweenness Centrality Maximum");
case 3 :
return ("Number of Cliques");
case 4 :
return ("Number of Components");
default :
return (null);
}
case 1 :
switch (rowIndex)
{
case 0 :
return (stats.mostCentralDegreeAlterName);
case 1 :
return (stats.mostCentralClosenessAlterName);
case 2 :
return (stats.mostCentralBetweenAlterName);
case 3 :
return (new Integer(stats.cliqueSet.size()));
case 4 :
return (new Integer(stats.componentSet.size()));
default :
return (null);
}
case 2 :
switch (rowIndex)
{
case 0 :
return (new Integer(stats.mostCentralDegreeAlterValue));
case 1 :
return (new Float(stats.mostCentralClosenessAlterValue));
case 2 :
return (new Float(stats.mostCentralBetweenAlterValue));
default :
return (null);
}
default :
return (null);
}
}
|
diff --git a/modules/analysis/common/src/java/org/apache/lucene/analysis/id/IndonesianAnalyzer.java b/modules/analysis/common/src/java/org/apache/lucene/analysis/id/IndonesianAnalyzer.java
index e4b78e8a6..210f9ae4d 100644
--- a/modules/analysis/common/src/java/org/apache/lucene/analysis/id/IndonesianAnalyzer.java
+++ b/modules/analysis/common/src/java/org/apache/lucene/analysis/id/IndonesianAnalyzer.java
@@ -1,130 +1,130 @@
package org.apache.lucene.analysis.id;
/**
* 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.
*/
import java.io.IOException;
import java.io.Reader;
import java.util.Set;
import org.apache.lucene.analysis.core.LowerCaseFilter;
import org.apache.lucene.analysis.core.StopFilter;
import org.apache.lucene.analysis.miscellaneous.KeywordMarkerFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.standard.StandardFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.analysis.util.StopwordAnalyzerBase;
import org.apache.lucene.util.Version;
/**
* Analyzer for Indonesian (Bahasa)
*/
public final class IndonesianAnalyzer extends StopwordAnalyzerBase {
/** File containing default Indonesian stopwords. */
public final static String DEFAULT_STOPWORD_FILE = "stopwords.txt";
/**
* Returns an unmodifiable instance of the default stop-words set.
* @return an unmodifiable instance of the default stop-words set.
*/
public static Set<?> getDefaultStopSet(){
return DefaultSetHolder.DEFAULT_STOP_SET;
}
/**
* Atomically loads the DEFAULT_STOP_SET in a lazy fashion once the outer class
* accesses the static final set the first time.;
*/
private static class DefaultSetHolder {
static final Set<?> DEFAULT_STOP_SET;
static {
try {
DEFAULT_STOP_SET = loadStopwordSet(false, IndonesianAnalyzer.class, DEFAULT_STOPWORD_FILE, "#");
} catch (IOException ex) {
// default set should always be present as it is part of the
// distribution (JAR)
throw new RuntimeException("Unable to load default stopword set");
}
}
}
private final Set<?> stemExclusionSet;
/**
* Builds an analyzer with the default stop words: {@link #DEFAULT_STOPWORD_FILE}.
*/
public IndonesianAnalyzer(Version matchVersion) {
this(matchVersion, DefaultSetHolder.DEFAULT_STOP_SET);
}
/**
* Builds an analyzer with the given stop words
*
* @param matchVersion
* lucene compatibility version
* @param stopwords
* a stopword set
*/
public IndonesianAnalyzer(Version matchVersion, Set<?> stopwords){
this(matchVersion, stopwords, CharArraySet.EMPTY_SET);
}
/**
* Builds an analyzer with the given stop word. If a none-empty stem exclusion set is
* provided this analyzer will add a {@link KeywordMarkerFilter} before
* {@link IndonesianStemFilter}.
*
* @param matchVersion
* lucene compatibility version
* @param stopwords
* a stopword set
* @param stemExclusionSet
* a set of terms not to be stemmed
*/
public IndonesianAnalyzer(Version matchVersion, Set<?> stopwords, Set<?> stemExclusionSet){
super(matchVersion, stopwords);
this.stemExclusionSet = CharArraySet.unmodifiableSet(CharArraySet.copy(
matchVersion, stemExclusionSet));
}
/**
* Creates
* {@link org.apache.lucene.analysis.util.ReusableAnalyzerBase.TokenStreamComponents}
* used to tokenize all the text in the provided {@link Reader}.
*
* @return {@link org.apache.lucene.analysis.util.ReusableAnalyzerBase.TokenStreamComponents}
* built from an {@link StandardTokenizer} filtered with
* {@link StandardFilter}, {@link LowerCaseFilter},
* {@link StopFilter}, {@link KeywordMarkerFilter}
* if a stem exclusion set is provided and {@link IndonesianStemFilter}.
*/
@Override
protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
final Tokenizer source = new StandardTokenizer(matchVersion, reader);
TokenStream result = new StandardFilter(matchVersion, source);
- result = new LowerCaseFilter(matchVersion, source);
+ result = new LowerCaseFilter(matchVersion, result);
result = new StopFilter(matchVersion, result, stopwords);
if (!stemExclusionSet.isEmpty()) {
result = new KeywordMarkerFilter(result, stemExclusionSet);
}
return new TokenStreamComponents(source, new IndonesianStemFilter(result));
}
}
| true | true | protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
final Tokenizer source = new StandardTokenizer(matchVersion, reader);
TokenStream result = new StandardFilter(matchVersion, source);
result = new LowerCaseFilter(matchVersion, source);
result = new StopFilter(matchVersion, result, stopwords);
if (!stemExclusionSet.isEmpty()) {
result = new KeywordMarkerFilter(result, stemExclusionSet);
}
return new TokenStreamComponents(source, new IndonesianStemFilter(result));
}
| protected TokenStreamComponents createComponents(String fieldName,
Reader reader) {
final Tokenizer source = new StandardTokenizer(matchVersion, reader);
TokenStream result = new StandardFilter(matchVersion, source);
result = new LowerCaseFilter(matchVersion, result);
result = new StopFilter(matchVersion, result, stopwords);
if (!stemExclusionSet.isEmpty()) {
result = new KeywordMarkerFilter(result, stemExclusionSet);
}
return new TokenStreamComponents(source, new IndonesianStemFilter(result));
}
|
diff --git a/src/main/java/be/Balor/Manager/Commands/Player/Reply.java b/src/main/java/be/Balor/Manager/Commands/Player/Reply.java
index 4267207b..735784f0 100644
--- a/src/main/java/be/Balor/Manager/Commands/Player/Reply.java
+++ b/src/main/java/be/Balor/Manager/Commands/Player/Reply.java
@@ -1,134 +1,134 @@
/************************************************************************
* This file is part of AdminCmd.
*
* AdminCmd 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.
*
* AdminCmd 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 AdminCmd. If not, see <http://www.gnu.org/licenses/>.
************************************************************************/
package be.Balor.Manager.Commands.Player;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import be.Balor.Manager.Commands.CommandArgs;
import be.Balor.Manager.Exceptions.PlayerNotFound;
import be.Balor.Manager.Permissions.ActionNotPermitedException;
import be.Balor.Manager.Permissions.PermissionManager;
import be.Balor.Player.ACPlayer;
import be.Balor.Tools.Type;
import be.Balor.Tools.Utils;
import be.Balor.Tools.Debug.ACLogger;
import be.Balor.bukkit.AdminCmd.ACHelper;
import be.Balor.bukkit.AdminCmd.ConfigEnum;
import be.Balor.bukkit.AdminCmd.LocaleHelper;
import belgium.Balor.Workers.AFKWorker;
import belgium.Balor.Workers.InvisibleWorker;
/**
* @author Lathanael (aka Philippe Leipold)
*
*/
public class Reply extends PlayerCommand {
/**
*
*/
public Reply() {
permNode = "admincmd.player.reply";
cmdName = "bal_reply";
}
@Override
public void execute(final CommandSender sender, final CommandArgs args)
throws ActionNotPermitedException, PlayerNotFound {
if (!Utils.isPlayer(sender, true)) {
return;
}
if (Utils.isPlayer(sender, false)
&& ACPlayer.getPlayer(((Player) sender)).hasPower(Type.MUTED)
&& ConfigEnum.MUTEDPM.getBoolean()) {
Utils.sI18n(sender, "muteEnabled");
return;
}
final Player pSender = (Player) sender;
final Player buddy = ACHelper.getInstance().getReplyPlayer(pSender);
if (buddy != null) {
if (!buddy.isOnline()) {
- Utils.sI18n(sender, "offline");
+ Utils.sI18n(sender, "offline", "player", buddy.getDisplayName());
ACHelper.getInstance().removeReplyPlayer(pSender);
return;
}
if (InvisibleWorker.getInstance().hasInvisiblePowers(buddy)
&& !PermissionManager.hasPerm(sender,
"admincmd.invisible.cansee", false)) {
Utils.sI18n(sender, "playerNotFound", "player",
args.getString(0));
return;
}
String senderPm = "";
String msg = "";
String senderName = "";
senderName = pSender.getName();
senderPm = Utils.getPlayerName(pSender, buddy) + ChatColor.WHITE
+ " - ";
for (final String arg : args) {
msg += arg + " ";
}
msg = msg.trim();
String parsed = Utils.colorParser(msg);
if (parsed == null) {
parsed = msg;
}
final HashMap<String, String> replace = new HashMap<String, String>();
replace.put("sender", senderPm);
replace.put("receiver", Utils.getPlayerName(buddy));
buddy.sendMessage(Utils.I18n("privateMessageHeader", replace)
+ parsed);
ACHelper.getInstance().setReplyPlayer(buddy, pSender);
if (AFKWorker.getInstance().isAfk(buddy)) {
AFKWorker.getInstance().sendAfkMessage(sender, buddy);
} else {
sender.sendMessage(Utils.I18n("privateMessageHeader", replace)
+ parsed);
}
final String spyMsg = LocaleHelper.SPYMSG_HEADER.getLocale(replace)
+ parsed;
for (final Player p : ACHelper.getInstance().getSpyPlayers()) {
if (p != null && !p.getName().equals(senderName)
&& !p.getName().equals(buddy.getName())) {
p.sendMessage(spyMsg);
}
}
if (ConfigEnum.LOG_PM.getBoolean()) {
ACLogger.info(spyMsg);
}
} else {
Utils.sI18n(sender, "noPlayerToReply");
}
}
/*
* (non-Javadoc)
*
* @see be.Balor.Manager.ACCommands#argsCheck(java.lang.String[])
*/
@Override
public boolean argsCheck(final String... args) {
return args != null && args.length >= 1;
}
}
| true | true | public void execute(final CommandSender sender, final CommandArgs args)
throws ActionNotPermitedException, PlayerNotFound {
if (!Utils.isPlayer(sender, true)) {
return;
}
if (Utils.isPlayer(sender, false)
&& ACPlayer.getPlayer(((Player) sender)).hasPower(Type.MUTED)
&& ConfigEnum.MUTEDPM.getBoolean()) {
Utils.sI18n(sender, "muteEnabled");
return;
}
final Player pSender = (Player) sender;
final Player buddy = ACHelper.getInstance().getReplyPlayer(pSender);
if (buddy != null) {
if (!buddy.isOnline()) {
Utils.sI18n(sender, "offline");
ACHelper.getInstance().removeReplyPlayer(pSender);
return;
}
if (InvisibleWorker.getInstance().hasInvisiblePowers(buddy)
&& !PermissionManager.hasPerm(sender,
"admincmd.invisible.cansee", false)) {
Utils.sI18n(sender, "playerNotFound", "player",
args.getString(0));
return;
}
String senderPm = "";
String msg = "";
String senderName = "";
senderName = pSender.getName();
senderPm = Utils.getPlayerName(pSender, buddy) + ChatColor.WHITE
+ " - ";
for (final String arg : args) {
msg += arg + " ";
}
msg = msg.trim();
String parsed = Utils.colorParser(msg);
if (parsed == null) {
parsed = msg;
}
final HashMap<String, String> replace = new HashMap<String, String>();
replace.put("sender", senderPm);
replace.put("receiver", Utils.getPlayerName(buddy));
buddy.sendMessage(Utils.I18n("privateMessageHeader", replace)
+ parsed);
ACHelper.getInstance().setReplyPlayer(buddy, pSender);
if (AFKWorker.getInstance().isAfk(buddy)) {
AFKWorker.getInstance().sendAfkMessage(sender, buddy);
} else {
sender.sendMessage(Utils.I18n("privateMessageHeader", replace)
+ parsed);
}
final String spyMsg = LocaleHelper.SPYMSG_HEADER.getLocale(replace)
+ parsed;
for (final Player p : ACHelper.getInstance().getSpyPlayers()) {
if (p != null && !p.getName().equals(senderName)
&& !p.getName().equals(buddy.getName())) {
p.sendMessage(spyMsg);
}
}
if (ConfigEnum.LOG_PM.getBoolean()) {
ACLogger.info(spyMsg);
}
} else {
Utils.sI18n(sender, "noPlayerToReply");
}
}
| public void execute(final CommandSender sender, final CommandArgs args)
throws ActionNotPermitedException, PlayerNotFound {
if (!Utils.isPlayer(sender, true)) {
return;
}
if (Utils.isPlayer(sender, false)
&& ACPlayer.getPlayer(((Player) sender)).hasPower(Type.MUTED)
&& ConfigEnum.MUTEDPM.getBoolean()) {
Utils.sI18n(sender, "muteEnabled");
return;
}
final Player pSender = (Player) sender;
final Player buddy = ACHelper.getInstance().getReplyPlayer(pSender);
if (buddy != null) {
if (!buddy.isOnline()) {
Utils.sI18n(sender, "offline", "player", buddy.getDisplayName());
ACHelper.getInstance().removeReplyPlayer(pSender);
return;
}
if (InvisibleWorker.getInstance().hasInvisiblePowers(buddy)
&& !PermissionManager.hasPerm(sender,
"admincmd.invisible.cansee", false)) {
Utils.sI18n(sender, "playerNotFound", "player",
args.getString(0));
return;
}
String senderPm = "";
String msg = "";
String senderName = "";
senderName = pSender.getName();
senderPm = Utils.getPlayerName(pSender, buddy) + ChatColor.WHITE
+ " - ";
for (final String arg : args) {
msg += arg + " ";
}
msg = msg.trim();
String parsed = Utils.colorParser(msg);
if (parsed == null) {
parsed = msg;
}
final HashMap<String, String> replace = new HashMap<String, String>();
replace.put("sender", senderPm);
replace.put("receiver", Utils.getPlayerName(buddy));
buddy.sendMessage(Utils.I18n("privateMessageHeader", replace)
+ parsed);
ACHelper.getInstance().setReplyPlayer(buddy, pSender);
if (AFKWorker.getInstance().isAfk(buddy)) {
AFKWorker.getInstance().sendAfkMessage(sender, buddy);
} else {
sender.sendMessage(Utils.I18n("privateMessageHeader", replace)
+ parsed);
}
final String spyMsg = LocaleHelper.SPYMSG_HEADER.getLocale(replace)
+ parsed;
for (final Player p : ACHelper.getInstance().getSpyPlayers()) {
if (p != null && !p.getName().equals(senderName)
&& !p.getName().equals(buddy.getName())) {
p.sendMessage(spyMsg);
}
}
if (ConfigEnum.LOG_PM.getBoolean()) {
ACLogger.info(spyMsg);
}
} else {
Utils.sI18n(sender, "noPlayerToReply");
}
}
|
diff --git a/AeroControl/src/com/aero/control/fragments/MemoryFragment.java b/AeroControl/src/com/aero/control/fragments/MemoryFragment.java
index 059990d..0760cb4 100644
--- a/AeroControl/src/com/aero/control/fragments/MemoryFragment.java
+++ b/AeroControl/src/com/aero/control/fragments/MemoryFragment.java
@@ -1,453 +1,453 @@
package com.aero.control.fragments;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.aero.control.AeroActivity;
import com.aero.control.R;
import com.aero.control.helpers.CustomTextPreference;
import com.espian.showcaseview.ShowcaseView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
/**
* Created by Alexander Christ on 16.09.13.
* Default Memory Fragment
*/
public class MemoryFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
public static final String GOV_IO_FILE = "/sys/block/mmcblk0/queue/scheduler";
public static final String DYANMIC_FSYNC = "/sys/kernel/dyn_fsync/Dyn_fsync_active";
public static final String CMDLINE_ZACHE = "/system/bootmenu/2nd-boot/cmdline";
public static final String WRITEBACK = "/sys/devices/virtual/misc/writeback/writeback_enabled";
public static final String LOW_MEM = "/system/build.prop";
public static final String FILENAME = "firstrun_trim";
public static final String FILENAME_HIDDEN = "firstrun_hidden_feature";
public static final String GOV_IO_PARAMETER = "/sys/devices/platform/mmci-omap-hs.0/mmc_host/mmc0/mmc0:1234/block/mmcblk0/queue/iosched/";
public ShowcaseView.ConfigOptions mConfigOptions;
public ShowcaseView mShowCase;
public PreferenceCategory PrefCat;
public PreferenceScreen root;
private MemoryDalvikFragment mMemoryDalvikFragment;
public boolean showDialog = true;
public static final Handler progressHandler = new Handler();
private CheckBoxPreference mDynFSync, mZCache, mLowMemoryPref, mWriteBackControl;
private EditTextPreference mSwappiness, mMinFreeRAM;
private Preference mFSTrimToggle, mDalvikSettings;
private ListPreference mIOScheduler;
private static final String MEMORY_SETTINGS_CATEGORY = "memory_settings";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.layout.memory_fragment);
root = this.getPreferenceScreen();
final PreferenceCategory memorySettingsCategory =
(PreferenceCategory) findPreference(MEMORY_SETTINGS_CATEGORY);
mDynFSync = (CheckBoxPreference) findPreference("dynFsync");
if ("1".equals(AeroActivity.shell.getInfo(DYANMIC_FSYNC))) {
mDynFSync.setChecked(true);
} else if ("0".equals(AeroActivity.shell.getInfo(DYANMIC_FSYNC))) {
mDynFSync.setChecked(false);
} else {
if (memorySettingsCategory != null) memorySettingsCategory.removePreference(mDynFSync);
}
mZCache = (CheckBoxPreference) findPreference("zcache");
- if ("Unavailable".equals(AeroActivity.shell.getInfo(CMDLINE_ZACHE)))
+ if ("Unavailable".equals(AeroActivity.shell.getInfo(CMDLINE_ZACHE))) {
if (memorySettingsCategory != null) memorySettingsCategory.removePreference(mZCache);
- else {
- final String fileCMD = AeroActivity.shell.getInfo(CMDLINE_ZACHE);
- final boolean zcacheEnabled = fileCMD.length() != 0 && fileCMD.contains("zcache");
- mZCache.setChecked(zcacheEnabled);
- }
+ } else {
+ final String fileCMD = AeroActivity.shell.getInfo(CMDLINE_ZACHE);
+ final boolean zcacheEnabled = fileCMD.length() != 0 && fileCMD.contains("zcache");
+ mZCache.setChecked(zcacheEnabled);
+ }
mWriteBackControl = (CheckBoxPreference) findPreference("writeback");
- if (AeroActivity.shell.getInfo(WRITEBACK).equals("1")) {
+ if ("1".equals(AeroActivity.shell.getInfo(WRITEBACK))) {
mWriteBackControl.setChecked(true);
- } else if (AeroActivity.shell.getInfo(WRITEBACK).equals("0")) {
+ } else if ("0".equals(AeroActivity.shell.getInfo(WRITEBACK))) {
mWriteBackControl.setChecked(false);
} else {
if (memorySettingsCategory != null)
memorySettingsCategory.removePreference(mWriteBackControl);
}
mLowMemoryPref = (CheckBoxPreference) findPreference("low_mem");
mFSTrimToggle = findPreference("fstrim_toggle");
mDalvikSettings = findPreference("dalvik_settings");
mIOScheduler = (ListPreference) findPreference("io_scheduler_list");
mIOScheduler.setEntries(AeroActivity.shell.getInfoArray(GOV_IO_FILE, 0, 1));
mIOScheduler.setEntryValues(AeroActivity.shell.getInfoArray(GOV_IO_FILE, 0, 1));
mIOScheduler.setValue(AeroActivity.shell.getInfoString(AeroActivity.shell.getInfo(GOV_IO_FILE)));
mIOScheduler.setSummary(AeroActivity.shell.getInfoString(AeroActivity.shell.getInfo(GOV_IO_FILE)));
mIOScheduler.setDialogIcon(R.drawable.memory_dark);
mIOScheduler.setOnPreferenceChangeListener(this);
if (showDialog) {
// Ensure only devices with this special path are checked;
final String fileMount[] = AeroActivity.shell.getInfo("/proc/mounts", false);
boolean fileMountCheck = false;
for (String tmp : fileMount) {
if (tmp.contains("/dev/block/mmcblk1p25")) {
fileMountCheck = true;
break;
}
}
showDialog = false;
if (fileMountCheck) {
final String fileJournal = AeroActivity.shell.getRootInfo("tune2fs -l", "/dev/block/mmcblk1p25");
final boolean fileSystemCheck = fileJournal.length() != 0 && fileJournal.contains("has_journal");
if (!fileSystemCheck) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
// Just reuse aboutScreen, because its Linear and has a TextView
View layout = inflater.inflate(R.layout.about_screen, null);
TextView aboutText = (TextView) (layout != null ? layout.findViewById(R.id.aboutScreen) : null);
builder.setTitle(R.string.has_journal_dialog_header);
if (aboutText != null) {
aboutText.setText(getText(R.string.has_journal_dialog));
aboutText.setTextSize(13);
}
builder.setView(layout)
.setPositiveButton(R.string.got_it, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
}
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Prepare Showcase;
mConfigOptions = new ShowcaseView.ConfigOptions();
mConfigOptions.hideOnClickOutside = false;
mConfigOptions.shotType = ShowcaseView.TYPE_ONE_SHOT;
// Set up our file;
int output = 0;
final byte[] buffer = new byte[1024];
try {
FileInputStream fis = getActivity().openFileInput(FILENAME);
output = fis.read(buffer);
fis.close();
} catch (IOException e) {
Log.e("Aero", "Couldn't open File... " + output);
}
// Only show showcase once;
if (output == 0)
DrawFirstStart(R.string.showcase_memory_fragment_trim, R.string.showcase_memory_fragment_trim_sum, FILENAME);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
if (preference == mLowMemoryPref) {
lowMemoryPrefClick();
} else if (preference == mDynFSync) {
boolean value = mDynFSync.isChecked();
if (value) AeroActivity.shell.setRootInfo("1", DYANMIC_FSYNC);
else AeroActivity.shell.setRootInfo("0", DYANMIC_FSYNC);
} else if (preference == mZCache) {
zCacheClick();
} else if (preference == mWriteBackControl) {
boolean value = mWriteBackControl.isChecked();
if (value) AeroActivity.shell.setRootInfo("1", WRITEBACK);
else AeroActivity.shell.setRootInfo("0", WRITEBACK);
} else if (preference == mFSTrimToggle) {
fsTrimToggleClick();
} else if (preference == mDalvikSettings) {
if (mMemoryDalvikFragment == null)
mMemoryDalvikFragment = new MemoryDalvikFragment();
getFragmentManager()
.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.replace(R.id.content_frame, mMemoryDalvikFragment)
.addToBackStack("Memory")
.commit();
} else {
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
preference.getEditor().commit();
return true;
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == mIOScheduler) {
String value = (String) newValue;
mIOScheduler.setSummary(value);
AeroActivity.shell.setRootInfo(value, GOV_IO_FILE);
loadIOParameter();
} else {
return false;
}
preference.getEditor().commit();
return true;
}
private void zCacheClick() {
String getState = AeroActivity.shell.getInfo(CMDLINE_ZACHE);
boolean value = mZCache.isChecked();
AeroActivity.shell.remountSystem();
if (value) {
// If already on, we can bail out;
if (getState.contains("zcache")) return;
getState = getState + " zcache";
} else {
// bail out again, because its already how we want it;
if (!getState.contains("zcache")) return;
getState = getState.replace(" zcache", "");
}
// Set current State to path;
AeroActivity.shell.setRootInfo(getState, CMDLINE_ZACHE);
Toast.makeText(getActivity(), R.string.need_reboot, Toast.LENGTH_LONG).show();
}
private void lowMemoryPrefClick() {
String getState = null;
boolean value = mLowMemoryPref.isChecked();
AeroActivity.shell.remountSystem();
try {
final BufferedReader br = new BufferedReader(new FileReader(LOW_MEM));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append('\n');
line = br.readLine();
}
getState = sb.toString();
if (value) {
// If already on, we can bail out;
if (getState.contains("ro.config.low_ram=true")) return;
getState = getState.replace("ro.config.low_ram=false", "ro.config.low_ram=true");
} else {
// bail out again, because its already how we want it;
if (getState.contains("ro.config.low_ram=false")) return;
getState = getState.replace("ro.config.low_ram=true", "ro.config.low_ram=false");
}
} catch (IOException ignored) {
}
} catch (FileNotFoundException ignored) {
}
// Set current State to path;
AeroActivity.shell.setRootInfo(getState, LOW_MEM);
Toast.makeText(getActivity(), R.string.need_reboot, Toast.LENGTH_LONG).show();
}
private void fsTrimToggleClick() {
final CharSequence[] system = {"/system", "/data", "/cache"};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final ProgressDialog update = new ProgressDialog(getActivity());
builder.setTitle(R.string.fstrim_header);
builder.setIcon(R.drawable.gear_dark);
builder.setItems(system, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
final String b = (String) system[item];
update.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
update.setCancelable(false);
update.setMax(100);
update.setIndeterminate(true);
update.show();
AeroActivity.shell.remountSystem();
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
while (update.getProgress() < 100) {
// Set up the root-command;
AeroActivity.shell.getRootInfo("fstrim -v", b);
update.setIndeterminate(false);
update.setProgress(100);
progressHandler.sendMessage(progressHandler.obtainMessage());
// Sleep the current thread and exit dialog;
Thread.sleep(2000);
update.dismiss();
}
} catch (Exception e) {
Log.e("Aero", "An error occurred while trimming.", e);
}
}
};
Thread trimThread = new Thread(runnable);
if (!trimThread.isAlive())
trimThread.start();
}
}).show();
}
public void DrawFirstStart(int header, int content, String filename) {
try {
FileOutputStream fos = getActivity().openFileOutput(filename, Context.MODE_PRIVATE);
fos.write("1".getBytes());
fos.close();
} catch (IOException e) {
Log.e("Aero", "Could not save file. ", e);
}
mShowCase = ShowcaseView.insertShowcaseView(150, 730, getActivity(), header, content, mConfigOptions);
}
private void loadIOParameter() {
mConfigOptions = new ShowcaseView.ConfigOptions();
mConfigOptions.hideOnClickOutside = false;
mConfigOptions.shotType = ShowcaseView.TYPE_ONE_SHOT;
// Set up our file;
int output = 0;
final byte[] buffer = new byte[1024];
try {
FileInputStream fis = getActivity().openFileInput(FILENAME_HIDDEN);
output = fis.read(buffer);
fis.close();
} catch (IOException e) {
Log.e("Aero", "Couldn't open File... " + output);
}
// Only show showcase once;
if (output == 0)
DrawFirstStart(R.string.showcase_hidden_feature, R.string.showcase_hidden_feature_sum, FILENAME_HIDDEN);
final String complete_path = GOV_IO_PARAMETER;
try {
String completeParamterList[] = AeroActivity.shell.getDirInfo(complete_path, true);
// If there are already some entries, kill them all (with fire)
if (PrefCat != null)
root.removePreference(PrefCat);
PrefCat = new PreferenceCategory(getActivity());
PrefCat.setTitle(R.string.io_scheduler);
root.addPreference(PrefCat);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.e("Aero", "Something interrupted the main Thread, try again.", e);
}
handler h = new handler();
for (String b : completeParamterList)
h.generateSettings(b, complete_path);
// Probably the wrong place, should be in getDirInfo ?
} catch (NullPointerException e) {
Toast.makeText(getActivity(), "Looks like there are no parameter for this governor?", Toast.LENGTH_LONG).show();
Log.e("Aero", "There isn't any folder i can check. Does this governor has parameters?", e);
}
}
// Make a private class to load all parameters;
private class handler {
public void generateSettings(final String parameter, String path) {
final CustomTextPreference prefload = new CustomTextPreference(getActivity());
// Strings saves the complete path for a given governor;
final String parameterPath = path + "/" + parameter;
String summary = AeroActivity.shell.getInfo(parameterPath);
// Only show numbers in input field;
prefload.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
// Setup all things we would normally do in XML;
prefload.setSummary(summary);
prefload.setTitle(parameter);
prefload.setText(summary);
prefload.setDialogTitle(parameter);
if ("Unavailable".equals(prefload.getSummary())) {
prefload.setEnabled(false);
prefload.setSummary("This value can't be changed.");
}
PrefCat.addPreference(prefload);
// Custom OnChangeListener for each element in our list;
prefload.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object o) {
String a = (String) o;
CharSequence oldValue = prefload.getSummary();
AeroActivity.shell.setRootInfo(a, parameterPath);
if (AeroActivity.shell.checkPath(AeroActivity.shell.getInfo(parameterPath), a)) {
prefload.setSummary(a);
} else {
Toast.makeText(getActivity(), "Couldn't set desired parameter" + " Old value; " +
AeroActivity.shell.getInfo(parameterPath) + " New Value; " + a, Toast.LENGTH_LONG).show();
prefload.setSummary(oldValue);
}
// Store our custom preferences if available;
SharedPreferences preferences = getPreferenceManager().getSharedPreferences();
preferences.edit().putString(parameterPath, o.toString()).commit();
return true;
}
;
});
}
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.layout.memory_fragment);
root = this.getPreferenceScreen();
final PreferenceCategory memorySettingsCategory =
(PreferenceCategory) findPreference(MEMORY_SETTINGS_CATEGORY);
mDynFSync = (CheckBoxPreference) findPreference("dynFsync");
if ("1".equals(AeroActivity.shell.getInfo(DYANMIC_FSYNC))) {
mDynFSync.setChecked(true);
} else if ("0".equals(AeroActivity.shell.getInfo(DYANMIC_FSYNC))) {
mDynFSync.setChecked(false);
} else {
if (memorySettingsCategory != null) memorySettingsCategory.removePreference(mDynFSync);
}
mZCache = (CheckBoxPreference) findPreference("zcache");
if ("Unavailable".equals(AeroActivity.shell.getInfo(CMDLINE_ZACHE)))
if (memorySettingsCategory != null) memorySettingsCategory.removePreference(mZCache);
else {
final String fileCMD = AeroActivity.shell.getInfo(CMDLINE_ZACHE);
final boolean zcacheEnabled = fileCMD.length() != 0 && fileCMD.contains("zcache");
mZCache.setChecked(zcacheEnabled);
}
mWriteBackControl = (CheckBoxPreference) findPreference("writeback");
if (AeroActivity.shell.getInfo(WRITEBACK).equals("1")) {
mWriteBackControl.setChecked(true);
} else if (AeroActivity.shell.getInfo(WRITEBACK).equals("0")) {
mWriteBackControl.setChecked(false);
} else {
if (memorySettingsCategory != null)
memorySettingsCategory.removePreference(mWriteBackControl);
}
mLowMemoryPref = (CheckBoxPreference) findPreference("low_mem");
mFSTrimToggle = findPreference("fstrim_toggle");
mDalvikSettings = findPreference("dalvik_settings");
mIOScheduler = (ListPreference) findPreference("io_scheduler_list");
mIOScheduler.setEntries(AeroActivity.shell.getInfoArray(GOV_IO_FILE, 0, 1));
mIOScheduler.setEntryValues(AeroActivity.shell.getInfoArray(GOV_IO_FILE, 0, 1));
mIOScheduler.setValue(AeroActivity.shell.getInfoString(AeroActivity.shell.getInfo(GOV_IO_FILE)));
mIOScheduler.setSummary(AeroActivity.shell.getInfoString(AeroActivity.shell.getInfo(GOV_IO_FILE)));
mIOScheduler.setDialogIcon(R.drawable.memory_dark);
mIOScheduler.setOnPreferenceChangeListener(this);
if (showDialog) {
// Ensure only devices with this special path are checked;
final String fileMount[] = AeroActivity.shell.getInfo("/proc/mounts", false);
boolean fileMountCheck = false;
for (String tmp : fileMount) {
if (tmp.contains("/dev/block/mmcblk1p25")) {
fileMountCheck = true;
break;
}
}
showDialog = false;
if (fileMountCheck) {
final String fileJournal = AeroActivity.shell.getRootInfo("tune2fs -l", "/dev/block/mmcblk1p25");
final boolean fileSystemCheck = fileJournal.length() != 0 && fileJournal.contains("has_journal");
if (!fileSystemCheck) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
// Just reuse aboutScreen, because its Linear and has a TextView
View layout = inflater.inflate(R.layout.about_screen, null);
TextView aboutText = (TextView) (layout != null ? layout.findViewById(R.id.aboutScreen) : null);
builder.setTitle(R.string.has_journal_dialog_header);
if (aboutText != null) {
aboutText.setText(getText(R.string.has_journal_dialog));
aboutText.setTextSize(13);
}
builder.setView(layout)
.setPositiveButton(R.string.got_it, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
}
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.layout.memory_fragment);
root = this.getPreferenceScreen();
final PreferenceCategory memorySettingsCategory =
(PreferenceCategory) findPreference(MEMORY_SETTINGS_CATEGORY);
mDynFSync = (CheckBoxPreference) findPreference("dynFsync");
if ("1".equals(AeroActivity.shell.getInfo(DYANMIC_FSYNC))) {
mDynFSync.setChecked(true);
} else if ("0".equals(AeroActivity.shell.getInfo(DYANMIC_FSYNC))) {
mDynFSync.setChecked(false);
} else {
if (memorySettingsCategory != null) memorySettingsCategory.removePreference(mDynFSync);
}
mZCache = (CheckBoxPreference) findPreference("zcache");
if ("Unavailable".equals(AeroActivity.shell.getInfo(CMDLINE_ZACHE))) {
if (memorySettingsCategory != null) memorySettingsCategory.removePreference(mZCache);
} else {
final String fileCMD = AeroActivity.shell.getInfo(CMDLINE_ZACHE);
final boolean zcacheEnabled = fileCMD.length() != 0 && fileCMD.contains("zcache");
mZCache.setChecked(zcacheEnabled);
}
mWriteBackControl = (CheckBoxPreference) findPreference("writeback");
if ("1".equals(AeroActivity.shell.getInfo(WRITEBACK))) {
mWriteBackControl.setChecked(true);
} else if ("0".equals(AeroActivity.shell.getInfo(WRITEBACK))) {
mWriteBackControl.setChecked(false);
} else {
if (memorySettingsCategory != null)
memorySettingsCategory.removePreference(mWriteBackControl);
}
mLowMemoryPref = (CheckBoxPreference) findPreference("low_mem");
mFSTrimToggle = findPreference("fstrim_toggle");
mDalvikSettings = findPreference("dalvik_settings");
mIOScheduler = (ListPreference) findPreference("io_scheduler_list");
mIOScheduler.setEntries(AeroActivity.shell.getInfoArray(GOV_IO_FILE, 0, 1));
mIOScheduler.setEntryValues(AeroActivity.shell.getInfoArray(GOV_IO_FILE, 0, 1));
mIOScheduler.setValue(AeroActivity.shell.getInfoString(AeroActivity.shell.getInfo(GOV_IO_FILE)));
mIOScheduler.setSummary(AeroActivity.shell.getInfoString(AeroActivity.shell.getInfo(GOV_IO_FILE)));
mIOScheduler.setDialogIcon(R.drawable.memory_dark);
mIOScheduler.setOnPreferenceChangeListener(this);
if (showDialog) {
// Ensure only devices with this special path are checked;
final String fileMount[] = AeroActivity.shell.getInfo("/proc/mounts", false);
boolean fileMountCheck = false;
for (String tmp : fileMount) {
if (tmp.contains("/dev/block/mmcblk1p25")) {
fileMountCheck = true;
break;
}
}
showDialog = false;
if (fileMountCheck) {
final String fileJournal = AeroActivity.shell.getRootInfo("tune2fs -l", "/dev/block/mmcblk1p25");
final boolean fileSystemCheck = fileJournal.length() != 0 && fileJournal.contains("has_journal");
if (!fileSystemCheck) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
// Just reuse aboutScreen, because its Linear and has a TextView
View layout = inflater.inflate(R.layout.about_screen, null);
TextView aboutText = (TextView) (layout != null ? layout.findViewById(R.id.aboutScreen) : null);
builder.setTitle(R.string.has_journal_dialog_header);
if (aboutText != null) {
aboutText.setText(getText(R.string.has_journal_dialog));
aboutText.setTextSize(13);
}
builder.setView(layout)
.setPositiveButton(R.string.got_it, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
}
}
}
|
diff --git a/jdbc2/src/examples/TestJava2d.java b/jdbc2/src/examples/TestJava2d.java
index 2a4ca33d0..8ae614814 100644
--- a/jdbc2/src/examples/TestJava2d.java
+++ b/jdbc2/src/examples/TestJava2d.java
@@ -1,179 +1,179 @@
/*
* Test.java
*
* PostGIS extension for PostgreSQL JDBC driver - example and test classes
*
* (C) 2004 Paul Ramsey, [email protected]
*
* (C) 2005 Markus Schaber, [email protected]
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License.
*
* 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 or visit the web at
* http://www.gnu.org.
*
* $Id$
*/
package examples;
import java.awt.*;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.postgis.java2d.Java2DWrapper;
public class TestJava2d {
private static final boolean DEBUG = true;
public static final Shape[] SHAPEARRAY = new Shape[0];
static {
new Java2DWrapper(); // make shure our driver is initialized
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
if (args.length != 5) {
- System.err.println("Usage: java examples/TestServer dburl user pass tablename column");
+ System.err.println("Usage: java examples/TestJava2D dburl user pass tablename column");
System.err.println();
System.err.println("dburl has the following format:");
System.err.println(Java2DWrapper.POSTGIS_PROTOCOL + "//HOST:PORT/DATABASENAME");
System.err.println("tablename is 'jdbc_test' by default.");
System.exit(1);
}
Shape[] geometries = read(args[0], args[1], args[2], "SELECT " + args[4] + " FROM "
+ args[3]);
if (geometries.length == 0) {
System.err.println("No geometries were found.");
return;
}
System.err.println("Painting...");
Frame window = new Frame("PostGIS java2D demo");
Canvas CV = new GisCanvas(geometries);
window.add(CV);
window.setSize(500, 500);
window.addWindowListener(new EventHandler());
window.show();
}
static Rectangle2D calcbbox(Shape[] geometries) {
Rectangle2D bbox = geometries[0].getBounds2D();
for (int i = 1; i < geometries.length; i++) {
bbox = bbox.createUnion(geometries[i].getBounds2D());
}
return bbox;
}
private static Shape[] read(String dburl, String dbuser, String dbpass, String query)
throws ClassNotFoundException, SQLException {
ArrayList geometries = new ArrayList();
System.out.println("Creating JDBC connection...");
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection(dburl, dbuser, dbpass);
System.out.println("fetching geometries");
ResultSet r = conn.createStatement().executeQuery(query);
while (r.next()) {
final Shape current = (Shape) r.getObject(1);
if (current != null) {
geometries.add(current);
}
}
conn.close();
return (Shape[]) geometries.toArray(SHAPEARRAY);
}
public static class GisCanvas extends Canvas {
/** Keep java 1.5 compiler happy */
private static final long serialVersionUID = 1L;
final Rectangle2D bbox;
final Shape[] geometries;
public GisCanvas(Shape[] geometries) {
this.geometries = geometries;
this.bbox = calcbbox(geometries);
setBackground(Color.GREEN);
}
public void paint(Graphics og) {
Graphics2D g = (Graphics2D) og;
final double scaleX = (super.getWidth() - 10) / bbox.getWidth();
final double scaleY = (super.getHeight() - 10) / bbox.getHeight();
AffineTransform at = new AffineTransform();
at.translate(super.getX() + 5, super.getY() + 5);
at.scale(scaleX, scaleY);
at.translate(-bbox.getX(), -bbox.getY());
if (DEBUG) {
System.err.println();
System.err.println("bbox: " + bbox);
System.err.println("trans: " + at);
System.err.println("new: " + at.createTransformedShape(bbox).getBounds2D());
System.err.println("visual:" + super.getBounds());
}
for (int i = 0; i < geometries.length; i++) {
g.setPaint(Color.BLUE);
final Shape shape = at.createTransformedShape(geometries[i]);
g.fill(shape);
g.setPaint(Color.ORANGE);
g.draw(shape);
}
}
}
public static class EventHandler implements WindowListener {
public void windowActivated(WindowEvent e) {//
}
public void windowClosed(WindowEvent e) {//
}
public void windowClosing(WindowEvent e) {
e.getWindow().hide();
System.exit(0);
}
public void windowDeactivated(WindowEvent e) {//
}
public void windowDeiconified(WindowEvent e) {//
}
public void windowIconified(WindowEvent e) {//
}
public void windowOpened(WindowEvent e) {//
}
}
}
| true | true | public static void main(String[] args) throws ClassNotFoundException, SQLException {
if (args.length != 5) {
System.err.println("Usage: java examples/TestServer dburl user pass tablename column");
System.err.println();
System.err.println("dburl has the following format:");
System.err.println(Java2DWrapper.POSTGIS_PROTOCOL + "//HOST:PORT/DATABASENAME");
System.err.println("tablename is 'jdbc_test' by default.");
System.exit(1);
}
Shape[] geometries = read(args[0], args[1], args[2], "SELECT " + args[4] + " FROM "
+ args[3]);
if (geometries.length == 0) {
System.err.println("No geometries were found.");
return;
}
System.err.println("Painting...");
Frame window = new Frame("PostGIS java2D demo");
Canvas CV = new GisCanvas(geometries);
window.add(CV);
window.setSize(500, 500);
window.addWindowListener(new EventHandler());
window.show();
}
| public static void main(String[] args) throws ClassNotFoundException, SQLException {
if (args.length != 5) {
System.err.println("Usage: java examples/TestJava2D dburl user pass tablename column");
System.err.println();
System.err.println("dburl has the following format:");
System.err.println(Java2DWrapper.POSTGIS_PROTOCOL + "//HOST:PORT/DATABASENAME");
System.err.println("tablename is 'jdbc_test' by default.");
System.exit(1);
}
Shape[] geometries = read(args[0], args[1], args[2], "SELECT " + args[4] + " FROM "
+ args[3]);
if (geometries.length == 0) {
System.err.println("No geometries were found.");
return;
}
System.err.println("Painting...");
Frame window = new Frame("PostGIS java2D demo");
Canvas CV = new GisCanvas(geometries);
window.add(CV);
window.setSize(500, 500);
window.addWindowListener(new EventHandler());
window.show();
}
|
diff --git a/src/com/ichi2/libanki/Utils.java b/src/com/ichi2/libanki/Utils.java
index 9d425418..8d5dadc2 100644
--- a/src/com/ichi2/libanki/Utils.java
+++ b/src/com/ichi2/libanki/Utils.java
@@ -1,1162 +1,1162 @@
/****************************************************************************************
* Copyright (c) 2009 Daniel Sv�rd <[email protected]> *
* Copyright (c) 2009 Edu Zamora <[email protected]> *
* Copyright (c) 2011 Norbert Nagold <[email protected]> *
* Copyright (c) 2012 Kostas Spyropoulos <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import com.ichi2.anki.AnkiDb;
import com.ichi2.anki.AnkiDroidApp;
import com.ichi2.anki.AnkiFont;
import com.ichi2.anki.R;
import com.ichi2.async.Connection.OldAnkiDeckFilter;
import com.mindprod.common11.BigDate;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Date;
import java.text.Normalizer;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* TODO comments
*/
public class Utils {
enum SqlCommandType { SQL_INS, SQL_UPD, SQL_DEL };
// Used to format doubles with English's decimal separator system
public static final Locale ENGLISH_LOCALE = new Locale("en_US");
public static final int CHUNK_SIZE = 32768;
private static final int DAYS_BEFORE_1970 = 719163;
private static NumberFormat mCurrentNumberFormat;
private static NumberFormat mCurrentPercentageFormat;
private static TreeSet<Long> sIdTree;
private static long sIdTime;
private static final int TIME_SECONDS = 0;
private static final int TIME_MINUTES = 1;
private static final int TIME_HOURS = 2;
private static final int TIME_DAYS = 3;
private static final int TIME_MONTHS = 4;
private static final int TIME_YEARS = 5;
public static final int TIME_FORMAT_DEFAULT = 0;
public static final int TIME_FORMAT_IN = 1;
public static final int TIME_FORMAT_BEFORE = 2;
/* Prevent class from being instantiated */
private Utils() { }
// Regex pattern used in removing tags from text before diff
private static final Pattern stylePattern = Pattern.compile("(?s)<style.*?>.*?</style>");
private static final Pattern scriptPattern = Pattern.compile("(?s)<script.*?>.*?</script>");
private static final Pattern tagPattern = Pattern.compile("<.*?>");
private static final Pattern imgPattern = Pattern.compile("<img src=[\\\"']?([^\\\"'>]+)[\\\"']? ?/?>");
private static final Pattern htmlEntitiesPattern = Pattern.compile("&#?\\w+;");
private static final String ALL_CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
/**The time in integer seconds. Pass scale=1000 to get milliseconds. */
public static double now() {
return (System.currentTimeMillis() / 1000.0);
}
/**The time in integer seconds. Pass scale=1000 to get milliseconds. */
public static long intNow() {
return intNow(1);
}
public static long intNow(int scale) {
return (long) (now() * scale);
}
// timetable
// aftertimetable
// shorttimetable
/**
* Return a string representing a time span (eg '2 days').
* @param inFormat: if true, return eg 'in 2 days'
*/
public static String fmtTimeSpan(int time) {
return fmtTimeSpan(time, 0, false, false);
}
public static String fmtTimeSpan(int time, boolean _short) {
return fmtTimeSpan(time, 0, _short, false);
}
public static String fmtTimeSpan(int time, int format, boolean _short, boolean boldNumber) {
int type;
int unit = 99;
int point = 0;
if (Math.abs(time) < 60 || unit < 1) {
type = TIME_SECONDS;
} else if (Math.abs(time) < 3600 || unit < 2) {
type = TIME_MINUTES;
} else if (Math.abs(time) < 60 * 60 * 24 || unit < 3) {
type = TIME_HOURS;
} else if (Math.abs(time) < 60 * 60 * 24 * 29.5 || unit < 4) {
type = TIME_DAYS;
} else if (Math.abs(time) < 60 * 60 * 24 * 30 * 11.95 || unit < 5) {
type = TIME_MONTHS;
point = 1;
} else {
type = TIME_YEARS;
point = 1;
}
double ftime = convertSecondsTo(time, type);
int formatId;
if (false){//_short) {
//formatId = R.array.next_review_short;
} else {
switch (format) {
case TIME_FORMAT_IN:
if (Math.round(ftime * 10) == 10) {
formatId = R.array.next_review_in_s;
} else {
formatId = R.array.next_review_in_p;
}
break;
case TIME_FORMAT_BEFORE:
if (Math.round(ftime * 10) == 10) {
formatId = R.array.next_review_before_s;
} else {
formatId = R.array.next_review_before_p;
}
break;
case TIME_FORMAT_DEFAULT:
default:
if (Math.round(ftime * 10) == 10) {
formatId = R.array.next_review_s;
} else {
formatId = R.array.next_review_p;
}
break;
}
}
String timeString = String.format(AnkiDroidApp.getAppResources().getStringArray(formatId)[type], boldNumber ? "<b>" + fmtDouble(ftime, point) + "</b>" : fmtDouble(ftime, point));
if (boldNumber && time == 1) {
timeString = timeString.replace("1", "<b>1</b>");
}
return timeString;
}
private static double convertSecondsTo(int seconds, int type) {
switch (type) {
case TIME_SECONDS:
return seconds;
case TIME_MINUTES:
return seconds / 60.0;
case TIME_HOURS:
return seconds / 3600.0;
case TIME_DAYS:
return seconds / 86400.0;
case TIME_MONTHS:
return seconds / 2592000.0;
case TIME_YEARS:
return seconds / 31536000.0;
default:
return 0;
}
}
/**
* Locale
* ***********************************************************************************************
*/
/**
* @return double with percentage sign
*/
public static String fmtPercentage(Double value) {
return fmtPercentage(value, 0);
}
public static String fmtPercentage(Double value, int point) {
// only retrieve the percentage format the first time
if (mCurrentPercentageFormat == null) {
mCurrentPercentageFormat = NumberFormat.getPercentInstance(Locale.getDefault());
}
mCurrentNumberFormat.setMaximumFractionDigits(point);
return mCurrentPercentageFormat.format(value);
}
/**
* @return a string with decimal separator according to current locale
*/
public static String fmtDouble(Double value) {
return fmtDouble(value, 1);
}
public static String fmtDouble(Double value, int point) {
// only retrieve the number format the first time
if (mCurrentNumberFormat == null) {
mCurrentNumberFormat = NumberFormat.getInstance(Locale.getDefault());
}
mCurrentNumberFormat.setMaximumFractionDigits(point);
return mCurrentNumberFormat.format(value);
}
/**
* HTML
* ***********************************************************************************************
*/
/**
* Strips a text from <style>...</style>, <script>...</script> and <_any_tag_> HTML tags.
* @param The HTML text to be cleaned.
* @return The text without the aforementioned tags.
*/
public static String stripHTML(String s) {
Matcher htmlMatcher = stylePattern.matcher(s);
s = htmlMatcher.replaceAll("");
htmlMatcher = scriptPattern.matcher(s);
s = htmlMatcher.replaceAll("");
htmlMatcher = tagPattern.matcher(s);
s = htmlMatcher.replaceAll("");
return entsToTxt(s);
}
/**
* Strip HTML but keep media filenames
*/
public static String stripHTMLMedia(String s) {
Matcher imgMatcher = imgPattern.matcher(s);
return stripHTML(imgMatcher.replaceAll(" $1 "));
}
private String minimizeHTML(String s) {
// TODO
return s;
}
/**
* Takes a string and replaces all the HTML symbols in it with their unescaped representation.
* This should only affect substrings of the form &something; and not tags.
* Internet rumour says that Html.fromHtml() doesn't cover all cases, but it doesn't get less
* vague than that.
* @param html The HTML escaped text
* @return The text with its HTML entities unescaped.
*/
private static String entsToTxt(String html) {
Matcher htmlEntities = htmlEntitiesPattern.matcher(html);
StringBuffer sb = new StringBuffer();
while (htmlEntities.find()) {
htmlEntities.appendReplacement(sb, Html.fromHtml(htmlEntities.group()).toString());
}
htmlEntities.appendTail(sb);
return sb.toString();
}
/**
* IDs
* ***********************************************************************************************
*/
public static String hexifyID(long id) {
return Long.toHexString(id);
}
public static long dehexifyID(String id) {
return Long.valueOf(id, 16);
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(int[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("(");
if (ids != null) {
String s = Arrays.toString(ids);
sb.append(s.substring(1, s.length() - 1));
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(long[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("(");
if (ids != null) {
String s = Arrays.toString(ids);
sb.append(s.substring(1, s.length() - 1));
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(Long[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("(");
if (ids != null) {
String s = Arrays.toString(ids);
sb.append(s.substring(1, s.length() - 1));
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static <T> String ids2str(List<T> ids) {
StringBuilder sb = new StringBuilder(512);
sb.append("(");
boolean isNotFirst = false;
for (T id : ids) {
if (isNotFirst) {
sb.append(", ");
} else {
isNotFirst = true;
}
sb.append(id);
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(JSONArray ids) {
StringBuilder str = new StringBuilder(512);
str.append("(");
if (ids != null) {
int len = ids.length();
for (int i = 0; i < len; i++) {
try {
if (i == (len - 1)) {
str.append(ids.get(i));
} else {
str.append(ids.get(i)).append(",");
}
} catch (JSONException e) {
Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
}
}
}
str.append(")");
return str.toString();
}
/** LIBANKI: not in libanki */
public static long[] arrayList2array(List<Long> list) {
long[] ar = new long[list.size()];
int i = 0;
for (long l : list) {
ar[i++] = l;
}
return ar;
}
/** Return a non-conflicting timestamp for table. */
public static long timestampID(AnkiDb db, String table) {
// be careful not to create multiple objects without flushing them, or they
// may share an ID.
long t = intNow(1000);
while (db.queryScalar("SELECT id FROM " + table + " WHERE id = " + t, false) != 0) {
t += 1;
}
return t;
}
/** Return the first safe ID to use. */
public static long maxID(AnkiDb db) {
long now = intNow(1000);
now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM cards"));
now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM notes"));
return now + 1;
}
// used in ankiweb
public static String base62(int num, String extra) {
String table = ALL_CHARACTERS + extra;
int len = table.length();
String buf = "";
int mod = 0;
while (num != 0) {
mod = num % len;
buf = buf + table.substring(mod, mod + 1);
num = num / len;
}
return buf;
}
// all printable characters minus quotes, backslash and separators
public static String base91(int num) {
return base62(num, "!#$%&()*+,-./:;<=>?@[]^_`{|}~");
}
/** return a base91-encoded 64bit random number */
public static String guid64() {
return base91((new Random()).nextInt((int) (Math.pow(2, 61) - 1)));
}
// public static JSONArray listToJSONArray(List<Object> list) {
// JSONArray jsonArray = new JSONArray();
//
// for (Object o : list) {
// jsonArray.put(o);
// }
//
// return jsonArray;
// }
//
//
// public static List<String> jsonArrayToListString(JSONArray jsonArray) throws JSONException {
// ArrayList<String> list = new ArrayList<String>();
//
// int len = jsonArray.length();
// for (int i = 0; i < len; i++) {
// list.add(jsonArray.getString(i));
// }
//
// return list;
// }
public static long[] jsonArrayToLongArray(JSONArray jsonArray) throws JSONException {
long[] ar = new long[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
ar[i] = jsonArray.getLong(i);
}
return ar;
}
/**
* Fields
* ***********************************************************************************************
*/
public static String joinFields(String[] list) {
StringBuilder result = new StringBuilder(128);
for (int i = 0; i < list.length - 1; i++) {
result.append(list[i]).append("\u001f");
}
if (list.length > 0) {
result.append(list[list.length - 1]);
}
return result.toString();
}
public static String[] splitFields(String fields) {
// do not drop empty fields
fields = fields.replaceAll("\\x1f\\x1f", "\u001f\u001e\u001f");
fields = fields.replaceAll("\\x1f$", "\u001f\u001e");
String[] split = fields.split("\\x1f");
for (int i = 0; i < split.length; i++) {
if (split[i].matches("\\x1e")) {
split[i] = "";
}
}
return split;
}
/**
* Checksums
* ***********************************************************************************************
*/
/**
- * MD5 checksum.
+ * SHA1 checksum.
* Equivalent to python sha1.hexdigest()
*
* @param data the string to generate hash from
* @return A string of length 40 containing the hexadecimal representation of the MD5 checksum of data.
*/
public static String checksum(String data) {
String result = "";
if (data != null) {
MessageDigest md = null;
byte[] digest = null;
try {
md = MessageDigest.getInstance("SHA");
digest = md.digest(data.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage());
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
Log.e(AnkiDroidApp.TAG, "Utils.checksum: " + e.getMessage());
e.printStackTrace();
}
BigInteger biginteger = new BigInteger(1, digest);
result = biginteger.toString(16);
// pad with zeros to length of 40 This method used to pad
// to the length of 32. As it turns out, sha1 has a digest
// size of 160 bits, leading to a hex digest size of 40,
// not 32.
if (result.length() < 40) {
String zeroes = "0000000000000000000000000000000000000000";
result = zeroes.substring(0, zeroes.length() - result.length()) + result;
}
}
return result;
}
/**
* @param data the string to generate hash from
* @return 32 bit unsigned number from first 8 digits of sha1 hash
*/
public static long fieldChecksum(String data) {
return Long.valueOf(checksum(data).substring(0, 8), 16);
}
/**
* Generate the SHA1 checksum of a file.
* @param file The file to be checked
* @return A string of length 32 containing the hexadecimal representation of the SHA1 checksum of the file's contents.
*/
public static String fileChecksum(String file) {
byte[] buffer = new byte[1024];
byte[] digest = null;
try {
InputStream fis = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("SHA1");
int numRead = 0;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
md.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
digest = md.digest();
} catch (FileNotFoundException e) {
Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: File not found.", e);
} catch (NoSuchAlgorithmException e) {
Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: No such algorithm.", e);
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: IO exception.", e);
}
BigInteger biginteger = new BigInteger(1, digest);
String result = biginteger.toString(16);
// pad with zeros to length of 40 - SHA1 is 160bit long
if (result.length() < 40) {
result = "0000000000000000000000000000000000000000".substring(0, 40 - result.length()) + result;
}
return result;
}
/** Replace HTML line break tags with new lines. */
public static String replaceLineBreak(String text) {
return text.replaceAll("<br(\\s*\\/*)>", "\n");
}
// /**
// * MD5 sum of file.
// * Equivalent to checksum(open(os.path.join(mdir, file), "rb").read()))
// *
// * @param path The full path to the file
// * @return A string of length 32 containing the hexadecimal representation of the MD5 checksum of the contents
// * of the file
// */
// public static String fileChecksum(String path) {
// byte[] bytes = null;
// try {
// File file = new File(path);
// if (file != null && file.isFile()) {
// bytes = new byte[(int)file.length()];
// FileInputStream fin = new FileInputStream(file);
// fin.read(bytes);
// }
// } catch (FileNotFoundException e) {
// Log.e(AnkiDroidApp.TAG, "Can't find file " + path + " to calculate its checksum");
// } catch (IOException e) {
// Log.e(AnkiDroidApp.TAG, "Can't read file " + path + " to calculate its checksum");
// }
// if (bytes == null) {
// Log.w(AnkiDroidApp.TAG, "File " + path + " appears to be empty");
// return "";
// }
// MessageDigest md = null;
// byte[] digest = null;
// try {
// md = MessageDigest.getInstance("MD5");
// digest = md.digest(bytes);
// } catch (NoSuchAlgorithmException e) {
// Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage());
// throw new RuntimeException(e);
// }
// BigInteger biginteger = new BigInteger(1, digest);
// String result = biginteger.toString(16);
// // pad with zeros to length of 32
// if (result.length() < 32) {
// result = "00000000000000000000000000000000".substring(0, 32 - result.length()) + result;
// }
// return result;
// }
/**
* Tempo files
* ***********************************************************************************************
*/
// tmpdir
// tmpfile
// namedtmp
/**
* Converts an InputStream to a String.
* @param is InputStream to convert
* @return String version of the InputStream
*/
public static String convertStreamToString(InputStream is) {
String contentOfMyInputStream = "";
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096);
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
contentOfMyInputStream = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return contentOfMyInputStream;
}
public static boolean unzip(String filename, String targetDirectory) {
try {
File dir = new File(targetDirectory);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
byte[] buf = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(filename));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String name = ze.getName();
Log.i(AnkiDroidApp.TAG, "uncompress " + name);
int n;
FileOutputStream fos = new FileOutputStream(targetDirectory + "/" + name);
while ((n = zis.read(buf, 0, 1024)) > -1) {
fos.write(buf, 0, n);
}
fos.close();
zis.closeEntry();
ze = zis.getNextEntry();
}
zis.close();
return true;
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "IOException on decompressing file " + filename);
return false;
}
}
/**
* Compress data.
* @param bytesToCompress is the byte array to compress.
* @return a compressed byte array.
* @throws java.io.IOException
*/
public static byte[] compress(byte[] bytesToCompress, int comp) throws IOException {
// Compressor with highest level of compression.
Deflater compressor = new Deflater(comp, true);
// Give the compressor the data to compress.
compressor.setInput(bytesToCompress);
compressor.finish();
// Create an expandable byte array to hold the compressed data.
// It is not necessary that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytesToCompress.length);
// Compress the data
byte[] buf = new byte[65536];
while (!compressor.finished()) {
bos.write(buf, 0, compressor.deflate(buf));
}
bos.close();
// Get the compressed data
return bos.toByteArray();
}
/**
* Utility method to write to a file.
* Throws the exception, so we can report it in syncing log
* @throws IOException
*/
public static void writeToFile(InputStream source, String destination) throws IOException {
Log.i(AnkiDroidApp.TAG, "Creating new file... = " + destination);
new File(destination).createNewFile();
long startTimeMillis = System.currentTimeMillis();
OutputStream output = new BufferedOutputStream(new FileOutputStream(destination));
// Transfer bytes, from source to destination.
byte[] buf = new byte[CHUNK_SIZE];
long sizeBytes = 0;
int len;
if (source == null) {
Log.e(AnkiDroidApp.TAG, "source is null!");
}
while ((len = source.read(buf)) >= 0) {
output.write(buf, 0, len);
sizeBytes += len;
}
long endTimeMillis = System.currentTimeMillis();
Log.i(AnkiDroidApp.TAG, "Finished writing!");
long durationSeconds = (endTimeMillis - startTimeMillis) / 1000;
long sizeKb = sizeBytes / 1024;
long speedKbSec = 0;
if (endTimeMillis != startTimeMillis) {
speedKbSec = sizeKb * 1000 / (endTimeMillis - startTimeMillis);
}
Log.d(AnkiDroidApp.TAG, "Utils.writeToFile: " + "Size: " + sizeKb + "Kb, " + "Duration: " + durationSeconds + "s, " + "Speed: " + speedKbSec + "Kb/s");
output.close();
}
// Print methods
public static void printJSONObject(JSONObject jsonObject) {
printJSONObject(jsonObject, "-", null);
}
public static void printJSONObject(JSONObject jsonObject, boolean writeToFile) {
BufferedWriter buff;
try {
buff = writeToFile ?
new BufferedWriter(new FileWriter("/sdcard/payloadAndroid.txt"), 8192) : null;
try {
printJSONObject(jsonObject, "-", buff);
} finally {
if (buff != null)
buff.close();
}
} catch (IOException ioe) {
Log.e(AnkiDroidApp.TAG, "IOException = " + ioe.getMessage());
}
}
private static void printJSONObject(JSONObject jsonObject, String indentation, BufferedWriter buff) {
try {
@SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys();
TreeSet<String> orderedKeysSet = new TreeSet<String>();
while (keys.hasNext()) {
orderedKeysSet.add(keys.next());
}
Iterator<String> orderedKeys = orderedKeysSet.iterator();
while (orderedKeys.hasNext()) {
String key = orderedKeys.next();
try {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
if (buff != null) {
buff.write(indentation + " " + key + " : ");
buff.newLine();
}
Log.i(AnkiDroidApp.TAG, " " + indentation + key + " : ");
printJSONObject((JSONObject) value, indentation + "-", buff);
} else {
if (buff != null) {
buff.write(indentation + " " + key + " = " + jsonObject.get(key).toString());
buff.newLine();
}
Log.i(AnkiDroidApp.TAG, " " + indentation + key + " = " + jsonObject.get(key).toString());
}
} catch (JSONException e) {
Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
}
}
} catch (IOException e1) {
Log.e(AnkiDroidApp.TAG, "IOException = " + e1.getMessage());
}
}
/*
public static void saveJSONObject(JSONObject jsonObject) throws IOException {
Log.i(AnkiDroidApp.TAG, "saveJSONObject");
BufferedWriter buff = new BufferedWriter(new FileWriter("/sdcard/jsonObjectAndroid.txt", true));
buff.write(jsonObject.toString());
buff.close();
}
*/
/**
* Returns 1 if true, 0 if false
*
* @param b The boolean to convert to integer
* @return 1 if b is true, 0 otherwise
*/
public static int booleanToInt(boolean b) {
return (b) ? 1 : 0;
}
/**
* Returns the effective date of the present moment.
* If the time is prior the cut-off time (9:00am by default as of 11/02/10) return yesterday,
* otherwise today
* Note that the Date class is java.sql.Date whose constructor sets hours, minutes etc to zero
*
* @param utcOffset The UTC offset in seconds we are going to use to determine today or yesterday.
* @return The date (with time set to 00:00:00) that corresponds to today in Anki terms
*/
public static Date genToday(double utcOffset) {
// The result is not adjusted for timezone anymore, following libanki model
// Timezone adjustment happens explicitly in Deck.updateCutoff(), but not in Deck.checkDailyStats()
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(System.currentTimeMillis() - (long) utcOffset * 1000l);
Date today = Date.valueOf(df.format(cal.getTime()));
return today;
}
public static void printDate(String name, double date) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis((long)date * 1000);
Log.d(AnkiDroidApp.TAG, "Value of " + name + ": " + cal.getTime().toGMTString());
}
public static String doubleToTime(double value) {
int time = (int) Math.round(value);
int seconds = time % 60;
int minutes = (time - seconds) / 60;
String formattedTime;
if (seconds < 10) {
formattedTime = Integer.toString(minutes) + ":0" + Integer.toString(seconds);
} else {
formattedTime = Integer.toString(minutes) + ":" + Integer.toString(seconds);
}
return formattedTime;
}
/**
* Returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1.
* @param date Date to convert to ordinal, since 01/01/01
* @return The ordinal representing the date
*/
public static int dateToOrdinal(Date date) {
// BigDate.toOrdinal returns the ordinal since 1970, so we add up the days from 01/01/01 to 1970
return BigDate.toOrdinal(date.getYear() + 1900, date.getMonth() + 1, date.getDate()) + DAYS_BEFORE_1970;
}
/**
* Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
* @param ordinal representing the days since 01/01/01
* @return Date converted from the ordinal
*/
public static Date ordinalToDate(int ordinal) {
return new Date((new BigDate(ordinal - DAYS_BEFORE_1970)).getLocalDate().getTime());
}
/**
* Indicates whether the specified action can be used as an intent. This method queries the package manager for
* installed packages that can respond to an intent with the specified action. If no suitable package is found, this
* method returns false.
* @param context The application's environment.
* @param action The Intent action to check for availability.
* @return True if an Intent with the specified action can be sent and responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
return isIntentAvailable(context, action, null);
}
public static boolean isIntentAvailable(Context context, String action, ComponentName componentName) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
intent.setComponent(componentName);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
/**
* @param mediaDir media directory path on SD card
* @return path converted to file URL, properly UTF-8 URL encoded
*/
public static String getBaseUrl(String mediaDir) {
// Use android.net.Uri class to ensure whole path is properly encoded
// File.toURL() does not work here, and URLEncoder class is not directly usable
// with existing slashes
if (mediaDir.length() != 0 && !mediaDir.equalsIgnoreCase("null")) {
Uri mediaDirUri = Uri.fromFile(new File(mediaDir));
return mediaDirUri.toString() +"/";
}
return "";
}
/**
* Take an array of Long and return an array of long
*
* @param array The input with type Long[]
* @return The output with type long[]
*/
public static long[] toPrimitive(Long[] array) {
long[] results = new long[array.length];
if (array != null) {
for (int i = 0; i < array.length; i++) {
results[i] = array[i].longValue();
}
}
return results;
}
public static long[] toPrimitive(Collection<Long> array) {
long[] results = new long[array.size()];
if (array != null) {
int i = 0;
for (Long item : array) {
results[i++] = item.longValue();
}
}
return results;
}
public static void updateProgressBars(View view, int x, int y) {
if (view == null) {
return;
}
if (view.getParent() instanceof LinearLayout) {
LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0, 0);
lparam.height = y;
lparam.width = x;
view.setLayoutParams(lparam);
} else if (view.getParent() instanceof FrameLayout) {
FrameLayout.LayoutParams lparam = new FrameLayout.LayoutParams(0, 0);
lparam.height = y;
lparam.width = x;
view.setLayoutParams(lparam);
}
}
/**
* Calculate the UTC offset
*/
public static double utcOffset() {
Calendar cal = Calendar.getInstance();
// 4am
return 4 * 60 * 60 - (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000;
}
/** Returns the filename without the extension. */
public static String removeExtension(String filename) {
int dotPosition = filename.lastIndexOf('.');
if (dotPosition == -1) {
return filename;
}
return filename.substring(0, dotPosition);
}
/** Removes any character that are not valid as deck names. */
public static String removeInvalidDeckNameCharacters(String name) {
if (name == null) { return null; }
// The only characters that we cannot absolutely allow to appear in the filename are the ones reserved in some
// file system. Currently these are \, /, and :, in order to cover Linux, OSX, and Windows.
return name.replaceAll("[:/\\\\]", "");
}
/** Returns a list of files for the installed custom fonts. */
public static List<AnkiFont> getCustomFonts(Context context) {
String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(context);
String fontsPath = deckPath + "/fonts/";
File fontsDir = new File(fontsPath);
int fontsCount = 0;
File[] fontsList = null;
if (fontsDir.exists() && fontsDir.isDirectory()) {
fontsCount = fontsDir.listFiles().length;
fontsList = fontsDir.listFiles();
}
String[] ankiDroidFonts = null;
try {
ankiDroidFonts = context.getAssets().list("fonts");
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "Error on retrieving ankidroid fonts: " + e);
}
List<AnkiFont> fonts = new ArrayList<AnkiFont>();
for (int i = 0; i < fontsCount; i++) {
AnkiFont font = AnkiFont.createAnkiFont(context, fontsList[i].getAbsolutePath(), false);
if (font != null) {
fonts.add(font);
}
}
for (int i = 0; i < ankiDroidFonts.length; i++) {
AnkiFont font = AnkiFont.createAnkiFont(context, ankiDroidFonts[i], true);
if (font != null) {
fonts.add(font);
}
}
return fonts;
}
/** Returns a list of apkg-files. */
public static List<File> getImportableDecks(Context context) {
String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(context);
File dir = new File(deckPath);
int deckCount = 0;
File[] deckList = null;
if (dir.exists() && dir.isDirectory()) {
deckList = dir.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
if (pathname.isFile() && pathname.getName().endsWith(".apkg")) {
return true;
}
return false;
}
});
deckCount = deckList.length;
}
List<File> decks = new ArrayList<File>();
for (int i = 0; i < deckCount; i++) {
decks.add(deckList[i]);
}
return decks;
}
/** Joins the given string values using the delimiter between them. */
public static String join(String delimiter, String... values) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (sb.length() != 0) {
sb.append(delimiter);
}
sb.append(value);
}
return sb.toString();
}
/**
* Simply copy a file to another location
* @param sourceFile The source file
* @param destFile The destination file, doesn't need to exist yet.
* @throws IOException
*/
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
}
| true | true | public static String fmtTimeSpan(int time, int format, boolean _short, boolean boldNumber) {
int type;
int unit = 99;
int point = 0;
if (Math.abs(time) < 60 || unit < 1) {
type = TIME_SECONDS;
} else if (Math.abs(time) < 3600 || unit < 2) {
type = TIME_MINUTES;
} else if (Math.abs(time) < 60 * 60 * 24 || unit < 3) {
type = TIME_HOURS;
} else if (Math.abs(time) < 60 * 60 * 24 * 29.5 || unit < 4) {
type = TIME_DAYS;
} else if (Math.abs(time) < 60 * 60 * 24 * 30 * 11.95 || unit < 5) {
type = TIME_MONTHS;
point = 1;
} else {
type = TIME_YEARS;
point = 1;
}
double ftime = convertSecondsTo(time, type);
int formatId;
if (false){//_short) {
//formatId = R.array.next_review_short;
} else {
switch (format) {
case TIME_FORMAT_IN:
if (Math.round(ftime * 10) == 10) {
formatId = R.array.next_review_in_s;
} else {
formatId = R.array.next_review_in_p;
}
break;
case TIME_FORMAT_BEFORE:
if (Math.round(ftime * 10) == 10) {
formatId = R.array.next_review_before_s;
} else {
formatId = R.array.next_review_before_p;
}
break;
case TIME_FORMAT_DEFAULT:
default:
if (Math.round(ftime * 10) == 10) {
formatId = R.array.next_review_s;
} else {
formatId = R.array.next_review_p;
}
break;
}
}
String timeString = String.format(AnkiDroidApp.getAppResources().getStringArray(formatId)[type], boldNumber ? "<b>" + fmtDouble(ftime, point) + "</b>" : fmtDouble(ftime, point));
if (boldNumber && time == 1) {
timeString = timeString.replace("1", "<b>1</b>");
}
return timeString;
}
private static double convertSecondsTo(int seconds, int type) {
switch (type) {
case TIME_SECONDS:
return seconds;
case TIME_MINUTES:
return seconds / 60.0;
case TIME_HOURS:
return seconds / 3600.0;
case TIME_DAYS:
return seconds / 86400.0;
case TIME_MONTHS:
return seconds / 2592000.0;
case TIME_YEARS:
return seconds / 31536000.0;
default:
return 0;
}
}
/**
* Locale
* ***********************************************************************************************
*/
/**
* @return double with percentage sign
*/
public static String fmtPercentage(Double value) {
return fmtPercentage(value, 0);
}
public static String fmtPercentage(Double value, int point) {
// only retrieve the percentage format the first time
if (mCurrentPercentageFormat == null) {
mCurrentPercentageFormat = NumberFormat.getPercentInstance(Locale.getDefault());
}
mCurrentNumberFormat.setMaximumFractionDigits(point);
return mCurrentPercentageFormat.format(value);
}
/**
* @return a string with decimal separator according to current locale
*/
public static String fmtDouble(Double value) {
return fmtDouble(value, 1);
}
public static String fmtDouble(Double value, int point) {
// only retrieve the number format the first time
if (mCurrentNumberFormat == null) {
mCurrentNumberFormat = NumberFormat.getInstance(Locale.getDefault());
}
mCurrentNumberFormat.setMaximumFractionDigits(point);
return mCurrentNumberFormat.format(value);
}
/**
* HTML
* ***********************************************************************************************
*/
/**
* Strips a text from <style>...</style>, <script>...</script> and <_any_tag_> HTML tags.
* @param The HTML text to be cleaned.
* @return The text without the aforementioned tags.
*/
public static String stripHTML(String s) {
Matcher htmlMatcher = stylePattern.matcher(s);
s = htmlMatcher.replaceAll("");
htmlMatcher = scriptPattern.matcher(s);
s = htmlMatcher.replaceAll("");
htmlMatcher = tagPattern.matcher(s);
s = htmlMatcher.replaceAll("");
return entsToTxt(s);
}
/**
* Strip HTML but keep media filenames
*/
public static String stripHTMLMedia(String s) {
Matcher imgMatcher = imgPattern.matcher(s);
return stripHTML(imgMatcher.replaceAll(" $1 "));
}
private String minimizeHTML(String s) {
// TODO
return s;
}
/**
* Takes a string and replaces all the HTML symbols in it with their unescaped representation.
* This should only affect substrings of the form &something; and not tags.
* Internet rumour says that Html.fromHtml() doesn't cover all cases, but it doesn't get less
* vague than that.
* @param html The HTML escaped text
* @return The text with its HTML entities unescaped.
*/
private static String entsToTxt(String html) {
Matcher htmlEntities = htmlEntitiesPattern.matcher(html);
StringBuffer sb = new StringBuffer();
while (htmlEntities.find()) {
htmlEntities.appendReplacement(sb, Html.fromHtml(htmlEntities.group()).toString());
}
htmlEntities.appendTail(sb);
return sb.toString();
}
/**
* IDs
* ***********************************************************************************************
*/
public static String hexifyID(long id) {
return Long.toHexString(id);
}
public static long dehexifyID(String id) {
return Long.valueOf(id, 16);
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(int[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("(");
if (ids != null) {
String s = Arrays.toString(ids);
sb.append(s.substring(1, s.length() - 1));
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(long[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("(");
if (ids != null) {
String s = Arrays.toString(ids);
sb.append(s.substring(1, s.length() - 1));
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(Long[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("(");
if (ids != null) {
String s = Arrays.toString(ids);
sb.append(s.substring(1, s.length() - 1));
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static <T> String ids2str(List<T> ids) {
StringBuilder sb = new StringBuilder(512);
sb.append("(");
boolean isNotFirst = false;
for (T id : ids) {
if (isNotFirst) {
sb.append(", ");
} else {
isNotFirst = true;
}
sb.append(id);
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(JSONArray ids) {
StringBuilder str = new StringBuilder(512);
str.append("(");
if (ids != null) {
int len = ids.length();
for (int i = 0; i < len; i++) {
try {
if (i == (len - 1)) {
str.append(ids.get(i));
} else {
str.append(ids.get(i)).append(",");
}
} catch (JSONException e) {
Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
}
}
}
str.append(")");
return str.toString();
}
/** LIBANKI: not in libanki */
public static long[] arrayList2array(List<Long> list) {
long[] ar = new long[list.size()];
int i = 0;
for (long l : list) {
ar[i++] = l;
}
return ar;
}
/** Return a non-conflicting timestamp for table. */
public static long timestampID(AnkiDb db, String table) {
// be careful not to create multiple objects without flushing them, or they
// may share an ID.
long t = intNow(1000);
while (db.queryScalar("SELECT id FROM " + table + " WHERE id = " + t, false) != 0) {
t += 1;
}
return t;
}
/** Return the first safe ID to use. */
public static long maxID(AnkiDb db) {
long now = intNow(1000);
now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM cards"));
now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM notes"));
return now + 1;
}
// used in ankiweb
public static String base62(int num, String extra) {
String table = ALL_CHARACTERS + extra;
int len = table.length();
String buf = "";
int mod = 0;
while (num != 0) {
mod = num % len;
buf = buf + table.substring(mod, mod + 1);
num = num / len;
}
return buf;
}
// all printable characters minus quotes, backslash and separators
public static String base91(int num) {
return base62(num, "!#$%&()*+,-./:;<=>?@[]^_`{|}~");
}
/** return a base91-encoded 64bit random number */
public static String guid64() {
return base91((new Random()).nextInt((int) (Math.pow(2, 61) - 1)));
}
// public static JSONArray listToJSONArray(List<Object> list) {
// JSONArray jsonArray = new JSONArray();
//
// for (Object o : list) {
// jsonArray.put(o);
// }
//
// return jsonArray;
// }
//
//
// public static List<String> jsonArrayToListString(JSONArray jsonArray) throws JSONException {
// ArrayList<String> list = new ArrayList<String>();
//
// int len = jsonArray.length();
// for (int i = 0; i < len; i++) {
// list.add(jsonArray.getString(i));
// }
//
// return list;
// }
public static long[] jsonArrayToLongArray(JSONArray jsonArray) throws JSONException {
long[] ar = new long[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
ar[i] = jsonArray.getLong(i);
}
return ar;
}
/**
* Fields
* ***********************************************************************************************
*/
public static String joinFields(String[] list) {
StringBuilder result = new StringBuilder(128);
for (int i = 0; i < list.length - 1; i++) {
result.append(list[i]).append("\u001f");
}
if (list.length > 0) {
result.append(list[list.length - 1]);
}
return result.toString();
}
public static String[] splitFields(String fields) {
// do not drop empty fields
fields = fields.replaceAll("\\x1f\\x1f", "\u001f\u001e\u001f");
fields = fields.replaceAll("\\x1f$", "\u001f\u001e");
String[] split = fields.split("\\x1f");
for (int i = 0; i < split.length; i++) {
if (split[i].matches("\\x1e")) {
split[i] = "";
}
}
return split;
}
/**
* Checksums
* ***********************************************************************************************
*/
/**
* MD5 checksum.
* Equivalent to python sha1.hexdigest()
*
* @param data the string to generate hash from
* @return A string of length 40 containing the hexadecimal representation of the MD5 checksum of data.
*/
public static String checksum(String data) {
String result = "";
if (data != null) {
MessageDigest md = null;
byte[] digest = null;
try {
md = MessageDigest.getInstance("SHA");
digest = md.digest(data.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage());
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
Log.e(AnkiDroidApp.TAG, "Utils.checksum: " + e.getMessage());
e.printStackTrace();
}
BigInteger biginteger = new BigInteger(1, digest);
result = biginteger.toString(16);
// pad with zeros to length of 40 This method used to pad
// to the length of 32. As it turns out, sha1 has a digest
// size of 160 bits, leading to a hex digest size of 40,
// not 32.
if (result.length() < 40) {
String zeroes = "0000000000000000000000000000000000000000";
result = zeroes.substring(0, zeroes.length() - result.length()) + result;
}
}
return result;
}
/**
* @param data the string to generate hash from
* @return 32 bit unsigned number from first 8 digits of sha1 hash
*/
public static long fieldChecksum(String data) {
return Long.valueOf(checksum(data).substring(0, 8), 16);
}
/**
* Generate the SHA1 checksum of a file.
* @param file The file to be checked
* @return A string of length 32 containing the hexadecimal representation of the SHA1 checksum of the file's contents.
*/
public static String fileChecksum(String file) {
byte[] buffer = new byte[1024];
byte[] digest = null;
try {
InputStream fis = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("SHA1");
int numRead = 0;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
md.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
digest = md.digest();
} catch (FileNotFoundException e) {
Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: File not found.", e);
} catch (NoSuchAlgorithmException e) {
Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: No such algorithm.", e);
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: IO exception.", e);
}
BigInteger biginteger = new BigInteger(1, digest);
String result = biginteger.toString(16);
// pad with zeros to length of 40 - SHA1 is 160bit long
if (result.length() < 40) {
result = "0000000000000000000000000000000000000000".substring(0, 40 - result.length()) + result;
}
return result;
}
/** Replace HTML line break tags with new lines. */
public static String replaceLineBreak(String text) {
return text.replaceAll("<br(\\s*\\/*)>", "\n");
}
// /**
// * MD5 sum of file.
// * Equivalent to checksum(open(os.path.join(mdir, file), "rb").read()))
// *
// * @param path The full path to the file
// * @return A string of length 32 containing the hexadecimal representation of the MD5 checksum of the contents
// * of the file
// */
// public static String fileChecksum(String path) {
// byte[] bytes = null;
// try {
// File file = new File(path);
// if (file != null && file.isFile()) {
// bytes = new byte[(int)file.length()];
// FileInputStream fin = new FileInputStream(file);
// fin.read(bytes);
// }
// } catch (FileNotFoundException e) {
// Log.e(AnkiDroidApp.TAG, "Can't find file " + path + " to calculate its checksum");
// } catch (IOException e) {
// Log.e(AnkiDroidApp.TAG, "Can't read file " + path + " to calculate its checksum");
// }
// if (bytes == null) {
// Log.w(AnkiDroidApp.TAG, "File " + path + " appears to be empty");
// return "";
// }
// MessageDigest md = null;
// byte[] digest = null;
// try {
// md = MessageDigest.getInstance("MD5");
// digest = md.digest(bytes);
// } catch (NoSuchAlgorithmException e) {
// Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage());
// throw new RuntimeException(e);
// }
// BigInteger biginteger = new BigInteger(1, digest);
// String result = biginteger.toString(16);
// // pad with zeros to length of 32
// if (result.length() < 32) {
// result = "00000000000000000000000000000000".substring(0, 32 - result.length()) + result;
// }
// return result;
// }
/**
* Tempo files
* ***********************************************************************************************
*/
// tmpdir
// tmpfile
// namedtmp
/**
* Converts an InputStream to a String.
* @param is InputStream to convert
* @return String version of the InputStream
*/
public static String convertStreamToString(InputStream is) {
String contentOfMyInputStream = "";
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096);
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
contentOfMyInputStream = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return contentOfMyInputStream;
}
public static boolean unzip(String filename, String targetDirectory) {
try {
File dir = new File(targetDirectory);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
byte[] buf = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(filename));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String name = ze.getName();
Log.i(AnkiDroidApp.TAG, "uncompress " + name);
int n;
FileOutputStream fos = new FileOutputStream(targetDirectory + "/" + name);
while ((n = zis.read(buf, 0, 1024)) > -1) {
fos.write(buf, 0, n);
}
fos.close();
zis.closeEntry();
ze = zis.getNextEntry();
}
zis.close();
return true;
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "IOException on decompressing file " + filename);
return false;
}
}
/**
* Compress data.
* @param bytesToCompress is the byte array to compress.
* @return a compressed byte array.
* @throws java.io.IOException
*/
public static byte[] compress(byte[] bytesToCompress, int comp) throws IOException {
// Compressor with highest level of compression.
Deflater compressor = new Deflater(comp, true);
// Give the compressor the data to compress.
compressor.setInput(bytesToCompress);
compressor.finish();
// Create an expandable byte array to hold the compressed data.
// It is not necessary that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytesToCompress.length);
// Compress the data
byte[] buf = new byte[65536];
while (!compressor.finished()) {
bos.write(buf, 0, compressor.deflate(buf));
}
bos.close();
// Get the compressed data
return bos.toByteArray();
}
/**
* Utility method to write to a file.
* Throws the exception, so we can report it in syncing log
* @throws IOException
*/
public static void writeToFile(InputStream source, String destination) throws IOException {
Log.i(AnkiDroidApp.TAG, "Creating new file... = " + destination);
new File(destination).createNewFile();
long startTimeMillis = System.currentTimeMillis();
OutputStream output = new BufferedOutputStream(new FileOutputStream(destination));
// Transfer bytes, from source to destination.
byte[] buf = new byte[CHUNK_SIZE];
long sizeBytes = 0;
int len;
if (source == null) {
Log.e(AnkiDroidApp.TAG, "source is null!");
}
while ((len = source.read(buf)) >= 0) {
output.write(buf, 0, len);
sizeBytes += len;
}
long endTimeMillis = System.currentTimeMillis();
Log.i(AnkiDroidApp.TAG, "Finished writing!");
long durationSeconds = (endTimeMillis - startTimeMillis) / 1000;
long sizeKb = sizeBytes / 1024;
long speedKbSec = 0;
if (endTimeMillis != startTimeMillis) {
speedKbSec = sizeKb * 1000 / (endTimeMillis - startTimeMillis);
}
Log.d(AnkiDroidApp.TAG, "Utils.writeToFile: " + "Size: " + sizeKb + "Kb, " + "Duration: " + durationSeconds + "s, " + "Speed: " + speedKbSec + "Kb/s");
output.close();
}
// Print methods
public static void printJSONObject(JSONObject jsonObject) {
printJSONObject(jsonObject, "-", null);
}
public static void printJSONObject(JSONObject jsonObject, boolean writeToFile) {
BufferedWriter buff;
try {
buff = writeToFile ?
new BufferedWriter(new FileWriter("/sdcard/payloadAndroid.txt"), 8192) : null;
try {
printJSONObject(jsonObject, "-", buff);
} finally {
if (buff != null)
buff.close();
}
} catch (IOException ioe) {
Log.e(AnkiDroidApp.TAG, "IOException = " + ioe.getMessage());
}
}
private static void printJSONObject(JSONObject jsonObject, String indentation, BufferedWriter buff) {
try {
@SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys();
TreeSet<String> orderedKeysSet = new TreeSet<String>();
while (keys.hasNext()) {
orderedKeysSet.add(keys.next());
}
Iterator<String> orderedKeys = orderedKeysSet.iterator();
while (orderedKeys.hasNext()) {
String key = orderedKeys.next();
try {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
if (buff != null) {
buff.write(indentation + " " + key + " : ");
buff.newLine();
}
Log.i(AnkiDroidApp.TAG, " " + indentation + key + " : ");
printJSONObject((JSONObject) value, indentation + "-", buff);
} else {
if (buff != null) {
buff.write(indentation + " " + key + " = " + jsonObject.get(key).toString());
buff.newLine();
}
Log.i(AnkiDroidApp.TAG, " " + indentation + key + " = " + jsonObject.get(key).toString());
}
} catch (JSONException e) {
Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
}
}
} catch (IOException e1) {
Log.e(AnkiDroidApp.TAG, "IOException = " + e1.getMessage());
}
}
/*
public static void saveJSONObject(JSONObject jsonObject) throws IOException {
Log.i(AnkiDroidApp.TAG, "saveJSONObject");
BufferedWriter buff = new BufferedWriter(new FileWriter("/sdcard/jsonObjectAndroid.txt", true));
buff.write(jsonObject.toString());
buff.close();
}
*/
/**
* Returns 1 if true, 0 if false
*
* @param b The boolean to convert to integer
* @return 1 if b is true, 0 otherwise
*/
public static int booleanToInt(boolean b) {
return (b) ? 1 : 0;
}
/**
* Returns the effective date of the present moment.
* If the time is prior the cut-off time (9:00am by default as of 11/02/10) return yesterday,
* otherwise today
* Note that the Date class is java.sql.Date whose constructor sets hours, minutes etc to zero
*
* @param utcOffset The UTC offset in seconds we are going to use to determine today or yesterday.
* @return The date (with time set to 00:00:00) that corresponds to today in Anki terms
*/
public static Date genToday(double utcOffset) {
// The result is not adjusted for timezone anymore, following libanki model
// Timezone adjustment happens explicitly in Deck.updateCutoff(), but not in Deck.checkDailyStats()
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(System.currentTimeMillis() - (long) utcOffset * 1000l);
Date today = Date.valueOf(df.format(cal.getTime()));
return today;
}
public static void printDate(String name, double date) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis((long)date * 1000);
Log.d(AnkiDroidApp.TAG, "Value of " + name + ": " + cal.getTime().toGMTString());
}
public static String doubleToTime(double value) {
int time = (int) Math.round(value);
int seconds = time % 60;
int minutes = (time - seconds) / 60;
String formattedTime;
if (seconds < 10) {
formattedTime = Integer.toString(minutes) + ":0" + Integer.toString(seconds);
} else {
formattedTime = Integer.toString(minutes) + ":" + Integer.toString(seconds);
}
return formattedTime;
}
/**
* Returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1.
* @param date Date to convert to ordinal, since 01/01/01
* @return The ordinal representing the date
*/
public static int dateToOrdinal(Date date) {
// BigDate.toOrdinal returns the ordinal since 1970, so we add up the days from 01/01/01 to 1970
return BigDate.toOrdinal(date.getYear() + 1900, date.getMonth() + 1, date.getDate()) + DAYS_BEFORE_1970;
}
/**
* Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
* @param ordinal representing the days since 01/01/01
* @return Date converted from the ordinal
*/
public static Date ordinalToDate(int ordinal) {
return new Date((new BigDate(ordinal - DAYS_BEFORE_1970)).getLocalDate().getTime());
}
/**
* Indicates whether the specified action can be used as an intent. This method queries the package manager for
* installed packages that can respond to an intent with the specified action. If no suitable package is found, this
* method returns false.
* @param context The application's environment.
* @param action The Intent action to check for availability.
* @return True if an Intent with the specified action can be sent and responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
return isIntentAvailable(context, action, null);
}
public static boolean isIntentAvailable(Context context, String action, ComponentName componentName) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
intent.setComponent(componentName);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
/**
* @param mediaDir media directory path on SD card
* @return path converted to file URL, properly UTF-8 URL encoded
*/
public static String getBaseUrl(String mediaDir) {
// Use android.net.Uri class to ensure whole path is properly encoded
// File.toURL() does not work here, and URLEncoder class is not directly usable
// with existing slashes
if (mediaDir.length() != 0 && !mediaDir.equalsIgnoreCase("null")) {
Uri mediaDirUri = Uri.fromFile(new File(mediaDir));
return mediaDirUri.toString() +"/";
}
return "";
}
/**
* Take an array of Long and return an array of long
*
* @param array The input with type Long[]
* @return The output with type long[]
*/
public static long[] toPrimitive(Long[] array) {
long[] results = new long[array.length];
if (array != null) {
for (int i = 0; i < array.length; i++) {
results[i] = array[i].longValue();
}
}
return results;
}
public static long[] toPrimitive(Collection<Long> array) {
long[] results = new long[array.size()];
if (array != null) {
int i = 0;
for (Long item : array) {
results[i++] = item.longValue();
}
}
return results;
}
public static void updateProgressBars(View view, int x, int y) {
if (view == null) {
return;
}
if (view.getParent() instanceof LinearLayout) {
LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0, 0);
lparam.height = y;
lparam.width = x;
view.setLayoutParams(lparam);
} else if (view.getParent() instanceof FrameLayout) {
FrameLayout.LayoutParams lparam = new FrameLayout.LayoutParams(0, 0);
lparam.height = y;
lparam.width = x;
view.setLayoutParams(lparam);
}
}
/**
* Calculate the UTC offset
*/
public static double utcOffset() {
Calendar cal = Calendar.getInstance();
// 4am
return 4 * 60 * 60 - (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000;
}
/** Returns the filename without the extension. */
public static String removeExtension(String filename) {
int dotPosition = filename.lastIndexOf('.');
if (dotPosition == -1) {
return filename;
}
return filename.substring(0, dotPosition);
}
/** Removes any character that are not valid as deck names. */
public static String removeInvalidDeckNameCharacters(String name) {
if (name == null) { return null; }
// The only characters that we cannot absolutely allow to appear in the filename are the ones reserved in some
// file system. Currently these are \, /, and :, in order to cover Linux, OSX, and Windows.
return name.replaceAll("[:/\\\\]", "");
}
/** Returns a list of files for the installed custom fonts. */
public static List<AnkiFont> getCustomFonts(Context context) {
String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(context);
String fontsPath = deckPath + "/fonts/";
File fontsDir = new File(fontsPath);
int fontsCount = 0;
File[] fontsList = null;
if (fontsDir.exists() && fontsDir.isDirectory()) {
fontsCount = fontsDir.listFiles().length;
fontsList = fontsDir.listFiles();
}
String[] ankiDroidFonts = null;
try {
ankiDroidFonts = context.getAssets().list("fonts");
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "Error on retrieving ankidroid fonts: " + e);
}
List<AnkiFont> fonts = new ArrayList<AnkiFont>();
for (int i = 0; i < fontsCount; i++) {
AnkiFont font = AnkiFont.createAnkiFont(context, fontsList[i].getAbsolutePath(), false);
if (font != null) {
fonts.add(font);
}
}
for (int i = 0; i < ankiDroidFonts.length; i++) {
AnkiFont font = AnkiFont.createAnkiFont(context, ankiDroidFonts[i], true);
if (font != null) {
fonts.add(font);
}
}
return fonts;
}
/** Returns a list of apkg-files. */
public static List<File> getImportableDecks(Context context) {
String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(context);
File dir = new File(deckPath);
int deckCount = 0;
File[] deckList = null;
if (dir.exists() && dir.isDirectory()) {
deckList = dir.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
if (pathname.isFile() && pathname.getName().endsWith(".apkg")) {
return true;
}
return false;
}
});
deckCount = deckList.length;
}
List<File> decks = new ArrayList<File>();
for (int i = 0; i < deckCount; i++) {
decks.add(deckList[i]);
}
return decks;
}
/** Joins the given string values using the delimiter between them. */
public static String join(String delimiter, String... values) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (sb.length() != 0) {
sb.append(delimiter);
}
sb.append(value);
}
return sb.toString();
}
/**
* Simply copy a file to another location
* @param sourceFile The source file
* @param destFile The destination file, doesn't need to exist yet.
* @throws IOException
*/
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
}
| public static String fmtTimeSpan(int time, int format, boolean _short, boolean boldNumber) {
int type;
int unit = 99;
int point = 0;
if (Math.abs(time) < 60 || unit < 1) {
type = TIME_SECONDS;
} else if (Math.abs(time) < 3600 || unit < 2) {
type = TIME_MINUTES;
} else if (Math.abs(time) < 60 * 60 * 24 || unit < 3) {
type = TIME_HOURS;
} else if (Math.abs(time) < 60 * 60 * 24 * 29.5 || unit < 4) {
type = TIME_DAYS;
} else if (Math.abs(time) < 60 * 60 * 24 * 30 * 11.95 || unit < 5) {
type = TIME_MONTHS;
point = 1;
} else {
type = TIME_YEARS;
point = 1;
}
double ftime = convertSecondsTo(time, type);
int formatId;
if (false){//_short) {
//formatId = R.array.next_review_short;
} else {
switch (format) {
case TIME_FORMAT_IN:
if (Math.round(ftime * 10) == 10) {
formatId = R.array.next_review_in_s;
} else {
formatId = R.array.next_review_in_p;
}
break;
case TIME_FORMAT_BEFORE:
if (Math.round(ftime * 10) == 10) {
formatId = R.array.next_review_before_s;
} else {
formatId = R.array.next_review_before_p;
}
break;
case TIME_FORMAT_DEFAULT:
default:
if (Math.round(ftime * 10) == 10) {
formatId = R.array.next_review_s;
} else {
formatId = R.array.next_review_p;
}
break;
}
}
String timeString = String.format(AnkiDroidApp.getAppResources().getStringArray(formatId)[type], boldNumber ? "<b>" + fmtDouble(ftime, point) + "</b>" : fmtDouble(ftime, point));
if (boldNumber && time == 1) {
timeString = timeString.replace("1", "<b>1</b>");
}
return timeString;
}
private static double convertSecondsTo(int seconds, int type) {
switch (type) {
case TIME_SECONDS:
return seconds;
case TIME_MINUTES:
return seconds / 60.0;
case TIME_HOURS:
return seconds / 3600.0;
case TIME_DAYS:
return seconds / 86400.0;
case TIME_MONTHS:
return seconds / 2592000.0;
case TIME_YEARS:
return seconds / 31536000.0;
default:
return 0;
}
}
/**
* Locale
* ***********************************************************************************************
*/
/**
* @return double with percentage sign
*/
public static String fmtPercentage(Double value) {
return fmtPercentage(value, 0);
}
public static String fmtPercentage(Double value, int point) {
// only retrieve the percentage format the first time
if (mCurrentPercentageFormat == null) {
mCurrentPercentageFormat = NumberFormat.getPercentInstance(Locale.getDefault());
}
mCurrentNumberFormat.setMaximumFractionDigits(point);
return mCurrentPercentageFormat.format(value);
}
/**
* @return a string with decimal separator according to current locale
*/
public static String fmtDouble(Double value) {
return fmtDouble(value, 1);
}
public static String fmtDouble(Double value, int point) {
// only retrieve the number format the first time
if (mCurrentNumberFormat == null) {
mCurrentNumberFormat = NumberFormat.getInstance(Locale.getDefault());
}
mCurrentNumberFormat.setMaximumFractionDigits(point);
return mCurrentNumberFormat.format(value);
}
/**
* HTML
* ***********************************************************************************************
*/
/**
* Strips a text from <style>...</style>, <script>...</script> and <_any_tag_> HTML tags.
* @param The HTML text to be cleaned.
* @return The text without the aforementioned tags.
*/
public static String stripHTML(String s) {
Matcher htmlMatcher = stylePattern.matcher(s);
s = htmlMatcher.replaceAll("");
htmlMatcher = scriptPattern.matcher(s);
s = htmlMatcher.replaceAll("");
htmlMatcher = tagPattern.matcher(s);
s = htmlMatcher.replaceAll("");
return entsToTxt(s);
}
/**
* Strip HTML but keep media filenames
*/
public static String stripHTMLMedia(String s) {
Matcher imgMatcher = imgPattern.matcher(s);
return stripHTML(imgMatcher.replaceAll(" $1 "));
}
private String minimizeHTML(String s) {
// TODO
return s;
}
/**
* Takes a string and replaces all the HTML symbols in it with their unescaped representation.
* This should only affect substrings of the form &something; and not tags.
* Internet rumour says that Html.fromHtml() doesn't cover all cases, but it doesn't get less
* vague than that.
* @param html The HTML escaped text
* @return The text with its HTML entities unescaped.
*/
private static String entsToTxt(String html) {
Matcher htmlEntities = htmlEntitiesPattern.matcher(html);
StringBuffer sb = new StringBuffer();
while (htmlEntities.find()) {
htmlEntities.appendReplacement(sb, Html.fromHtml(htmlEntities.group()).toString());
}
htmlEntities.appendTail(sb);
return sb.toString();
}
/**
* IDs
* ***********************************************************************************************
*/
public static String hexifyID(long id) {
return Long.toHexString(id);
}
public static long dehexifyID(String id) {
return Long.valueOf(id, 16);
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(int[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("(");
if (ids != null) {
String s = Arrays.toString(ids);
sb.append(s.substring(1, s.length() - 1));
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(long[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("(");
if (ids != null) {
String s = Arrays.toString(ids);
sb.append(s.substring(1, s.length() - 1));
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(Long[] ids) {
StringBuilder sb = new StringBuilder();
sb.append("(");
if (ids != null) {
String s = Arrays.toString(ids);
sb.append(s.substring(1, s.length() - 1));
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static <T> String ids2str(List<T> ids) {
StringBuilder sb = new StringBuilder(512);
sb.append("(");
boolean isNotFirst = false;
for (T id : ids) {
if (isNotFirst) {
sb.append(", ");
} else {
isNotFirst = true;
}
sb.append(id);
}
sb.append(")");
return sb.toString();
}
/** Given a list of integers, return a string '(int1,int2,...)'. */
public static String ids2str(JSONArray ids) {
StringBuilder str = new StringBuilder(512);
str.append("(");
if (ids != null) {
int len = ids.length();
for (int i = 0; i < len; i++) {
try {
if (i == (len - 1)) {
str.append(ids.get(i));
} else {
str.append(ids.get(i)).append(",");
}
} catch (JSONException e) {
Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
}
}
}
str.append(")");
return str.toString();
}
/** LIBANKI: not in libanki */
public static long[] arrayList2array(List<Long> list) {
long[] ar = new long[list.size()];
int i = 0;
for (long l : list) {
ar[i++] = l;
}
return ar;
}
/** Return a non-conflicting timestamp for table. */
public static long timestampID(AnkiDb db, String table) {
// be careful not to create multiple objects without flushing them, or they
// may share an ID.
long t = intNow(1000);
while (db.queryScalar("SELECT id FROM " + table + " WHERE id = " + t, false) != 0) {
t += 1;
}
return t;
}
/** Return the first safe ID to use. */
public static long maxID(AnkiDb db) {
long now = intNow(1000);
now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM cards"));
now = Math.max(now, db.queryLongScalar("SELECT MAX(id) FROM notes"));
return now + 1;
}
// used in ankiweb
public static String base62(int num, String extra) {
String table = ALL_CHARACTERS + extra;
int len = table.length();
String buf = "";
int mod = 0;
while (num != 0) {
mod = num % len;
buf = buf + table.substring(mod, mod + 1);
num = num / len;
}
return buf;
}
// all printable characters minus quotes, backslash and separators
public static String base91(int num) {
return base62(num, "!#$%&()*+,-./:;<=>?@[]^_`{|}~");
}
/** return a base91-encoded 64bit random number */
public static String guid64() {
return base91((new Random()).nextInt((int) (Math.pow(2, 61) - 1)));
}
// public static JSONArray listToJSONArray(List<Object> list) {
// JSONArray jsonArray = new JSONArray();
//
// for (Object o : list) {
// jsonArray.put(o);
// }
//
// return jsonArray;
// }
//
//
// public static List<String> jsonArrayToListString(JSONArray jsonArray) throws JSONException {
// ArrayList<String> list = new ArrayList<String>();
//
// int len = jsonArray.length();
// for (int i = 0; i < len; i++) {
// list.add(jsonArray.getString(i));
// }
//
// return list;
// }
public static long[] jsonArrayToLongArray(JSONArray jsonArray) throws JSONException {
long[] ar = new long[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
ar[i] = jsonArray.getLong(i);
}
return ar;
}
/**
* Fields
* ***********************************************************************************************
*/
public static String joinFields(String[] list) {
StringBuilder result = new StringBuilder(128);
for (int i = 0; i < list.length - 1; i++) {
result.append(list[i]).append("\u001f");
}
if (list.length > 0) {
result.append(list[list.length - 1]);
}
return result.toString();
}
public static String[] splitFields(String fields) {
// do not drop empty fields
fields = fields.replaceAll("\\x1f\\x1f", "\u001f\u001e\u001f");
fields = fields.replaceAll("\\x1f$", "\u001f\u001e");
String[] split = fields.split("\\x1f");
for (int i = 0; i < split.length; i++) {
if (split[i].matches("\\x1e")) {
split[i] = "";
}
}
return split;
}
/**
* Checksums
* ***********************************************************************************************
*/
/**
* SHA1 checksum.
* Equivalent to python sha1.hexdigest()
*
* @param data the string to generate hash from
* @return A string of length 40 containing the hexadecimal representation of the MD5 checksum of data.
*/
public static String checksum(String data) {
String result = "";
if (data != null) {
MessageDigest md = null;
byte[] digest = null;
try {
md = MessageDigest.getInstance("SHA");
digest = md.digest(data.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage());
throw new RuntimeException(e);
} catch (UnsupportedEncodingException e) {
Log.e(AnkiDroidApp.TAG, "Utils.checksum: " + e.getMessage());
e.printStackTrace();
}
BigInteger biginteger = new BigInteger(1, digest);
result = biginteger.toString(16);
// pad with zeros to length of 40 This method used to pad
// to the length of 32. As it turns out, sha1 has a digest
// size of 160 bits, leading to a hex digest size of 40,
// not 32.
if (result.length() < 40) {
String zeroes = "0000000000000000000000000000000000000000";
result = zeroes.substring(0, zeroes.length() - result.length()) + result;
}
}
return result;
}
/**
* @param data the string to generate hash from
* @return 32 bit unsigned number from first 8 digits of sha1 hash
*/
public static long fieldChecksum(String data) {
return Long.valueOf(checksum(data).substring(0, 8), 16);
}
/**
* Generate the SHA1 checksum of a file.
* @param file The file to be checked
* @return A string of length 32 containing the hexadecimal representation of the SHA1 checksum of the file's contents.
*/
public static String fileChecksum(String file) {
byte[] buffer = new byte[1024];
byte[] digest = null;
try {
InputStream fis = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("SHA1");
int numRead = 0;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
md.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
digest = md.digest();
} catch (FileNotFoundException e) {
Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: File not found.", e);
} catch (NoSuchAlgorithmException e) {
Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: No such algorithm.", e);
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "Utils.fileChecksum: IO exception.", e);
}
BigInteger biginteger = new BigInteger(1, digest);
String result = biginteger.toString(16);
// pad with zeros to length of 40 - SHA1 is 160bit long
if (result.length() < 40) {
result = "0000000000000000000000000000000000000000".substring(0, 40 - result.length()) + result;
}
return result;
}
/** Replace HTML line break tags with new lines. */
public static String replaceLineBreak(String text) {
return text.replaceAll("<br(\\s*\\/*)>", "\n");
}
// /**
// * MD5 sum of file.
// * Equivalent to checksum(open(os.path.join(mdir, file), "rb").read()))
// *
// * @param path The full path to the file
// * @return A string of length 32 containing the hexadecimal representation of the MD5 checksum of the contents
// * of the file
// */
// public static String fileChecksum(String path) {
// byte[] bytes = null;
// try {
// File file = new File(path);
// if (file != null && file.isFile()) {
// bytes = new byte[(int)file.length()];
// FileInputStream fin = new FileInputStream(file);
// fin.read(bytes);
// }
// } catch (FileNotFoundException e) {
// Log.e(AnkiDroidApp.TAG, "Can't find file " + path + " to calculate its checksum");
// } catch (IOException e) {
// Log.e(AnkiDroidApp.TAG, "Can't read file " + path + " to calculate its checksum");
// }
// if (bytes == null) {
// Log.w(AnkiDroidApp.TAG, "File " + path + " appears to be empty");
// return "";
// }
// MessageDigest md = null;
// byte[] digest = null;
// try {
// md = MessageDigest.getInstance("MD5");
// digest = md.digest(bytes);
// } catch (NoSuchAlgorithmException e) {
// Log.e(AnkiDroidApp.TAG, "Utils.checksum: No such algorithm. " + e.getMessage());
// throw new RuntimeException(e);
// }
// BigInteger biginteger = new BigInteger(1, digest);
// String result = biginteger.toString(16);
// // pad with zeros to length of 32
// if (result.length() < 32) {
// result = "00000000000000000000000000000000".substring(0, 32 - result.length()) + result;
// }
// return result;
// }
/**
* Tempo files
* ***********************************************************************************************
*/
// tmpdir
// tmpfile
// namedtmp
/**
* Converts an InputStream to a String.
* @param is InputStream to convert
* @return String version of the InputStream
*/
public static String convertStreamToString(InputStream is) {
String contentOfMyInputStream = "";
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096);
String line;
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
contentOfMyInputStream = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return contentOfMyInputStream;
}
public static boolean unzip(String filename, String targetDirectory) {
try {
File dir = new File(targetDirectory);
if (!dir.exists() || !dir.isDirectory()) {
dir.mkdirs();
}
byte[] buf = new byte[1024];
ZipInputStream zis = new ZipInputStream(new FileInputStream(filename));
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String name = ze.getName();
Log.i(AnkiDroidApp.TAG, "uncompress " + name);
int n;
FileOutputStream fos = new FileOutputStream(targetDirectory + "/" + name);
while ((n = zis.read(buf, 0, 1024)) > -1) {
fos.write(buf, 0, n);
}
fos.close();
zis.closeEntry();
ze = zis.getNextEntry();
}
zis.close();
return true;
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "IOException on decompressing file " + filename);
return false;
}
}
/**
* Compress data.
* @param bytesToCompress is the byte array to compress.
* @return a compressed byte array.
* @throws java.io.IOException
*/
public static byte[] compress(byte[] bytesToCompress, int comp) throws IOException {
// Compressor with highest level of compression.
Deflater compressor = new Deflater(comp, true);
// Give the compressor the data to compress.
compressor.setInput(bytesToCompress);
compressor.finish();
// Create an expandable byte array to hold the compressed data.
// It is not necessary that the compressed data will be smaller than
// the uncompressed data.
ByteArrayOutputStream bos = new ByteArrayOutputStream(bytesToCompress.length);
// Compress the data
byte[] buf = new byte[65536];
while (!compressor.finished()) {
bos.write(buf, 0, compressor.deflate(buf));
}
bos.close();
// Get the compressed data
return bos.toByteArray();
}
/**
* Utility method to write to a file.
* Throws the exception, so we can report it in syncing log
* @throws IOException
*/
public static void writeToFile(InputStream source, String destination) throws IOException {
Log.i(AnkiDroidApp.TAG, "Creating new file... = " + destination);
new File(destination).createNewFile();
long startTimeMillis = System.currentTimeMillis();
OutputStream output = new BufferedOutputStream(new FileOutputStream(destination));
// Transfer bytes, from source to destination.
byte[] buf = new byte[CHUNK_SIZE];
long sizeBytes = 0;
int len;
if (source == null) {
Log.e(AnkiDroidApp.TAG, "source is null!");
}
while ((len = source.read(buf)) >= 0) {
output.write(buf, 0, len);
sizeBytes += len;
}
long endTimeMillis = System.currentTimeMillis();
Log.i(AnkiDroidApp.TAG, "Finished writing!");
long durationSeconds = (endTimeMillis - startTimeMillis) / 1000;
long sizeKb = sizeBytes / 1024;
long speedKbSec = 0;
if (endTimeMillis != startTimeMillis) {
speedKbSec = sizeKb * 1000 / (endTimeMillis - startTimeMillis);
}
Log.d(AnkiDroidApp.TAG, "Utils.writeToFile: " + "Size: " + sizeKb + "Kb, " + "Duration: " + durationSeconds + "s, " + "Speed: " + speedKbSec + "Kb/s");
output.close();
}
// Print methods
public static void printJSONObject(JSONObject jsonObject) {
printJSONObject(jsonObject, "-", null);
}
public static void printJSONObject(JSONObject jsonObject, boolean writeToFile) {
BufferedWriter buff;
try {
buff = writeToFile ?
new BufferedWriter(new FileWriter("/sdcard/payloadAndroid.txt"), 8192) : null;
try {
printJSONObject(jsonObject, "-", buff);
} finally {
if (buff != null)
buff.close();
}
} catch (IOException ioe) {
Log.e(AnkiDroidApp.TAG, "IOException = " + ioe.getMessage());
}
}
private static void printJSONObject(JSONObject jsonObject, String indentation, BufferedWriter buff) {
try {
@SuppressWarnings("unchecked") Iterator<String> keys = (Iterator<String>) jsonObject.keys();
TreeSet<String> orderedKeysSet = new TreeSet<String>();
while (keys.hasNext()) {
orderedKeysSet.add(keys.next());
}
Iterator<String> orderedKeys = orderedKeysSet.iterator();
while (orderedKeys.hasNext()) {
String key = orderedKeys.next();
try {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
if (buff != null) {
buff.write(indentation + " " + key + " : ");
buff.newLine();
}
Log.i(AnkiDroidApp.TAG, " " + indentation + key + " : ");
printJSONObject((JSONObject) value, indentation + "-", buff);
} else {
if (buff != null) {
buff.write(indentation + " " + key + " = " + jsonObject.get(key).toString());
buff.newLine();
}
Log.i(AnkiDroidApp.TAG, " " + indentation + key + " = " + jsonObject.get(key).toString());
}
} catch (JSONException e) {
Log.e(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
}
}
} catch (IOException e1) {
Log.e(AnkiDroidApp.TAG, "IOException = " + e1.getMessage());
}
}
/*
public static void saveJSONObject(JSONObject jsonObject) throws IOException {
Log.i(AnkiDroidApp.TAG, "saveJSONObject");
BufferedWriter buff = new BufferedWriter(new FileWriter("/sdcard/jsonObjectAndroid.txt", true));
buff.write(jsonObject.toString());
buff.close();
}
*/
/**
* Returns 1 if true, 0 if false
*
* @param b The boolean to convert to integer
* @return 1 if b is true, 0 otherwise
*/
public static int booleanToInt(boolean b) {
return (b) ? 1 : 0;
}
/**
* Returns the effective date of the present moment.
* If the time is prior the cut-off time (9:00am by default as of 11/02/10) return yesterday,
* otherwise today
* Note that the Date class is java.sql.Date whose constructor sets hours, minutes etc to zero
*
* @param utcOffset The UTC offset in seconds we are going to use to determine today or yesterday.
* @return The date (with time set to 00:00:00) that corresponds to today in Anki terms
*/
public static Date genToday(double utcOffset) {
// The result is not adjusted for timezone anymore, following libanki model
// Timezone adjustment happens explicitly in Deck.updateCutoff(), but not in Deck.checkDailyStats()
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis(System.currentTimeMillis() - (long) utcOffset * 1000l);
Date today = Date.valueOf(df.format(cal.getTime()));
return today;
}
public static void printDate(String name, double date) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.setTimeInMillis((long)date * 1000);
Log.d(AnkiDroidApp.TAG, "Value of " + name + ": " + cal.getTime().toGMTString());
}
public static String doubleToTime(double value) {
int time = (int) Math.round(value);
int seconds = time % 60;
int minutes = (time - seconds) / 60;
String formattedTime;
if (seconds < 10) {
formattedTime = Integer.toString(minutes) + ":0" + Integer.toString(seconds);
} else {
formattedTime = Integer.toString(minutes) + ":" + Integer.toString(seconds);
}
return formattedTime;
}
/**
* Returns the proleptic Gregorian ordinal of the date, where January 1 of year 1 has ordinal 1.
* @param date Date to convert to ordinal, since 01/01/01
* @return The ordinal representing the date
*/
public static int dateToOrdinal(Date date) {
// BigDate.toOrdinal returns the ordinal since 1970, so we add up the days from 01/01/01 to 1970
return BigDate.toOrdinal(date.getYear() + 1900, date.getMonth() + 1, date.getDate()) + DAYS_BEFORE_1970;
}
/**
* Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1.
* @param ordinal representing the days since 01/01/01
* @return Date converted from the ordinal
*/
public static Date ordinalToDate(int ordinal) {
return new Date((new BigDate(ordinal - DAYS_BEFORE_1970)).getLocalDate().getTime());
}
/**
* Indicates whether the specified action can be used as an intent. This method queries the package manager for
* installed packages that can respond to an intent with the specified action. If no suitable package is found, this
* method returns false.
* @param context The application's environment.
* @param action The Intent action to check for availability.
* @return True if an Intent with the specified action can be sent and responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
return isIntentAvailable(context, action, null);
}
public static boolean isIntentAvailable(Context context, String action, ComponentName componentName) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
intent.setComponent(componentName);
List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
/**
* @param mediaDir media directory path on SD card
* @return path converted to file URL, properly UTF-8 URL encoded
*/
public static String getBaseUrl(String mediaDir) {
// Use android.net.Uri class to ensure whole path is properly encoded
// File.toURL() does not work here, and URLEncoder class is not directly usable
// with existing slashes
if (mediaDir.length() != 0 && !mediaDir.equalsIgnoreCase("null")) {
Uri mediaDirUri = Uri.fromFile(new File(mediaDir));
return mediaDirUri.toString() +"/";
}
return "";
}
/**
* Take an array of Long and return an array of long
*
* @param array The input with type Long[]
* @return The output with type long[]
*/
public static long[] toPrimitive(Long[] array) {
long[] results = new long[array.length];
if (array != null) {
for (int i = 0; i < array.length; i++) {
results[i] = array[i].longValue();
}
}
return results;
}
public static long[] toPrimitive(Collection<Long> array) {
long[] results = new long[array.size()];
if (array != null) {
int i = 0;
for (Long item : array) {
results[i++] = item.longValue();
}
}
return results;
}
public static void updateProgressBars(View view, int x, int y) {
if (view == null) {
return;
}
if (view.getParent() instanceof LinearLayout) {
LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(0, 0);
lparam.height = y;
lparam.width = x;
view.setLayoutParams(lparam);
} else if (view.getParent() instanceof FrameLayout) {
FrameLayout.LayoutParams lparam = new FrameLayout.LayoutParams(0, 0);
lparam.height = y;
lparam.width = x;
view.setLayoutParams(lparam);
}
}
/**
* Calculate the UTC offset
*/
public static double utcOffset() {
Calendar cal = Calendar.getInstance();
// 4am
return 4 * 60 * 60 - (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000;
}
/** Returns the filename without the extension. */
public static String removeExtension(String filename) {
int dotPosition = filename.lastIndexOf('.');
if (dotPosition == -1) {
return filename;
}
return filename.substring(0, dotPosition);
}
/** Removes any character that are not valid as deck names. */
public static String removeInvalidDeckNameCharacters(String name) {
if (name == null) { return null; }
// The only characters that we cannot absolutely allow to appear in the filename are the ones reserved in some
// file system. Currently these are \, /, and :, in order to cover Linux, OSX, and Windows.
return name.replaceAll("[:/\\\\]", "");
}
/** Returns a list of files for the installed custom fonts. */
public static List<AnkiFont> getCustomFonts(Context context) {
String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(context);
String fontsPath = deckPath + "/fonts/";
File fontsDir = new File(fontsPath);
int fontsCount = 0;
File[] fontsList = null;
if (fontsDir.exists() && fontsDir.isDirectory()) {
fontsCount = fontsDir.listFiles().length;
fontsList = fontsDir.listFiles();
}
String[] ankiDroidFonts = null;
try {
ankiDroidFonts = context.getAssets().list("fonts");
} catch (IOException e) {
Log.e(AnkiDroidApp.TAG, "Error on retrieving ankidroid fonts: " + e);
}
List<AnkiFont> fonts = new ArrayList<AnkiFont>();
for (int i = 0; i < fontsCount; i++) {
AnkiFont font = AnkiFont.createAnkiFont(context, fontsList[i].getAbsolutePath(), false);
if (font != null) {
fonts.add(font);
}
}
for (int i = 0; i < ankiDroidFonts.length; i++) {
AnkiFont font = AnkiFont.createAnkiFont(context, ankiDroidFonts[i], true);
if (font != null) {
fonts.add(font);
}
}
return fonts;
}
/** Returns a list of apkg-files. */
public static List<File> getImportableDecks(Context context) {
String deckPath = AnkiDroidApp.getCurrentAnkiDroidDirectory(context);
File dir = new File(deckPath);
int deckCount = 0;
File[] deckList = null;
if (dir.exists() && dir.isDirectory()) {
deckList = dir.listFiles(new FileFilter(){
@Override
public boolean accept(File pathname) {
if (pathname.isFile() && pathname.getName().endsWith(".apkg")) {
return true;
}
return false;
}
});
deckCount = deckList.length;
}
List<File> decks = new ArrayList<File>();
for (int i = 0; i < deckCount; i++) {
decks.add(deckList[i]);
}
return decks;
}
/** Joins the given string values using the delimiter between them. */
public static String join(String delimiter, String... values) {
StringBuilder sb = new StringBuilder();
for (String value : values) {
if (sb.length() != 0) {
sb.append(delimiter);
}
sb.append(value);
}
return sb.toString();
}
/**
* Simply copy a file to another location
* @param sourceFile The source file
* @param destFile The destination file, doesn't need to exist yet.
* @throws IOException
*/
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
}
|
diff --git a/plugins/org.eclipse.dltk.ruby.core/src/org/eclipse/dltk/ruby/core/RubyPlugin.java b/plugins/org.eclipse.dltk.ruby.core/src/org/eclipse/dltk/ruby/core/RubyPlugin.java
index bf918b62..d62922f8 100644
--- a/plugins/org.eclipse.dltk.ruby.core/src/org/eclipse/dltk/ruby/core/RubyPlugin.java
+++ b/plugins/org.eclipse.dltk.ruby.core/src/org/eclipse/dltk/ruby/core/RubyPlugin.java
@@ -1,173 +1,178 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.ruby.core;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Plugin;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.dltk.core.DLTKCore;
import org.eclipse.dltk.core.ISourceModule;
import org.eclipse.dltk.core.ModelException;
import org.eclipse.dltk.core.search.IDLTKSearchConstants;
import org.eclipse.dltk.core.search.IDLTKSearchScope;
import org.eclipse.dltk.core.search.SearchEngine;
import org.eclipse.dltk.core.search.SearchPattern;
import org.eclipse.dltk.core.search.TypeNameRequestor;
import org.eclipse.dltk.ruby.internal.parser.mixin.RubyMixinModel;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class RubyPlugin extends Plugin {
// The plug-in ID
public static final String PLUGIN_ID = "org.eclipse.dltk.ruby.core";
public static final boolean DUMP_EXCEPTIONS_TO_CONSOLE = Boolean.valueOf(
Platform.getDebugOption("org.eclipse.dltk.ruby.core/dumpErrorsToConsole"))
.booleanValue();
// The shared instance
private static RubyPlugin plugin;
/**
* The constructor
*/
public RubyPlugin() {
plugin = this;
}
/*
* (non-Javadoc)
* @see org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext)
*/
public void start(BundleContext context) throws Exception {
super.start(context);
}
/*
* (non-Javadoc)
* @see org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
RubyMixinModel.getRawInstance().stop();
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static RubyPlugin getDefault() {
return plugin;
}
public static void log(Exception ex) {
if (DLTKCore.DEBUG || DUMP_EXCEPTIONS_TO_CONSOLE)
ex.printStackTrace();
String message = ex.getMessage();
if (message == null)
message = "(no message)";
getDefault().getLog().log(new Status(Status.ERROR,
PLUGIN_ID, 0, message, ex));
}
public static void log(String message) {
if (DLTKCore.DEBUG || DUMP_EXCEPTIONS_TO_CONSOLE)
System.out.println(message);
getDefault().getLog().log(new Status(Status.WARNING,
PLUGIN_ID, 0, message, null));
}
/**
* Initializes DLTKCore internal structures to allow subsequent operations (such
* as the ones that need a resolved classpath) to run full speed. A client may
* choose to call this method in a background thread early after the workspace
* has started so that the initialization is transparent to the user.
* <p>
* However calling this method is optional. Services will lazily perform
* initialization when invoked. This is only a way to reduce initialization
* overhead on user actions, if it can be performed before at some
* appropriate moment.
* </p><p>
* This initialization runs accross all Java projects in the workspace. Thus the
* workspace root scheduling rule is used during this operation.
* </p><p>
* This method may return before the initialization is complete. The
* initialization will then continue in a background thread.
* </p><p>
* This method can be called concurrently.
* </p>
*
* @param monitor a progress monitor, or <code>null</code> if progress
* reporting and cancellation are not desired
* @exception CoreException if the initialization fails,
* the status of the exception indicates the reason of the failure
* @since 3.1
*/
public static void initializeAfterLoad(IProgressMonitor monitor) throws CoreException {
try {
if (monitor != null) monitor.beginTask("Initializing DLTK Ruby", 100);
// dummy query for waiting until the indexes are ready
SearchEngine engine = new SearchEngine();
IDLTKSearchScope scope = SearchEngine.createWorkspaceScope(RubyLanguageToolkit.getDefault());
try {
if (monitor != null)
monitor.subTask("Initializing search engine");
engine.searchAllTypeNames(
null,
SearchPattern.R_EXACT_MATCH,
"!@$#!@".toCharArray(), //$NON-NLS-1$
SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE,
IDLTKSearchConstants.TYPE,
scope,
new TypeNameRequestor() {
public void acceptType(
int modifiers,
char[] packageName,
char[] simpleTypeName,
char[][] enclosingTypeNames,
String path) {
// no type to accept
}
},
// will not activate index query caches if indexes are not ready, since it would take to long
// to wait until indexes are fully rebuild
IDLTKSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH,
monitor == null ? null : new SubProgressMonitor(monitor, 49) // 49% of the time is spent in the dummy search
);
- /*String[] searchMixinPatterns = SearchEngine.searchMixinPatterns("$*", RubyLanguageToolkit.getDefault());
- ISourceModule[] searchMixinSources = SearchEngine.searchMixinSources("$*", RubyLanguageToolkit.getDefault());
- System.out.println("ruby initialized 0==" + searchMixinPatterns.length + "," + searchMixinSources.length);*/
+ String[] mainClasses = new String[] {"Object", "String", "Fixnum", "Array", "Regexp"};
+ for (int i = 0; i < mainClasses.length; i++) {
+ RubyMixinModel.getInstance().createRubyElement(mainClasses[i]);
+ RubyMixinModel.getInstance().createRubyElement(mainClasses[i] + "%");
+ monitor.worked(10);
+ }
+ RubyMixinModel.getRawInstance().find("$*");
+ monitor.worked(10);
} catch (ModelException e) {
// /search failed: ignore
} catch (OperationCanceledException e) {
if (monitor != null && monitor.isCanceled())
throw e;
// else indexes were not ready: catch the exception so that jars are still refreshed
}
} finally {
if (monitor != null) monitor.done();
}
}
}
| false | true | public static void initializeAfterLoad(IProgressMonitor monitor) throws CoreException {
try {
if (monitor != null) monitor.beginTask("Initializing DLTK Ruby", 100);
// dummy query for waiting until the indexes are ready
SearchEngine engine = new SearchEngine();
IDLTKSearchScope scope = SearchEngine.createWorkspaceScope(RubyLanguageToolkit.getDefault());
try {
if (monitor != null)
monitor.subTask("Initializing search engine");
engine.searchAllTypeNames(
null,
SearchPattern.R_EXACT_MATCH,
"!@$#!@".toCharArray(), //$NON-NLS-1$
SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE,
IDLTKSearchConstants.TYPE,
scope,
new TypeNameRequestor() {
public void acceptType(
int modifiers,
char[] packageName,
char[] simpleTypeName,
char[][] enclosingTypeNames,
String path) {
// no type to accept
}
},
// will not activate index query caches if indexes are not ready, since it would take to long
// to wait until indexes are fully rebuild
IDLTKSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH,
monitor == null ? null : new SubProgressMonitor(monitor, 49) // 49% of the time is spent in the dummy search
);
/*String[] searchMixinPatterns = SearchEngine.searchMixinPatterns("$*", RubyLanguageToolkit.getDefault());
ISourceModule[] searchMixinSources = SearchEngine.searchMixinSources("$*", RubyLanguageToolkit.getDefault());
System.out.println("ruby initialized 0==" + searchMixinPatterns.length + "," + searchMixinSources.length);*/
} catch (ModelException e) {
// /search failed: ignore
} catch (OperationCanceledException e) {
if (monitor != null && monitor.isCanceled())
throw e;
// else indexes were not ready: catch the exception so that jars are still refreshed
}
} finally {
if (monitor != null) monitor.done();
}
}
| public static void initializeAfterLoad(IProgressMonitor monitor) throws CoreException {
try {
if (monitor != null) monitor.beginTask("Initializing DLTK Ruby", 100);
// dummy query for waiting until the indexes are ready
SearchEngine engine = new SearchEngine();
IDLTKSearchScope scope = SearchEngine.createWorkspaceScope(RubyLanguageToolkit.getDefault());
try {
if (monitor != null)
monitor.subTask("Initializing search engine");
engine.searchAllTypeNames(
null,
SearchPattern.R_EXACT_MATCH,
"!@$#!@".toCharArray(), //$NON-NLS-1$
SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE,
IDLTKSearchConstants.TYPE,
scope,
new TypeNameRequestor() {
public void acceptType(
int modifiers,
char[] packageName,
char[] simpleTypeName,
char[][] enclosingTypeNames,
String path) {
// no type to accept
}
},
// will not activate index query caches if indexes are not ready, since it would take to long
// to wait until indexes are fully rebuild
IDLTKSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH,
monitor == null ? null : new SubProgressMonitor(monitor, 49) // 49% of the time is spent in the dummy search
);
String[] mainClasses = new String[] {"Object", "String", "Fixnum", "Array", "Regexp"};
for (int i = 0; i < mainClasses.length; i++) {
RubyMixinModel.getInstance().createRubyElement(mainClasses[i]);
RubyMixinModel.getInstance().createRubyElement(mainClasses[i] + "%");
monitor.worked(10);
}
RubyMixinModel.getRawInstance().find("$*");
monitor.worked(10);
} catch (ModelException e) {
// /search failed: ignore
} catch (OperationCanceledException e) {
if (monitor != null && monitor.isCanceled())
throw e;
// else indexes were not ready: catch the exception so that jars are still refreshed
}
} finally {
if (monitor != null) monitor.done();
}
}
|
diff --git a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFDebugTask.java b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFDebugTask.java
index c0f62346f..609c99c6e 100644
--- a/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFDebugTask.java
+++ b/plugins/org.eclipse.tcf.debug.ui/src/org/eclipse/tcf/internal/debug/ui/model/TCFDebugTask.java
@@ -1,59 +1,59 @@
/*******************************************************************************
* Copyright (c) 2007, 2011 Wind River Systems, Inc. and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Wind River Systems - initial API and implementation
*******************************************************************************/
package org.eclipse.tcf.internal.debug.ui.model;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugException;
import org.eclipse.tcf.internal.debug.ui.Activator;
import org.eclipse.tcf.protocol.IChannel;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.util.TCFTask;
/**
* An extension of TCFTask class that adds support for throwing DebugException.
*/
public abstract class TCFDebugTask<V> extends TCFTask<V> {
public TCFDebugTask() {
}
public TCFDebugTask(IChannel channel) {
super(channel);
}
public synchronized V getD() throws DebugException {
assert !Protocol.isDispatchThread();
while (!isDone()) {
try {
wait();
}
catch (InterruptedException x) {
throw new DebugException(new Status(
IStatus.ERROR, Activator.PLUGIN_ID, DebugException.REQUEST_FAILED,
- "Debugger requiest interrupted", x));
+ "Debugger request interrupted", x));
}
}
assert isDone();
Throwable x = getError();
if (x instanceof DebugException) throw (DebugException)x;
if (x != null) throw new DebugException(new Status(
IStatus.ERROR, Activator.PLUGIN_ID, DebugException.REQUEST_FAILED,
- "Debugger requiest failed", x));
+ "Debugger request failed", x));
return getResult();
}
public void error(String msg) {
error(new DebugException(new Status(
IStatus.ERROR, Activator.PLUGIN_ID, DebugException.REQUEST_FAILED,
msg, null)));
}
}
| false | true | public synchronized V getD() throws DebugException {
assert !Protocol.isDispatchThread();
while (!isDone()) {
try {
wait();
}
catch (InterruptedException x) {
throw new DebugException(new Status(
IStatus.ERROR, Activator.PLUGIN_ID, DebugException.REQUEST_FAILED,
"Debugger requiest interrupted", x));
}
}
assert isDone();
Throwable x = getError();
if (x instanceof DebugException) throw (DebugException)x;
if (x != null) throw new DebugException(new Status(
IStatus.ERROR, Activator.PLUGIN_ID, DebugException.REQUEST_FAILED,
"Debugger requiest failed", x));
return getResult();
}
| public synchronized V getD() throws DebugException {
assert !Protocol.isDispatchThread();
while (!isDone()) {
try {
wait();
}
catch (InterruptedException x) {
throw new DebugException(new Status(
IStatus.ERROR, Activator.PLUGIN_ID, DebugException.REQUEST_FAILED,
"Debugger request interrupted", x));
}
}
assert isDone();
Throwable x = getError();
if (x instanceof DebugException) throw (DebugException)x;
if (x != null) throw new DebugException(new Status(
IStatus.ERROR, Activator.PLUGIN_ID, DebugException.REQUEST_FAILED,
"Debugger request failed", x));
return getResult();
}
|
diff --git a/Model/src/java/fr/cg95/cvq/util/mail/impl/MailService.java b/Model/src/java/fr/cg95/cvq/util/mail/impl/MailService.java
index 6e2e4bdd7..bd992b173 100644
--- a/Model/src/java/fr/cg95/cvq/util/mail/impl/MailService.java
+++ b/Model/src/java/fr/cg95/cvq/util/mail/impl/MailService.java
@@ -1,103 +1,104 @@
package fr.cg95.cvq.util.mail.impl;
import java.util.HashMap;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.log4j.Logger;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.exception.CvqModelException;
import fr.cg95.cvq.security.SecurityContext;
import fr.cg95.cvq.util.mail.IMailService;
public final class MailService implements IMailService {
private static Logger logger = Logger.getLogger(MailService.class);
private String systemEmail;
private JavaMailSender mailSender;
@Override
public void send(final String from, final String to, final String[] cc, final String subject,
final String body, final Map<String, byte[]> attachments)
throws CvqException {
if (to == null)
throw new CvqModelException("email.to_is_required");
logger.debug("send() sending mail with " + subject);
try {
mailSender.send(new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage)
throws MessagingException {
MimeMessageHelper message =
new MimeMessageHelper(mimeMessage, true, "UTF-8");
if (from != null && !from.equals(""))
message.setFrom(from);
else {
if (SecurityContext.getCurrentSite().getAdminEmail() != null && !SecurityContext.getCurrentSite().getAdminEmail().trim().isEmpty()) {
message.setFrom(SecurityContext.getCurrentSite().getAdminEmail());
} else {
message.setFrom(systemEmail);
}
}
if (!to.equals(""))
message.setTo(to);
else {
if (SecurityContext.getCurrentSite().getAdminEmail() != null && !SecurityContext.getCurrentSite().getAdminEmail().trim().isEmpty()) {
message.setTo(SecurityContext.getCurrentSite().getAdminEmail());
} else {
message.setTo(systemEmail);
}
}
message.setSubject(subject);
message.setText(body);
if (cc != null && cc.length > 0)
message.setCc(cc);
if (attachments != null) {
for (Map.Entry<String, byte[]> attachment : attachments.entrySet()) {
- ByteArrayResource byteArrayResource =
- new ByteArrayResource(attachment.getValue());
- message.addAttachment(attachment.getKey(), byteArrayResource);
+ if (attachment.getValue() != null) {
+ message.addAttachment(attachment.getKey(),
+ new ByteArrayResource(attachment.getValue()));
+ }
}
}
}
});
} catch (MailException ex) {
logger.error(ex.getMessage());
throw new CvqException("Unable to send email message");
}
}
@Override
public void send(final String from, final String to, final String[] cc, final String subject,
final String body, final byte[] attachment, final String attachmentName)
throws CvqException {
Map<String, byte[]> attachments = new HashMap<String, byte[]>(1);
attachments.put(attachmentName, attachment);
send(from, to, cc, subject, body, attachments);
}
@Override
public void send(final String from, final String to, final String[] cc, final String subject,
final String body) throws CvqException {
send(from, to, cc, subject, body, null);
}
public void setMailSender(JavaMailSender mailSender) {
this.mailSender = mailSender;
}
public void setSystemEmail(String systemEmail) {
this.systemEmail = systemEmail;
}
}
| true | true | public void send(final String from, final String to, final String[] cc, final String subject,
final String body, final Map<String, byte[]> attachments)
throws CvqException {
if (to == null)
throw new CvqModelException("email.to_is_required");
logger.debug("send() sending mail with " + subject);
try {
mailSender.send(new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage)
throws MessagingException {
MimeMessageHelper message =
new MimeMessageHelper(mimeMessage, true, "UTF-8");
if (from != null && !from.equals(""))
message.setFrom(from);
else {
if (SecurityContext.getCurrentSite().getAdminEmail() != null && !SecurityContext.getCurrentSite().getAdminEmail().trim().isEmpty()) {
message.setFrom(SecurityContext.getCurrentSite().getAdminEmail());
} else {
message.setFrom(systemEmail);
}
}
if (!to.equals(""))
message.setTo(to);
else {
if (SecurityContext.getCurrentSite().getAdminEmail() != null && !SecurityContext.getCurrentSite().getAdminEmail().trim().isEmpty()) {
message.setTo(SecurityContext.getCurrentSite().getAdminEmail());
} else {
message.setTo(systemEmail);
}
}
message.setSubject(subject);
message.setText(body);
if (cc != null && cc.length > 0)
message.setCc(cc);
if (attachments != null) {
for (Map.Entry<String, byte[]> attachment : attachments.entrySet()) {
ByteArrayResource byteArrayResource =
new ByteArrayResource(attachment.getValue());
message.addAttachment(attachment.getKey(), byteArrayResource);
}
}
}
});
} catch (MailException ex) {
logger.error(ex.getMessage());
throw new CvqException("Unable to send email message");
}
}
| public void send(final String from, final String to, final String[] cc, final String subject,
final String body, final Map<String, byte[]> attachments)
throws CvqException {
if (to == null)
throw new CvqModelException("email.to_is_required");
logger.debug("send() sending mail with " + subject);
try {
mailSender.send(new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage)
throws MessagingException {
MimeMessageHelper message =
new MimeMessageHelper(mimeMessage, true, "UTF-8");
if (from != null && !from.equals(""))
message.setFrom(from);
else {
if (SecurityContext.getCurrentSite().getAdminEmail() != null && !SecurityContext.getCurrentSite().getAdminEmail().trim().isEmpty()) {
message.setFrom(SecurityContext.getCurrentSite().getAdminEmail());
} else {
message.setFrom(systemEmail);
}
}
if (!to.equals(""))
message.setTo(to);
else {
if (SecurityContext.getCurrentSite().getAdminEmail() != null && !SecurityContext.getCurrentSite().getAdminEmail().trim().isEmpty()) {
message.setTo(SecurityContext.getCurrentSite().getAdminEmail());
} else {
message.setTo(systemEmail);
}
}
message.setSubject(subject);
message.setText(body);
if (cc != null && cc.length > 0)
message.setCc(cc);
if (attachments != null) {
for (Map.Entry<String, byte[]> attachment : attachments.entrySet()) {
if (attachment.getValue() != null) {
message.addAttachment(attachment.getKey(),
new ByteArrayResource(attachment.getValue()));
}
}
}
}
});
} catch (MailException ex) {
logger.error(ex.getMessage());
throw new CvqException("Unable to send email message");
}
}
|
diff --git a/AndroidVkSdk/src/com/perm/kate/api/Photo.java b/AndroidVkSdk/src/com/perm/kate/api/Photo.java
index fa74136..42704ea 100644
--- a/AndroidVkSdk/src/com/perm/kate/api/Photo.java
+++ b/AndroidVkSdk/src/com/perm/kate/api/Photo.java
@@ -1,110 +1,110 @@
package com.perm.kate.api;
import java.io.Serializable;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Photo implements Serializable {
private static final long serialVersionUID = 1L;
public long pid;
public long aid;
public String owner_id;
public String src;//photo_130
public String src_small;//photo_75
public String src_big;//photo_604
public String src_xbig;//photo_807
public String src_xxbig;//photo_1280
public String src_xxxbig;//photo_2560
public String phototext;
public long created;
public Integer like_count;
public Boolean user_likes;
public Integer comments_count;
public Integer tags_count;
public Boolean can_comment;
public int width;//0 means value is unknown
public int height;//0 means value is unknown
public String access_key;
public String user_id; //for group
public static Photo parse(JSONObject o) throws NumberFormatException, JSONException{
Photo p = new Photo();
p.pid = o.getLong("id");
p.aid = o.optLong("album_id");
p.owner_id = o.getString("owner_id");
p.src = o.optString("photo_130");
p.src_small = o.optString("photo_75");
p.src_big = o.optString("photo_604");
p.src_xbig = o.optString("photo_807");
p.src_xxbig = o.optString("photo_1280");
p.src_xxxbig = o.optString("photo_2560");
p.phototext = Api.unescape(o.optString("text"));
- p.created = o.optLong("created");
+ p.created = o.optLong("date"); //date instead created for api v 5.0 and higher
p.user_id = o.optString("user_id");
if (o.has("likes")) {
JSONObject jlikes = o.getJSONObject("likes");
p.like_count = jlikes.optInt("count");
p.user_likes = jlikes.optInt("user_likes")==1;
}
if (o.has("comments")) {
JSONObject jcomments = o.getJSONObject("comments");
p.comments_count = jcomments.optInt("count");
}
if (o.has("tags")) {
JSONObject jtags = o.getJSONObject("tags");
p.tags_count = jtags.optInt("count");
}
if (o.has("can_comment"))
p.can_comment = o.optInt("can_comment")==1;
p.width = o.optInt("width");
p.height = o.optInt("height");
p.access_key=o.optString("access_key");
return p;
}
public Photo(){
}
public Photo(Long id, String owner_id, String src, String src_big){
this.pid=id;
this.owner_id=owner_id;
this.src=src;
this.src_big=src_big;
}
public static Photo parseCounts(JSONObject o) throws NumberFormatException, JSONException{
Photo p = new Photo();
JSONArray pid_array = o.optJSONArray("pid");
if (pid_array != null && pid_array.length() > 0) {
p.pid = pid_array.getLong(0);
}
JSONArray likes_array = o.optJSONArray("likes");
if (likes_array != null && likes_array.length() > 0) {
JSONObject jlikes = likes_array.getJSONObject(0);
p.like_count = jlikes.optInt("count");
p.user_likes = jlikes.optInt("user_likes")==1;
}
JSONArray comments_array = o.optJSONArray("comments");
if (comments_array != null && comments_array.length() > 0) {
JSONObject jcomments = comments_array.getJSONObject(0);
p.comments_count = jcomments.optInt("count");
}
JSONArray tags_array = o.optJSONArray("tags");
if (tags_array != null && tags_array.length() > 0) {
JSONObject jtags = tags_array.getJSONObject(0);
p.tags_count = jtags.optInt("count");
}
JSONArray can_comment_array = o.optJSONArray("can_comment");
if (can_comment_array != null && can_comment_array.length() > 0) {
p.can_comment = can_comment_array.getInt(0)==1;
}
JSONArray user_id_array = o.optJSONArray("user_id");
if (user_id_array != null && user_id_array.length() > 0) {
p.user_id = user_id_array.getString(0);
}
return p;
}
}
| true | true | public static Photo parse(JSONObject o) throws NumberFormatException, JSONException{
Photo p = new Photo();
p.pid = o.getLong("id");
p.aid = o.optLong("album_id");
p.owner_id = o.getString("owner_id");
p.src = o.optString("photo_130");
p.src_small = o.optString("photo_75");
p.src_big = o.optString("photo_604");
p.src_xbig = o.optString("photo_807");
p.src_xxbig = o.optString("photo_1280");
p.src_xxxbig = o.optString("photo_2560");
p.phototext = Api.unescape(o.optString("text"));
p.created = o.optLong("created");
p.user_id = o.optString("user_id");
if (o.has("likes")) {
JSONObject jlikes = o.getJSONObject("likes");
p.like_count = jlikes.optInt("count");
p.user_likes = jlikes.optInt("user_likes")==1;
}
if (o.has("comments")) {
JSONObject jcomments = o.getJSONObject("comments");
p.comments_count = jcomments.optInt("count");
}
if (o.has("tags")) {
JSONObject jtags = o.getJSONObject("tags");
p.tags_count = jtags.optInt("count");
}
if (o.has("can_comment"))
p.can_comment = o.optInt("can_comment")==1;
p.width = o.optInt("width");
p.height = o.optInt("height");
p.access_key=o.optString("access_key");
return p;
}
| public static Photo parse(JSONObject o) throws NumberFormatException, JSONException{
Photo p = new Photo();
p.pid = o.getLong("id");
p.aid = o.optLong("album_id");
p.owner_id = o.getString("owner_id");
p.src = o.optString("photo_130");
p.src_small = o.optString("photo_75");
p.src_big = o.optString("photo_604");
p.src_xbig = o.optString("photo_807");
p.src_xxbig = o.optString("photo_1280");
p.src_xxxbig = o.optString("photo_2560");
p.phototext = Api.unescape(o.optString("text"));
p.created = o.optLong("date"); //date instead created for api v 5.0 and higher
p.user_id = o.optString("user_id");
if (o.has("likes")) {
JSONObject jlikes = o.getJSONObject("likes");
p.like_count = jlikes.optInt("count");
p.user_likes = jlikes.optInt("user_likes")==1;
}
if (o.has("comments")) {
JSONObject jcomments = o.getJSONObject("comments");
p.comments_count = jcomments.optInt("count");
}
if (o.has("tags")) {
JSONObject jtags = o.getJSONObject("tags");
p.tags_count = jtags.optInt("count");
}
if (o.has("can_comment"))
p.can_comment = o.optInt("can_comment")==1;
p.width = o.optInt("width");
p.height = o.optInt("height");
p.access_key=o.optString("access_key");
return p;
}
|
diff --git a/gshell/gshell-core/src/main/java/org/apache/geronimo/gshell/commands/builtins/InfoCommand.java b/gshell/gshell-core/src/main/java/org/apache/geronimo/gshell/commands/builtins/InfoCommand.java
index 28eeed66..d932c1e9 100644
--- a/gshell/gshell-core/src/main/java/org/apache/geronimo/gshell/commands/builtins/InfoCommand.java
+++ b/gshell/gshell-core/src/main/java/org/apache/geronimo/gshell/commands/builtins/InfoCommand.java
@@ -1,181 +1,181 @@
/*
* 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.geronimo.gshell.commands.builtins;
import java.lang.management.ClassLoadingMXBean;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.geronimo.gshell.ansi.Code;
import org.apache.geronimo.gshell.ansi.Renderer;
import org.apache.geronimo.gshell.branding.Branding;
import org.apache.geronimo.gshell.command.annotation.CommandComponent;
import org.apache.geronimo.gshell.command.annotation.Requirement;
import org.apache.geronimo.gshell.support.OsgiCommandSupport;
import org.codehaus.plexus.util.StringUtils;
/**
* Display environmental informations
*/
@CommandComponent(id="gshell-builtins:info", description="Show system informations")
public class InfoCommand
extends OsgiCommandSupport
{
@Requirement
private Branding branding;
private Renderer renderer = new Renderer();
private NumberFormat fmtI = new DecimalFormat("###,###", new DecimalFormatSymbols(Locale.ENGLISH));
private NumberFormat fmtD = new DecimalFormat("###,##0.000", new DecimalFormatSymbols(Locale.ENGLISH));
public InfoCommand(Branding branding) {
this.branding = branding;
}
@Override
protected OsgiCommandSupport createCommand() throws Exception {
return new InfoCommand(branding);
}
@Override
protected Object doExecute() throws Exception {
int maxNameLen;
String name;
Map<String, String> props = new HashMap<String, String>();
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean();
//
// print ServiceMix informations
//
maxNameLen = 25;
io.out.println("ServiceMix");
printValue("ServiceMix home", maxNameLen, System.getProperty("servicemix.home"));
printValue("ServiceMix base", maxNameLen, System.getProperty("servicemix.base"));
printValue("ServiceMix version", maxNameLen, branding.getVersion());
io.out.println();
io.out.println("JVM");
printValue("Java Virtual Machine", maxNameLen, runtime.getVmName() + " version " + runtime.getVmVersion());
printValue("Vendor", maxNameLen, runtime.getVmVendor());
printValue("Uptime", maxNameLen, printDuration(runtime.getUptime()));
try {
com.sun.management.OperatingSystemMXBean sunOs = (com.sun.management.OperatingSystemMXBean) os;
printValue("Process CPU time", maxNameLen, printDuration(sunOs.getProcessCpuTime() / 1000000));
printValue("Total compile time", maxNameLen, printDuration(ManagementFactory.getCompilationMXBean().getTotalCompilationTime()));
} catch (Throwable t) {}
io.out.println("Threads");
printValue("Live threads", maxNameLen, Integer.toString(threads.getThreadCount()));
printValue("Daemon threads", maxNameLen, Integer.toString(threads.getDaemonThreadCount()));
printValue("Peak", maxNameLen, Integer.toString(threads.getPeakThreadCount()));
printValue("Total started", maxNameLen, Long.toString(threads.getTotalStartedThreadCount()));
io.out.println("Memory");
printValue("Current heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getUsed()));
printValue("Maximum heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getMax()));
printValue("Committed heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getCommitted()));
printValue("Pending objects", maxNameLen, Integer.toString(mem.getObjectPendingFinalizationCount()));
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
String val = "Name = '" + gc.getName() + "', Collections = " + gc.getCollectionCount() + ", Time = " + printDuration(gc.getCollectionTime());
printValue("Garbage collector", maxNameLen, val);
}
io.out.println("Classes");
printValue("Current classes loaded", maxNameLen, printLong(cl.getLoadedClassCount()));
printValue("Total classes loaded", maxNameLen, printLong(cl.getTotalLoadedClassCount()));
printValue("Total classes unloaded", maxNameLen, printLong(cl.getUnloadedClassCount()));
io.out.println("Operating system");
printValue("Name", maxNameLen, os.getName() + " version " + os.getVersion());
printValue("Architecture", maxNameLen, os.getArch());
- printValue("Processrors", maxNameLen, Integer.toString(os.getAvailableProcessors()));
+ printValue("Processors", maxNameLen, Integer.toString(os.getAvailableProcessors()));
try {
com.sun.management.OperatingSystemMXBean sunOs = (com.sun.management.OperatingSystemMXBean) os;
printValue("Total physical memory", maxNameLen, printSizeInKb(sunOs.getTotalPhysicalMemorySize()));
printValue("Free physical memory", maxNameLen, printSizeInKb(sunOs.getFreePhysicalMemorySize()));
printValue("Committed virtual memory", maxNameLen, printSizeInKb(sunOs.getCommittedVirtualMemorySize()));
printValue("Total swap space", maxNameLen, printSizeInKb(sunOs.getTotalSwapSpaceSize()));
printValue("Free swap space", maxNameLen, printSizeInKb(sunOs.getFreeSwapSpaceSize()));
} catch (Throwable t) {}
return null;
}
private String printLong(long i) {
return fmtI.format(i);
}
private String printSizeInKb(double size) {
return fmtI.format((long) (size / 1024)) + " kbytes";
}
private String printDuration(double uptime) {
uptime /= 1000;
if (uptime < 60) {
return fmtD.format(uptime) + " seconds";
}
uptime /= 60;
if (uptime < 60) {
long minutes = (long) uptime;
String s = fmtI.format(minutes) + (minutes > 1 ? " minutes" : " minute");
return s;
}
uptime /= 60;
if (uptime < 24) {
long hours = (long) uptime;
long minutes = (long) ((uptime - hours) * 60);
String s = fmtI.format(hours) + (hours > 1 ? " hours" : " hour");
if (minutes != 0) {
s += " " + fmtI.format(minutes) + (minutes > 1 ? " minutes" : "minute");
}
return s;
}
uptime /= 24;
long days = (long) uptime;
long hours = (long) ((uptime - days) * 60);
String s = fmtI.format(days) + (days > 1 ? " days" : " day");
if (hours != 0) {
s += " " + fmtI.format(hours) + (hours > 1 ? " hours" : "hour");
}
return s;
}
void printSysValue(String prop, int pad) {
printValue(prop, pad, System.getProperty(prop));
}
void printValue(String name, int pad, String value) {
io.out.println(" " + renderer.render(Renderer.encode(StringUtils.rightPad(name, pad), Code.BOLD)) + " " + value);
}
}
| true | true | protected Object doExecute() throws Exception {
int maxNameLen;
String name;
Map<String, String> props = new HashMap<String, String>();
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean();
//
// print ServiceMix informations
//
maxNameLen = 25;
io.out.println("ServiceMix");
printValue("ServiceMix home", maxNameLen, System.getProperty("servicemix.home"));
printValue("ServiceMix base", maxNameLen, System.getProperty("servicemix.base"));
printValue("ServiceMix version", maxNameLen, branding.getVersion());
io.out.println();
io.out.println("JVM");
printValue("Java Virtual Machine", maxNameLen, runtime.getVmName() + " version " + runtime.getVmVersion());
printValue("Vendor", maxNameLen, runtime.getVmVendor());
printValue("Uptime", maxNameLen, printDuration(runtime.getUptime()));
try {
com.sun.management.OperatingSystemMXBean sunOs = (com.sun.management.OperatingSystemMXBean) os;
printValue("Process CPU time", maxNameLen, printDuration(sunOs.getProcessCpuTime() / 1000000));
printValue("Total compile time", maxNameLen, printDuration(ManagementFactory.getCompilationMXBean().getTotalCompilationTime()));
} catch (Throwable t) {}
io.out.println("Threads");
printValue("Live threads", maxNameLen, Integer.toString(threads.getThreadCount()));
printValue("Daemon threads", maxNameLen, Integer.toString(threads.getDaemonThreadCount()));
printValue("Peak", maxNameLen, Integer.toString(threads.getPeakThreadCount()));
printValue("Total started", maxNameLen, Long.toString(threads.getTotalStartedThreadCount()));
io.out.println("Memory");
printValue("Current heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getUsed()));
printValue("Maximum heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getMax()));
printValue("Committed heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getCommitted()));
printValue("Pending objects", maxNameLen, Integer.toString(mem.getObjectPendingFinalizationCount()));
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
String val = "Name = '" + gc.getName() + "', Collections = " + gc.getCollectionCount() + ", Time = " + printDuration(gc.getCollectionTime());
printValue("Garbage collector", maxNameLen, val);
}
io.out.println("Classes");
printValue("Current classes loaded", maxNameLen, printLong(cl.getLoadedClassCount()));
printValue("Total classes loaded", maxNameLen, printLong(cl.getTotalLoadedClassCount()));
printValue("Total classes unloaded", maxNameLen, printLong(cl.getUnloadedClassCount()));
io.out.println("Operating system");
printValue("Name", maxNameLen, os.getName() + " version " + os.getVersion());
printValue("Architecture", maxNameLen, os.getArch());
printValue("Processrors", maxNameLen, Integer.toString(os.getAvailableProcessors()));
try {
com.sun.management.OperatingSystemMXBean sunOs = (com.sun.management.OperatingSystemMXBean) os;
printValue("Total physical memory", maxNameLen, printSizeInKb(sunOs.getTotalPhysicalMemorySize()));
printValue("Free physical memory", maxNameLen, printSizeInKb(sunOs.getFreePhysicalMemorySize()));
printValue("Committed virtual memory", maxNameLen, printSizeInKb(sunOs.getCommittedVirtualMemorySize()));
printValue("Total swap space", maxNameLen, printSizeInKb(sunOs.getTotalSwapSpaceSize()));
printValue("Free swap space", maxNameLen, printSizeInKb(sunOs.getFreeSwapSpaceSize()));
} catch (Throwable t) {}
return null;
}
| protected Object doExecute() throws Exception {
int maxNameLen;
String name;
Map<String, String> props = new HashMap<String, String>();
RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
ThreadMXBean threads = ManagementFactory.getThreadMXBean();
MemoryMXBean mem = ManagementFactory.getMemoryMXBean();
ClassLoadingMXBean cl = ManagementFactory.getClassLoadingMXBean();
//
// print ServiceMix informations
//
maxNameLen = 25;
io.out.println("ServiceMix");
printValue("ServiceMix home", maxNameLen, System.getProperty("servicemix.home"));
printValue("ServiceMix base", maxNameLen, System.getProperty("servicemix.base"));
printValue("ServiceMix version", maxNameLen, branding.getVersion());
io.out.println();
io.out.println("JVM");
printValue("Java Virtual Machine", maxNameLen, runtime.getVmName() + " version " + runtime.getVmVersion());
printValue("Vendor", maxNameLen, runtime.getVmVendor());
printValue("Uptime", maxNameLen, printDuration(runtime.getUptime()));
try {
com.sun.management.OperatingSystemMXBean sunOs = (com.sun.management.OperatingSystemMXBean) os;
printValue("Process CPU time", maxNameLen, printDuration(sunOs.getProcessCpuTime() / 1000000));
printValue("Total compile time", maxNameLen, printDuration(ManagementFactory.getCompilationMXBean().getTotalCompilationTime()));
} catch (Throwable t) {}
io.out.println("Threads");
printValue("Live threads", maxNameLen, Integer.toString(threads.getThreadCount()));
printValue("Daemon threads", maxNameLen, Integer.toString(threads.getDaemonThreadCount()));
printValue("Peak", maxNameLen, Integer.toString(threads.getPeakThreadCount()));
printValue("Total started", maxNameLen, Long.toString(threads.getTotalStartedThreadCount()));
io.out.println("Memory");
printValue("Current heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getUsed()));
printValue("Maximum heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getMax()));
printValue("Committed heap size", maxNameLen, printSizeInKb(mem.getHeapMemoryUsage().getCommitted()));
printValue("Pending objects", maxNameLen, Integer.toString(mem.getObjectPendingFinalizationCount()));
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
String val = "Name = '" + gc.getName() + "', Collections = " + gc.getCollectionCount() + ", Time = " + printDuration(gc.getCollectionTime());
printValue("Garbage collector", maxNameLen, val);
}
io.out.println("Classes");
printValue("Current classes loaded", maxNameLen, printLong(cl.getLoadedClassCount()));
printValue("Total classes loaded", maxNameLen, printLong(cl.getTotalLoadedClassCount()));
printValue("Total classes unloaded", maxNameLen, printLong(cl.getUnloadedClassCount()));
io.out.println("Operating system");
printValue("Name", maxNameLen, os.getName() + " version " + os.getVersion());
printValue("Architecture", maxNameLen, os.getArch());
printValue("Processors", maxNameLen, Integer.toString(os.getAvailableProcessors()));
try {
com.sun.management.OperatingSystemMXBean sunOs = (com.sun.management.OperatingSystemMXBean) os;
printValue("Total physical memory", maxNameLen, printSizeInKb(sunOs.getTotalPhysicalMemorySize()));
printValue("Free physical memory", maxNameLen, printSizeInKb(sunOs.getFreePhysicalMemorySize()));
printValue("Committed virtual memory", maxNameLen, printSizeInKb(sunOs.getCommittedVirtualMemorySize()));
printValue("Total swap space", maxNameLen, printSizeInKb(sunOs.getTotalSwapSpaceSize()));
printValue("Free swap space", maxNameLen, printSizeInKb(sunOs.getFreeSwapSpaceSize()));
} catch (Throwable t) {}
return null;
}
|
diff --git a/openejb/container/openejb-core/src/main/java/org/apache/openejb/resource/activemq/ActiveMQResourceAdapter.java b/openejb/container/openejb-core/src/main/java/org/apache/openejb/resource/activemq/ActiveMQResourceAdapter.java
index b15c59064..c0fc00420 100644
--- a/openejb/container/openejb-core/src/main/java/org/apache/openejb/resource/activemq/ActiveMQResourceAdapter.java
+++ b/openejb/container/openejb-core/src/main/java/org/apache/openejb/resource/activemq/ActiveMQResourceAdapter.java
@@ -1,274 +1,274 @@
/*
* 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.openejb.resource.activemq;
import org.apache.activemq.broker.BrokerService;
import org.apache.openejb.util.Duration;
import org.apache.openejb.util.LogCategory;
import org.apache.openejb.util.URISupport;
import javax.resource.spi.BootstrapContext;
import javax.resource.spi.ResourceAdapterInternalException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
public class ActiveMQResourceAdapter extends org.apache.activemq.ra.ActiveMQResourceAdapter {
private String dataSource;
private String useDatabaseLock;
private String startupTimeout = "60000";
public String getDataSource() {
return dataSource;
}
public void setDataSource(final String dataSource) {
this.dataSource = dataSource;
}
public void setUseDatabaseLock(final String useDatabaseLock) {
this.useDatabaseLock = useDatabaseLock;
}
public int getStartupTimeout() {
return Integer.parseInt(this.startupTimeout);
}
public void setStartupTimeout(Duration startupTimeout) {
if (startupTimeout.getUnit() == null) {
startupTimeout.setUnit(TimeUnit.MILLISECONDS);
}
this.startupTimeout = "" + TimeUnit.MILLISECONDS.convert(startupTimeout.getTime(), startupTimeout.getUnit());
}
@Override
public void setServerUrl(final String url) {
super.setServerUrl(url);
}
// DMB: Work in progress. These all should go into the service-jar.xml
// Sources of info:
// - http://activemq.apache.org/resource-adapter-properties.html
// - http://activemq.apache.org/camel/maven/camel-core/apidocs/org/apache/camel/processor/RedeliveryPolicy.html
//
// /**
// * 100 The maximum number of messages sent to a consumer on a durable topic until acknowledgements are received
// * @param integer
// */
// public void setDurableTopicPrefetch(Integer integer) {
// super.setDurableTopicPrefetch(integer);
// }
//
// /**
// * 1000 The delay before redeliveries start. Also configurable on the ActivationSpec.
// * @param aLong
// */
// public void setInitialRedeliveryDelay(Long aLong) {
// super.setInitialRedeliveryDelay(aLong);
// }
//
// /**
// * 100 The maximum number of messages sent to a consumer on a JMS stream until acknowledgements are received
// * @param integer
// */
// public void setInputStreamPrefetch(Integer integer) {
// super.setInputStreamPrefetch(integer);
// }
//
// /**
// * 5 The maximum number of redeliveries or -1 for no maximum. Also configurable on the ActivationSpec.
// * @param integer
// */
// public void setMaximumRedeliveries(Integer integer) {
// super.setMaximumRedeliveries(integer);
// }
//
// public void setQueueBrowserPrefetch(Integer integer) {
// super.setQueueBrowserPrefetch(integer);
// }
//
// /**
// * 1000 The maximum number of messages sent to a consumer on a queue until acknowledgements are received
// * @param integer
// */
// public void setQueuePrefetch(Integer integer) {
// super.setQueuePrefetch(integer);
// }
//
// /**
// * 5 The multiplier to use if exponential back off is enabled. Also configurable on the ActivationSpec.
// * @param aShort
// */
// public void setRedeliveryBackOffMultiplier(Short aShort) {
// super.setRedeliveryBackOffMultiplier(aShort);
// }
//
// public void setRedeliveryUseExponentialBackOff(Boolean aBoolean) {
// super.setRedeliveryUseExponentialBackOff(aBoolean);
// }
//
// /**
// * 32766 The maximum number of messages sent to a consumer on a non-durable topic until acknowledgements are received
// * @param integer
// */
// public void setTopicPrefetch(Integer integer) {
// super.setTopicPrefetch(integer);
// }
@Override
public void start(final BootstrapContext bootstrapContext) throws ResourceAdapterInternalException {
final Properties properties = new Properties();
if (null != this.dataSource) {
properties.put("DataSource", this.dataSource);
}
if (null != this.useDatabaseLock) {
properties.put("UseDatabaseLock", this.useDatabaseLock);
}
if (null != this.startupTimeout) {
properties.put("StartupTimeout", this.startupTimeout);
}
// prefix server uri with 'broker:' so our broker factory is used
final String brokerXmlConfig = getBrokerXmlConfig();
if (brokerXmlConfig != null) {
try {
if (brokerXmlConfig.startsWith("broker:")) {
final URISupport.CompositeData compositeData = URISupport.parseComposite(new URI(brokerXmlConfig));
if (!compositeData.getParameters().containsKey("persistent")) {
//Override default - Which is 'true'
//noinspection unchecked
compositeData.getParameters().put("persistent", "false");
}
// compromise to avoid broker lock in some case + avoid failing tests
- if (!compositeData.getParameters().containsKey("watchTopicAdvisories")) {
- compositeData.getParameters().put("watchTopicAdvisories", "false");
+ if (!compositeData.getParameters().containsKey("jms.watchTopicAdvisories")) {
+ compositeData.getParameters().put("jms.watchTopicAdvisories", "false");
}
if ("false".equalsIgnoreCase(compositeData.getParameters().get("persistent").toString())) {
properties.remove("DataSource"); // no need
}
setBrokerXmlConfig(ActiveMQFactory.getBrokerMetaFile() + compositeData.toURI());
} else if (brokerXmlConfig.toLowerCase().startsWith("xbean:")) {
setBrokerXmlConfig(ActiveMQFactory.getBrokerMetaFile() + brokerXmlConfig);
}
} catch (URISyntaxException e) {
throw new ResourceAdapterInternalException("Invalid BrokerXmlConfig", e);
}
}
ActiveMQFactory.setThreadProperties(properties);
try {
super.start(bootstrapContext);
} finally {
ActiveMQFactory.setThreadProperties(null);
// reset brokerXmlConfig
if (brokerXmlConfig != null) {
setBrokerXmlConfig(brokerXmlConfig);
}
}
}
@Override
public void stop() {
org.apache.openejb.util.Logger.getInstance(LogCategory.OPENEJB_STARTUP, "org.apache.openejb.util.resources").info("Stopping ActiveMQ");
final Thread stopThread = new Thread("ActiveMQResourceAdapter stop") {
@Override
public void run() {
try {
stopImpl();
} catch (Throwable t) {
org.apache.openejb.util.Logger.getInstance(LogCategory.OPENEJB_STARTUP, "org.apache.openejb.util.resources").error("ActiveMQ shutdown failed", t);
}
}
};
stopThread.setDaemon(true);
stopThread.start();
int timeout = 60000;
try {
timeout = Integer.parseInt(this.startupTimeout);
} catch (Throwable e) {
//Ignore
}
try {
//Block for a maximum of timeout milliseconds waiting for this thread to die.
stopThread.join(timeout);
} catch (InterruptedException ex) {
org.apache.openejb.util.Logger.getInstance(LogCategory.OPENEJB_STARTUP, "org.apache.openejb.util.resources").warning("Gave up on ActiveMQ shutdown after " + timeout + "ms", ex);
}
}
private void stopImpl() throws Exception {
super.stop();
final ActiveMQResourceAdapter ra = this;
stopImpl(ra);
}
private static void stopImpl(final org.apache.activemq.ra.ActiveMQResourceAdapter instance) throws Exception {
final Collection<BrokerService> brokers = ActiveMQFactory.getBrokers();
final Iterator<BrokerService> it = brokers.iterator();
while (it.hasNext()) {
try {
it.next().waitUntilStopped();
} catch (Throwable t) {
//Ignore
}
it.remove();
}
stopScheduler();
org.apache.openejb.util.Logger.getInstance(LogCategory.OPENEJB_STARTUP, "org.apache.openejb.util.resources").info("Stopped ActiveMQ broker");
}
private static void stopScheduler() {
try {
final Class<?> clazz = Class.forName("org.apache.kahadb.util.Scheduler");
final Method method = clazz.getMethod("shutdown");
method.invoke(null);
} catch (Throwable e) {
//Ignore
}
}
}
| true | true | public void start(final BootstrapContext bootstrapContext) throws ResourceAdapterInternalException {
final Properties properties = new Properties();
if (null != this.dataSource) {
properties.put("DataSource", this.dataSource);
}
if (null != this.useDatabaseLock) {
properties.put("UseDatabaseLock", this.useDatabaseLock);
}
if (null != this.startupTimeout) {
properties.put("StartupTimeout", this.startupTimeout);
}
// prefix server uri with 'broker:' so our broker factory is used
final String brokerXmlConfig = getBrokerXmlConfig();
if (brokerXmlConfig != null) {
try {
if (brokerXmlConfig.startsWith("broker:")) {
final URISupport.CompositeData compositeData = URISupport.parseComposite(new URI(brokerXmlConfig));
if (!compositeData.getParameters().containsKey("persistent")) {
//Override default - Which is 'true'
//noinspection unchecked
compositeData.getParameters().put("persistent", "false");
}
// compromise to avoid broker lock in some case + avoid failing tests
if (!compositeData.getParameters().containsKey("watchTopicAdvisories")) {
compositeData.getParameters().put("watchTopicAdvisories", "false");
}
if ("false".equalsIgnoreCase(compositeData.getParameters().get("persistent").toString())) {
properties.remove("DataSource"); // no need
}
setBrokerXmlConfig(ActiveMQFactory.getBrokerMetaFile() + compositeData.toURI());
} else if (brokerXmlConfig.toLowerCase().startsWith("xbean:")) {
setBrokerXmlConfig(ActiveMQFactory.getBrokerMetaFile() + brokerXmlConfig);
}
} catch (URISyntaxException e) {
throw new ResourceAdapterInternalException("Invalid BrokerXmlConfig", e);
}
}
ActiveMQFactory.setThreadProperties(properties);
try {
super.start(bootstrapContext);
} finally {
ActiveMQFactory.setThreadProperties(null);
// reset brokerXmlConfig
if (brokerXmlConfig != null) {
setBrokerXmlConfig(brokerXmlConfig);
}
}
}
| public void start(final BootstrapContext bootstrapContext) throws ResourceAdapterInternalException {
final Properties properties = new Properties();
if (null != this.dataSource) {
properties.put("DataSource", this.dataSource);
}
if (null != this.useDatabaseLock) {
properties.put("UseDatabaseLock", this.useDatabaseLock);
}
if (null != this.startupTimeout) {
properties.put("StartupTimeout", this.startupTimeout);
}
// prefix server uri with 'broker:' so our broker factory is used
final String brokerXmlConfig = getBrokerXmlConfig();
if (brokerXmlConfig != null) {
try {
if (brokerXmlConfig.startsWith("broker:")) {
final URISupport.CompositeData compositeData = URISupport.parseComposite(new URI(brokerXmlConfig));
if (!compositeData.getParameters().containsKey("persistent")) {
//Override default - Which is 'true'
//noinspection unchecked
compositeData.getParameters().put("persistent", "false");
}
// compromise to avoid broker lock in some case + avoid failing tests
if (!compositeData.getParameters().containsKey("jms.watchTopicAdvisories")) {
compositeData.getParameters().put("jms.watchTopicAdvisories", "false");
}
if ("false".equalsIgnoreCase(compositeData.getParameters().get("persistent").toString())) {
properties.remove("DataSource"); // no need
}
setBrokerXmlConfig(ActiveMQFactory.getBrokerMetaFile() + compositeData.toURI());
} else if (brokerXmlConfig.toLowerCase().startsWith("xbean:")) {
setBrokerXmlConfig(ActiveMQFactory.getBrokerMetaFile() + brokerXmlConfig);
}
} catch (URISyntaxException e) {
throw new ResourceAdapterInternalException("Invalid BrokerXmlConfig", e);
}
}
ActiveMQFactory.setThreadProperties(properties);
try {
super.start(bootstrapContext);
} finally {
ActiveMQFactory.setThreadProperties(null);
// reset brokerXmlConfig
if (brokerXmlConfig != null) {
setBrokerXmlConfig(brokerXmlConfig);
}
}
}
|
diff --git a/core/src/main/java/org/kohsuke/stapler/bind/BoundObjectTable.java b/core/src/main/java/org/kohsuke/stapler/bind/BoundObjectTable.java
index bc7ad27cc..bf0261f89 100644
--- a/core/src/main/java/org/kohsuke/stapler/bind/BoundObjectTable.java
+++ b/core/src/main/java/org/kohsuke/stapler/bind/BoundObjectTable.java
@@ -1,245 +1,245 @@
/*
* Copyright (c) 2004-2010, Kohsuke Kawaguchi
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.kohsuke.stapler.bind;
import org.kohsuke.stapler.Ancestor;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
/**
* Objects exported and bound by JavaScript proxies.
*
* TODO: think about some kind of eviction strategy, beyond the session eviction.
* Maybe it's not necessary, I don't know.
*
* @author Kohsuke Kawaguchi
*/
public class BoundObjectTable implements StaplerFallback {
public Table getStaplerFallback() {
return resolve(false);
}
private Bound bind(Ref ref) {
return resolve(true).add(ref);
}
/**
* Binds an object temporarily and returns its URL.
*/
public Bound bind(Object o) {
return bind(new StrongRef(o));
}
/**
* Binds an object temporarily and returns its URL.
*/
public Bound bindWeak(Object o) {
return bind(new WeakRef(o));
}
/**
* Called from within the request handling of a bound object, to release the object explicitly.
*/
public void releaseMe() {
Ancestor eot = Stapler.getCurrentRequest().findAncestor(BoundObjectTable.class);
if (eot==null)
throw new IllegalStateException("The thread is not handling a request to a abound object");
String id = eot.getNextToken(0);
resolve(false).release(id); // resolve(false) can't fail because we are processing this request now.
}
/**
* Obtains a {@link Table} associated with this session.
*/
private Table resolve(boolean createIfNotExist) {
HttpSession session = Stapler.getCurrentRequest().getSession(createIfNotExist);
if (session==null) return null;
Table t = (Table) session.getAttribute(Table.class.getName());
if (t==null) {
if (createIfNotExist)
session.setAttribute(Table.class.getName(), t=new Table());
else
return null;
}
return t;
}
/**
* Explicit call to create the table if one doesn't exist yet.
*/
public Table getTable() {
return resolve(true);
}
/**
* Per-session table that remembers all the bound instances.
*/
public static class Table {
private final Map<String,Ref> entries = new HashMap<String,Ref>();
private boolean logging;
private synchronized Bound add(Ref ref) {
final Object target = ref.get();
if (target instanceof WithWellKnownURL) {
WithWellKnownURL w = (WithWellKnownURL) target;
String url = w.getWellKnownUrl();
if (!url.startsWith("/")) {
- throw new IllegalArgumentException("WithWellKnownURL.getWellKnownUrl must start with a slash: " + url);
+ LOGGER.warning("WithWellKnownURL.getWellKnownUrl must start with a slash. But we got " + url + " from "+w);
}
return new WellKnownObjectHandle(url, w);
}
final String id = UUID.randomUUID().toString();
entries.put(id,ref);
if (logging) LOGGER.info(String.format("%s binding %s for %s", toString(), target, id));
return new Bound() {
public void release() {
Table.this.release(id);
}
public String getURL() {
return Stapler.getCurrentRequest().getContextPath()+PREFIX+id;
}
public Object getTarget() {
return target;
}
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
rsp.sendRedirect2(getURL());
}
};
}
public Object getDynamic(String id) {
return resolve(id);
}
private synchronized Ref release(String id) {
return entries.remove(id);
}
private synchronized Object resolve(String id) {
Ref e = entries.get(id);
if (e==null) {
if (logging) LOGGER.info(toString()+" doesn't have binding for "+id);
return null;
}
Object v = e.get();
if (v==null) {
if (logging) LOGGER.warning(toString() + " had binding for " + id + " but it got garbage collected");
entries.remove(id); // reference is already garbage collected.
}
return v;
}
public HttpResponse doEnableLogging() {
if (DEBUG_LOGGING) {
this.logging = true;
return HttpResponses.plainText("Logging enabled for this session: "+toString());
} else {
return HttpResponses.forbidden();
}
}
}
private static final class WellKnownObjectHandle extends Bound {
private final String url;
private final Object target;
public WellKnownObjectHandle(String url, Object target) {
this.url = url;
this.target = target;
}
/**
* Objects with well-known URLs cannot be released, as their URL bindings are controlled
* implicitly by the application.
*/
public void release() {
}
public String getURL() {
return Stapler.getCurrentRequest().getContextPath()+url;
}
@Override
public Object getTarget() {
return target;
}
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
rsp.sendRedirect2(getURL());
}
}
/**
* Reference that resolves to an object.
*/
interface Ref {
Object get();
}
private static class StrongRef implements Ref {
private final Object o;
StrongRef(Object o) {
this.o = o;
}
public Object get() {
return o;
}
}
private static class WeakRef extends WeakReference implements Ref {
private WeakRef(Object referent) {
super(referent);
}
}
public static final String PREFIX = "/$stapler/bound/";
/**
* True to activate debug logging of session fragments.
*/
public static boolean DEBUG_LOGGING = Boolean.getBoolean(BoundObjectTable.class.getName()+".debugLog");
private static final Logger LOGGER = Logger.getLogger(BoundObjectTable.class.getName());
}
| true | true | private synchronized Bound add(Ref ref) {
final Object target = ref.get();
if (target instanceof WithWellKnownURL) {
WithWellKnownURL w = (WithWellKnownURL) target;
String url = w.getWellKnownUrl();
if (!url.startsWith("/")) {
throw new IllegalArgumentException("WithWellKnownURL.getWellKnownUrl must start with a slash: " + url);
}
return new WellKnownObjectHandle(url, w);
}
final String id = UUID.randomUUID().toString();
entries.put(id,ref);
if (logging) LOGGER.info(String.format("%s binding %s for %s", toString(), target, id));
return new Bound() {
public void release() {
Table.this.release(id);
}
public String getURL() {
return Stapler.getCurrentRequest().getContextPath()+PREFIX+id;
}
public Object getTarget() {
return target;
}
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
rsp.sendRedirect2(getURL());
}
};
}
| private synchronized Bound add(Ref ref) {
final Object target = ref.get();
if (target instanceof WithWellKnownURL) {
WithWellKnownURL w = (WithWellKnownURL) target;
String url = w.getWellKnownUrl();
if (!url.startsWith("/")) {
LOGGER.warning("WithWellKnownURL.getWellKnownUrl must start with a slash. But we got " + url + " from "+w);
}
return new WellKnownObjectHandle(url, w);
}
final String id = UUID.randomUUID().toString();
entries.put(id,ref);
if (logging) LOGGER.info(String.format("%s binding %s for %s", toString(), target, id));
return new Bound() {
public void release() {
Table.this.release(id);
}
public String getURL() {
return Stapler.getCurrentRequest().getContextPath()+PREFIX+id;
}
public Object getTarget() {
return target;
}
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException {
rsp.sendRedirect2(getURL());
}
};
}
|
diff --git a/javasvn/src/org/tigris/subversion/javahl/PromptAuthenticationProvider.java b/javasvn/src/org/tigris/subversion/javahl/PromptAuthenticationProvider.java
index 1f76a2cec..00a6885a1 100644
--- a/javasvn/src/org/tigris/subversion/javahl/PromptAuthenticationProvider.java
+++ b/javasvn/src/org/tigris/subversion/javahl/PromptAuthenticationProvider.java
@@ -1,36 +1,41 @@
/*
* Created on 25.06.2005
*/
package org.tigris.subversion.javahl;
import org.tmatesoft.svn.core.wc.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.wc.ISVNAuthenticationProvider;
import org.tmatesoft.svn.core.wc.SVNAuthentication;
public class PromptAuthenticationProvider implements ISVNAuthenticationProvider {
PromptUserPassword myPrompt;
public PromptAuthenticationProvider(PromptUserPassword prompt){
myPrompt = prompt;
}
public SVNAuthentication requestClientAuthentication(String kind,
String realm, String userName, ISVNAuthenticationManager manager) {
- if(myPrompt.prompt(realm, userName)){
- SVNAuthentication auth = new SVNAuthentication(kind, realm, myPrompt.getUsername(), myPrompt.getPassword());
- if (myPrompt instanceof PromptUserPassword3) {
- PromptUserPassword3 prompt3 = (PromptUserPassword3) myPrompt;
+ if (myPrompt instanceof PromptUserPassword3) {
+ PromptUserPassword3 prompt3 = (PromptUserPassword3) myPrompt;
+ if(prompt3.prompt(realm, userName, manager.isAuthStorageEnabled())){
+ SVNAuthentication auth = new SVNAuthentication(kind, realm,
+ prompt3.getUsername(), prompt3.getPassword());
auth.setStorageAllowed(prompt3.userAllowedSave());
}
- return auth;
+ }else{
+ if(myPrompt.prompt(realm, userName)){
+ SVNAuthentication auth = new SVNAuthentication(kind, realm, myPrompt.getUsername(), myPrompt.getPassword());
+ return auth;
+ }
}
return null;
}
public int acceptServerAuthentication(SVNAuthentication authentication,
ISVNAuthenticationManager manager) {
return ISVNAuthenticationProvider.ACCEPTED;
}
}
| false | true | public SVNAuthentication requestClientAuthentication(String kind,
String realm, String userName, ISVNAuthenticationManager manager) {
if(myPrompt.prompt(realm, userName)){
SVNAuthentication auth = new SVNAuthentication(kind, realm, myPrompt.getUsername(), myPrompt.getPassword());
if (myPrompt instanceof PromptUserPassword3) {
PromptUserPassword3 prompt3 = (PromptUserPassword3) myPrompt;
auth.setStorageAllowed(prompt3.userAllowedSave());
}
return auth;
}
return null;
}
| public SVNAuthentication requestClientAuthentication(String kind,
String realm, String userName, ISVNAuthenticationManager manager) {
if (myPrompt instanceof PromptUserPassword3) {
PromptUserPassword3 prompt3 = (PromptUserPassword3) myPrompt;
if(prompt3.prompt(realm, userName, manager.isAuthStorageEnabled())){
SVNAuthentication auth = new SVNAuthentication(kind, realm,
prompt3.getUsername(), prompt3.getPassword());
auth.setStorageAllowed(prompt3.userAllowedSave());
}
}else{
if(myPrompt.prompt(realm, userName)){
SVNAuthentication auth = new SVNAuthentication(kind, realm, myPrompt.getUsername(), myPrompt.getPassword());
return auth;
}
}
return null;
}
|
diff --git a/src/framework/java/com/flexive/shared/FxSharedUtils.java b/src/framework/java/com/flexive/shared/FxSharedUtils.java
index c82ba69f..8bccdc33 100644
--- a/src/framework/java/com/flexive/shared/FxSharedUtils.java
+++ b/src/framework/java/com/flexive/shared/FxSharedUtils.java
@@ -1,2205 +1,2212 @@
/***************************************************************
* This file is part of the [fleXive](R) framework.
*
* Copyright (c) 1999-2014
* UCS - unique computing solutions gmbh (http://www.ucs.at)
* All rights reserved
*
* The [fleXive](R) project is free software; you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public
* License version 2.1 or higher as published by the Free Software Foundation.
*
* The GNU Lesser General Public License can be found at
* http://www.gnu.org/licenses/lgpl.html.
* A copy is found in the textfile LGPL.txt and important notices to the
* license from the author are found in LICENSE.txt distributed with
* these libraries.
*
* 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.
*
* For further information about UCS - unique computing solutions gmbh,
* please see the company website: http://www.ucs.at
*
* For further information about [fleXive](R), please see the
* project website: http://www.flexive.org
*
*
* This copyright notice MUST APPEAR in all copies of the file!
***************************************************************/
package com.flexive.shared;
import com.flexive.shared.configuration.DivisionData;
import com.flexive.shared.configuration.SystemParameters;
import com.flexive.shared.exceptions.FxApplicationException;
import com.flexive.shared.exceptions.FxCreateException;
import com.flexive.shared.exceptions.FxInvalidParameterException;
import com.flexive.shared.exceptions.FxNotFoundException;
import com.flexive.shared.structure.FxAssignment;
import com.flexive.shared.structure.FxSelectListItem;
import com.flexive.shared.value.FxString;
import com.flexive.shared.value.FxValue;
import com.flexive.shared.workflow.Step;
import com.flexive.shared.workflow.StepDefinition;
import com.google.common.base.Charsets;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.CharStreams;
import groovy.lang.GroovySystem;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.management.ObjectName;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.text.CollationKey;
import java.text.Collator;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import static org.apache.commons.lang.StringUtils.defaultString;
/**
* Flexive shared utility functions.
*
* @author Markus Plesser ([email protected]), UCS - unique computing solutions gmbh (http://www.ucs.at)
*/
@SuppressWarnings({"ThrowableInstanceNeverThrown"})
public final class FxSharedUtils {
private static final Log LOG = LogFactory.getLog(FxSharedUtils.class);
/**
* Shared message resources bundle
*/
public static final String SHARED_BUNDLE = "FxSharedMessages";
private static String fxVersion = "3.1";
private static String fxEdition = "repository";
private static String fxProduct = "[fleXive]";
private static String fxBuild = "unknown";
private static long fxDBVersion = -1L;
private static String fxBuildDate = "unknown";
private static String fxBuildUser = "unknown";
private static String fxHeader = "[fleXive]";
private static boolean fxSnapshotVersion = false;
private static String bundledGroovyVersion;
private static List<String> translatedLocales = Collections.unmodifiableList(Arrays.asList("en"));
private static String hostname = null;
private static String appserver = null;
private static final String JBOSS6_VERSION_PROPERTIES = "org/jboss/version.properties";
/**
* The character(s) representing a "xpath slash" (/) in a public URL.
*/
public static final String XPATH_ENCODEDSLASH = "@@";
/**
* Browser tests set this cookie to force using the test division instead of the actual division
* defined by the URL domain.
* TODO: security?
*/
public static final String COOKIE_FORCE_TEST_DIVISION = "ForceTestDivision";
private static List<String> drops;
private static List<FxDropApplication> dropApplications;
/**
* Are JDK 6+ extensions allowed to be run on the current VM?
*/
public static final boolean USE_JDK6_EXTENSION;
public static final boolean WINDOWS = System.getProperty("os.name").contains("Windows");
public static final String FLEXIVE_DROP_PROPERTIES = "flexive-application.properties";
public static final String FLEXIVE_STORAGE_PROPERTIES = "flexive-storage.properties";
/**
* System property to force a minimum set of runonce scripts when set (e.g. UI icons are not installed).
* This should not be enabled for flexive's own test suite, but for tests in external projects
* that can assume that the stock run-once scripts work.
*/
public static final String PROP_RUNONCE_MINIMAL = "flexive.runonce.minimal";
private static String NODE_ID;
static {
int major = -1, minor = -1;
try {
String[] ver = System.getProperty("java.specification.version").split("\\.");
if (ver.length >= 2) {
major = Integer.parseInt(ver[0]);
minor = Integer.parseInt(ver[1]);
}
} catch (Exception e) {
LOG.error(e);
}
USE_JDK6_EXTENSION = major > 1 || (major == 1 && minor >= 6);
try {
PropertyResourceBundle bundle = (PropertyResourceBundle) PropertyResourceBundle.getBundle("flexive");
fxVersion = bundle.getString("flexive.version");
fxSnapshotVersion = fxVersion != null && fxVersion.endsWith("-SNAPSHOT");
fxEdition = bundle.getString("flexive.edition");
fxProduct = bundle.getString("flexive.product");
fxBuild = bundle.getString("flexive.buildnumber");
fxDBVersion = Long.parseLong(bundle.getString("flexive.dbversion"));
fxBuildDate = bundle.getString("flexive.builddate");
fxBuildUser = bundle.getString("flexive.builduser");
fxHeader = bundle.getString("flexive.header");
final String languagesValue = bundle.getString("flexive.translatedLocales");
if (StringUtils.isNotBlank(languagesValue)) {
final String[] languages = StringUtils.split(languagesValue, ",");
for (int i = 0; i < languages.length; i++) {
languages[i] = languages[i].trim().toLowerCase();
}
translatedLocales = Collections.unmodifiableList(Arrays.asList(languages));
}
} catch (Exception e) {
LOG.error(e);
}
}
/**
* Get the current hosts name
*
* @return current hosts name
* @since 3.1
*/
public synchronized static String getHostName() {
if (hostname != null)
return hostname;
String _hostname;
try {
_hostname = InetAddress.getLocalHost().getHostName();
if (StringUtils.isBlank(_hostname)) {
_hostname = "localhost";
LOG.warn("Hostname was empty, using \"localhost\"");
}
} catch (UnknownHostException e) {
LOG.warn("Failed to determine node ID, using \"localhost\": " + e.getMessage(), e);
_hostname = "localhost";
}
hostname = _hostname;
return hostname;
}
/**
* Get the name of the application server [fleXive] is running on
*
* @return name of the application server [fleXive] is running on
* @since 3.1
*/
public synchronized static String getApplicationServerName() {
if (appserver != null)
return appserver;
if (System.getProperty("product.name") != null) {
// Glassfish 2 / Sun AS
String ver = System.getProperty("product.name");
if (System.getProperty("com.sun.jbi.domain.name") != null)
ver += " (Domain: " + System.getProperty("com.sun.jbi.domain.name") + ")";
appserver = ver;
} else if (System.getProperty("glassfish.version") != null) {
// Glassfish 3+
appserver = System.getProperty("glassfish.version");
} else if (System.getProperty("jboss.home.dir") != null) {
appserver = "JBoss (unknown version)";
boolean found = false;
try {
final Class<?> cls = Class.forName("org.jboss.Version");
Method m = cls.getMethod("getInstance");
Object v = m.invoke(null);
Method pr = cls.getMethod("getProperties");
Map props = (Map) pr.invoke(v);
String ver = inspectJBossVersionProperties(props);
found = true;
appserver = ver;
} catch (ClassNotFoundException e) {
//ignore
} catch (NoSuchMethodException e) {
//ignore
} catch (IllegalAccessException e) {
//ignore
} catch (InvocationTargetException e) {
//ignore
}
if (!found) {
// try JBoss 7 MBean lookup
try {
final ObjectName name = new ObjectName("jboss.as:management-root=server");
final Object version = ManagementFactory.getPlatformMBeanServer().getAttribute(name, "releaseVersion");
if (version != null) {
appserver = "JBoss (" + version + ")";
found = true;
}
} catch (Exception e) {
// ignore
}
}
if (!found) {
//try again with a JBoss 6.x specific locations
try {
final ClassLoader jbossCL = Class.forName("org.jboss.Main").getClassLoader();
if (jbossCL.getResource(JBOSS6_VERSION_PROPERTIES) != null) {
Properties prop = new Properties();
prop.load(jbossCL.getResourceAsStream(JBOSS6_VERSION_PROPERTIES));
if (prop.containsKey("version.name")) {
appserver = inspectJBossVersionProperties(prop);
//noinspection UnusedAssignment
found = true;
}
}
} catch (ClassNotFoundException e) {
//ignore
} catch (IOException e) {
//ignore
}
}
} else if (System.getProperty("openejb.version") != null) {
// try to get Jetty version
String jettyVersion = "";
try {
final Class<?> cls = Class.forName("org.mortbay.jetty.Server");
jettyVersion = " (Jetty "
+ cls.getPackage().getImplementationVersion()
+ ")";
} catch (ClassNotFoundException e) {
// no Jetty version...
}
appserver = "OpenEJB " + System.getProperty("openejb.version") + jettyVersion;
} else if (System.getProperty("weblogic.home") != null) {
String server = System.getProperty("weblogic.Name");
String wlVersion = "";
try {
final Class<?> cls = Class.forName("weblogic.common.internal.VersionInfo");
Method m = cls.getMethod("theOne");
Object serverVersion = m.invoke(null);
Method sv = m.invoke(null).getClass().getMethod("getImplementationVersion");
wlVersion = " " + String.valueOf(sv.invoke(serverVersion));
} catch (ClassNotFoundException e) {
//ignore
} catch (NoSuchMethodException e) {
//ignore
} catch (InvocationTargetException e) {
//ignore
} catch (IllegalAccessException e) {
//ignore
}
if (StringUtils.isEmpty(server))
appserver = "WebLogic" + wlVersion;
else
appserver = "WebLogic" + wlVersion + " (server: " + server + ")";
} else if (System.getProperty("org.apache.geronimo.home.dir") != null) {
String gVersion = "";
try {
final Class<?> cls = Class.forName("org.apache.geronimo.system.serverinfo.ServerConstants");
Method m = cls.getMethod("getVersion");
gVersion = " " + String.valueOf(m.invoke(null));
m = cls.getMethod("getBuildDate");
gVersion = gVersion + " (" + String.valueOf(m.invoke(null)) + ")";
} catch (ClassNotFoundException e) {
//ignore
} catch (NoSuchMethodException e) {
//ignore
} catch (InvocationTargetException e) {
//ignore
} catch (IllegalAccessException e) {
//ignore
}
appserver = "Apache Geronimo " + gVersion;
} else {
appserver = "unknown";
}
return appserver;
}
/**
* Inspect a map of JBoss specific properties and build a version String
* @param props properties
* @return JBoss version string
*/
private static String inspectJBossVersionProperties(Map props) {
String ver = "JBoss";
if (props.containsKey("version.major") && props.containsKey("version.minor")) {
if (props.containsKey("version.name"))
ver = ver + " [" + props.get("version.name") + "]";
ver = ver + " " + props.get("version.major") + "." + props.get("version.minor");
if (props.containsKey("version.revision"))
ver = ver + "." + props.get("version.revision");
if (props.containsKey("version.tag"))
ver = ver + " " + props.get("version.tag");
if (props.containsKey("build.day"))
ver = ver + " built " + props.get("build.day");
} else
ver = ver + " (unknown version)";
return ver;
}
/**
* Get the named resource from the current thread's classloader
*
* @param name name of the resource
* @return inputstream for the resource
*/
public static InputStream getResourceStream(String name) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
return cl.getResourceAsStream(name);
}
/**
* This method returns all entries in a JarInputStream for a given search pattern within the jar as a Map
* having the filename as the key and the file content as its respective value (String).
* The boolean flag "isFile" marks the search pattern as a file, otherwise the pattern will be treated as
* a path to be found in the jarStream
* A successful search either returns a map of all entries for a given path or a map of all entries for a given file
* (again, depending on the "isFile" flag).
* Null will be returned if no occurrences of the search pattern were found.
*
* @param jarStream the given JarInputStream
* @param searchPattern the pattern to be examined as a String
* @param isFile if true, the searchPattern is treated as a file name, if false, the searchPattern will be treated as a path
* @return Returns all entries found for the given search pattern as a Map<String, String>, or null if no matches were found
* @throws IOException on I/O errors
*/
public static Map<String, String> getContentsFromJarStream(JarInputStream jarStream, String searchPattern, boolean isFile) throws IOException {
Map<String, String> jarContents = new HashMap<String, String>();
int found = 0;
try {
if (jarStream != null) {
JarEntry entry;
while ((entry = jarStream.getNextJarEntry()) != null) {
if (isFile) {
if (!entry.isDirectory() && entry.getName().endsWith(searchPattern)) {
final String name = entry.getName().substring(entry.getName().lastIndexOf("/") + 1);
jarContents.put(name, readFromJarEntry(jarStream, entry));
found++;
}
} else {
if (!entry.isDirectory() && entry.getName().startsWith(searchPattern)) {
jarContents.put(entry.getName(), readFromJarEntry(jarStream, entry));
found++;
}
}
}
if (LOG.isDebugEnabled()) {
LOG.debug("Found " + found + " entries in the JarInputStream for the pattern " + searchPattern);
}
}
} finally {
if (jarStream != null) {
try {
jarStream.close();
} catch (IOException e) {
LOG.warn("Failed to close stream: " + e.getMessage(), e);
}
} else {
LOG.warn("JarInputStream parameter was null, no search performed");
}
}
return jarContents.isEmpty() ? null : jarContents;
}
/**
* Reads the content of a given entry in a Jar file (JarInputStream) and returns it as a String
*
* @param jarStream the given JarInputStream
* @param entry the given entry in the jar file
* @return the entry's content as a String
* @throws java.io.IOException on errors
*/
public static String readFromJarEntry(JarInputStream jarStream, JarEntry entry) throws IOException {
final String fileContent;
if (entry.getSize() >= 0) {
// allocate buffer for the entire (uncompressed) script code
final byte[] buffer = new byte[(int) entry.getSize()];
// decompress JAR entry
int offset = 0;
int readBytes;
while ((readBytes = jarStream.read(buffer, offset, (int) entry.getSize() - offset)) > 0) {
offset += readBytes;
}
if (offset != entry.getSize()) {
throw new IOException("Failed to read complete script code for script: " + entry.getName());
}
fileContent = new String(buffer, "UTF-8").trim();
} else {
// use this method if the file size cannot be determined
//(might be the case with jar files created with some jar tools)
final StringBuilder out = new StringBuilder();
final byte[] buf = new byte[1024];
int readBytes;
while ((readBytes = jarStream.read(buf, 0, buf.length)) > 0) {
out.append(new String(buf, 0, readBytes, "UTF-8"));
}
fileContent = out.toString();
}
return fileContent;
}
/**
* Get a list of all installed and deployed drops
*
* @return list of all installed and deployed drops
*/
public static synchronized List<String> getDrops() {
if (drops == null) {
initDropApplications();
}
return drops;
}
private static synchronized void initDropApplications() {
final List<FxDropApplication> apps = new ArrayList<FxDropApplication>();
addDropsFromArchiveIndex(apps);
addDropsFromClasspath(apps);
// sort lexically
Collections.sort(apps, new Comparator<FxDropApplication>() {
public int compare(FxDropApplication o1, FxDropApplication o2) {
return o1.getName().compareTo(o2.getName());
}
});
dropApplications = Collections.unmodifiableList(apps);
drops = new ArrayList<String>(dropApplications.size());
for (FxDropApplication dropApplication : dropApplications) {
drops.add(dropApplication.getName());
}
drops = Collections.unmodifiableList(drops);
if (LOG.isInfoEnabled()) {
LOG.info("Detected [fleXive] drop applications: " + drops);
}
}
/**
* Get a list of all installed and deployed drops.
*
* @return a list of all installed and deployed drops.
* @since 3.0.2
*/
public static synchronized List<FxDropApplication> getDropApplications() {
getDrops();
return dropApplications;
}
/**
* Returns the drop application with the given name.
*
* @param name the application name
* @return the drop application with the given name.
* @since 3.0.2
*/
public static synchronized FxDropApplication getDropApplication(String name) {
for (FxDropApplication dropApplication : getDropApplications()) {
if (dropApplication.getName().equalsIgnoreCase(name)) {
return dropApplication;
}
}
throw new FxNotFoundException("ex.sharedUtils.drop.notFound", name).asRuntimeException();
}
/**
* Add drop applications explicitly mentioned in the drops.archives file.
*
* @param dropApplications list of drop application info objects to be populated
*/
private static void addDropsFromArchiveIndex(List<FxDropApplication> dropApplications) {
try {
final String dropsList = loadFromInputStream(
Thread.currentThread().getContextClassLoader().getResourceAsStream("drops.archives")
);
if (StringUtils.isNotEmpty(dropsList)) {
for (String name : dropsList.split(",")) {
dropApplications.add(new FxDropApplication(name));
}
}
} catch (Exception e) {
LOG.error("Failed to parse drops.archives: " + e.getMessage(), e);
}
}
/**
* Add drop applications from the classpath (based on a file called flexive.properties).
*
* @param dropApplications list of drop application info objects to be populated
*/
private static void addDropsFromClasspath(List<FxDropApplication> dropApplications) {
try {
final Enumeration<URL> fileUrls =
Thread.currentThread().getContextClassLoader().getResources(FLEXIVE_DROP_PROPERTIES);
while (fileUrls.hasMoreElements()) {
final URL url = fileUrls.nextElement();
// load properties from file
final Properties properties = new Properties();
properties.load(url.openStream());
// load drop configuration parameters
final String name = properties.getProperty("name");
final String contextRoot = properties.getProperty("contextRoot");
final String displayName = properties.getProperty("displayName");
if (StringUtils.isNotBlank(name)) {
dropApplications.add(
new FxDropApplication(
name,
contextRoot,
defaultString(displayName, name),
url
)
);
}
}
} catch (IOException e) {
LOG.error("Failed to initialize drops from the classpath: " + e.getMessage(), e);
}
}
/**
* Scan all flexive storage implementations to get the name of the factory classes
*
* @return list containing the name of all storage factory classes
*/
public static List<String> getStorageImplementations() {
List<String> found = new ArrayList<String>(10);
try {
final Enumeration<URL> fileUrls =
Thread.currentThread().getContextClassLoader().getResources(FLEXIVE_STORAGE_PROPERTIES);
while (fileUrls.hasMoreElements()) {
final URL url = fileUrls.nextElement();
// load properties from file
final Properties properties = new Properties();
properties.load(url.openStream());
// load factory parameter
final String factory = properties.getProperty("storage.factory");
if (StringUtils.isNotBlank(factory))
found.add(factory);
}
} catch (IOException e) {
LOG.error("Failed to initialize storage implementations from the classpath: " + e.getMessage(), e);
}
return found;
}
/**
* Add all resources found in the resource subfolder for the requested vendor to the map (key=script name, value=script code)
*
* @param storageVendor requested vendor
* @return map with key=script name and value=script code
*/
public static Map<String, String> getStorageScriptResources(String storageVendor) {
Map<String, String> result = new HashMap<String, String>(100);
try {
final String indexFileName = "storageindex-" + storageVendor + ".flexive";
final String indexPath = "resources/" + indexFileName;
// open the storage index file
final URL url = Thread.currentThread().getContextClassLoader().getResource(indexPath);
if (url == null) {
LOG.error("No storage index found for vendor " + storageVendor);
return Maps.newHashMap();
}
// get a base URL (JAR or VFS-based) for the storage JAR entry
final int indexFilePos = url.getPath().indexOf(indexFileName);
if (indexFilePos == -1) {
LOG.warn("Failed to build base URL for storage based on URL: " + url.getPath());
}
final String basePath = url.getProtocol() + ":" + url.getPath().substring(0, indexFilePos);
final String[] resources = loadFromInputStream(url.openStream()).split("\n");
for (String line : resources) {
final int splitPos = line.indexOf('|');
if (splitPos == -1) {
LOG.warn("Failed to parse storage index line: " + line);
continue;
}
final String name = line.substring(0, splitPos);
if (name.endsWith(".sql")) {
try {
final URL resourceURL = new URL(basePath + name);
final String code = loadFromInputStream(resourceURL.openStream());
result.put(name, code);
} catch (FileNotFoundException e) {
LOG.warn(e);
}
}
}
} catch (IOException e) {
LOG.error(e);
}
return result;
}
/**
* Return the index of the given column name. If <code>name</code> has no
* prefix (e.g. "co."), then only a suffix match is performed (e.g.
* "name" matches "co.name" or "abc.name", whichever comes first.)
*
* @param columnNames all column names to be searched
* @param name the requested column name
* @return the 1-based index of the given column, or -1 if it does not exist
*/
public static int getColumnIndex(String[] columnNames, String name) {
final String upperName = name.toUpperCase();
final String upperPropertyName = "." + upperName;
final String upperAliasName = "AS " + upperName;
for (int i = 0; i < columnNames.length; i++) {
final String columnName = columnNames[i];
final String upperColumn = columnName.toUpperCase();
if (upperColumn.equals(upperName) || upperColumn.endsWith(upperPropertyName)
|| upperColumn.endsWith(upperAliasName)) {
return i + 1;
}
}
return -1;
}
/**
* Return the index of the given column name. If <code>name</code> has no
* prefix (e.g. "co."), then only a suffix match is performed (e.g.
* "name" matches "co.name" or "abc.name", whichever comes first.)
*
* @param columnNames all column names to be searched
* @param name the requested column name
* @return the 1-based index of the given column, or -1 if it does not exist
*/
public static int getColumnIndex(List<String> columnNames, String name) {
return getColumnIndex(columnNames.toArray(new String[columnNames.size()]), name);
}
/**
* Compute the hash of the given flexive password, using the user ID.
*
* @param accountId the user account ID
* @param password the cleartext password
* @return a hashed password
*/
public static String hashPassword(long accountId, String password) {
try {
return sha1Hash(getBytes("FX-SALT" + accountId + password));
} catch (NoSuchAlgorithmException e) {
throw new FxCreateException("Failed to load the SHA1 algorithm.").asRuntimeException();
}
}
/**
* Compute the hash of the given flexive password using the login name. This is the default algorithm
* for installations since flexive 3.1.6.
*
* @param loginName the user login name
* @param password the cleartext password
* @return the hashed password
* @since 3.1.6
*/
public static String hashPassword(String loginName, String password) {
try {
return sha1Hash(getBytes("FX-SALT-" + loginName + "-" + password));
} catch (NoSuchAlgorithmException e) {
throw new FxCreateException("Failed to load the SHA1 algorithm.").asRuntimeException();
}
}
/**
* Compute the hash of the given password according to the setting in
* {@link com.flexive.shared.configuration.SystemParameters#PASSWORD_SALT_METHOD} (either with the user ID, or the user name).
*
* @param accountId the user account ID
* @param loginName the login name
* @param password the cleartext password
* @return the hashed password
* @since 3.1.6
*/
public static String hashPassword(long accountId, String loginName, String password) {
final String method;
try {
method = EJBLookup.getConfigurationEngine().get(SystemParameters.PASSWORD_SALT_METHOD);
} catch (FxApplicationException ex) {
throw ex.asRuntimeException();
}
if ("userid".equals(method)) {
if (accountId == -1) {
throw new IllegalArgumentException("Account-ID not set, but hash method set to userid");
}
return hashPassword(accountId, password);
} else if ("loginname".equals(method)) {
FxSharedUtils.checkParameterEmpty(loginName, "loginName");
return hashPassword(loginName, password);
} else {
throw new IllegalArgumentException("Unknown hash method: " + method);
}
}
/**
* Returns a collator for the calling user's locale.
*
* @return a collator for the calling user's locale.
*/
public static Collator getCollator() {
return Collator.getInstance(FxContext.getUserTicket().getLanguage().getLocale());
}
/**
* Is the script (most likely) a groovy script?
*
* @param name script name to check
* @return if this script could be a groovy script
*/
public static boolean isGroovyScript(String name) {
return name.toLowerCase().endsWith(".gy") || name.toLowerCase().endsWith(".groovy");
}
/**
* Check if the given parameter is multilingual and throw an exception if not
*
* @param value the value to check
* @param paramName name of the parameter
*/
public static void checkParameterMultilang(FxValue value, String paramName) {
if (value != null && !value.isMultiLanguage())
throw new FxInvalidParameterException(paramName, "ex.general.parameter.notMultilang", paramName).asRuntimeException();
}
/**
* Maps keys to values. Used for constructing JSF-EL parameter
* mapper objects for assicative lookups.
*/
public static interface ParameterMapper<K, V> extends Serializable {
V get(Object key);
}
/**
* Private constructor
*/
private FxSharedUtils() {
}
/**
* Creates a SHA-1 hash for the given data and returns it
* in hexadecimal string encoding.
*
* @param bytes data to be hashed
* @return hex-encoded hash
* @throws java.security.NoSuchAlgorithmException
* if the SHA-1 provider does not exist
*/
public static String sha1Hash(byte[] bytes) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(bytes);
return FxFormatUtils.encodeHex(md.digest());
}
/**
* Calculate an MD5 checksum for a file
*
* @param file file to calculate checksum for
* @return MD5 checksum (16 characters)
*/
public static String getMD5Sum(File file) {
InputStream is = null;
String md5sum = "unknown";
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
is = new FileInputStream(file);
byte[] buffer = new byte[8192];
int read;
while ((read = is.read(buffer)) > 0)
digest.update(buffer, 0, read);
BigInteger bigInt = new BigInteger(1, digest.digest());
md5sum = bigInt.toString(16);
} catch (IOException e) {
LOG.error("Unable calculate MD5 checksum!", e);
} catch (NoSuchAlgorithmException e) {
LOG.error("No MD5 algorithm found!", e);
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
//ignore
}
}
return md5sum;
}
/**
* Helperclass holding the result of the <code>executeCommand</code> method
*
* @see FxSharedUtils#executeCommand(String, String...)
*/
public static final class ProcessResult {
private String commandLine;
private int exitCode;
private String stdOut, stdErr;
/**
* Constructor
*
* @param commandLine the commandline executed
* @param exitCode exit code
* @param stdOut result from stdOut
* @param stdErr result from stdErr
*/
public ProcessResult(String commandLine, int exitCode, String stdOut, String stdErr) {
this.commandLine = commandLine;
this.exitCode = exitCode;
this.stdOut = stdOut;
this.stdErr = stdErr;
}
/**
* Getter for the commandline
*
* @return commandline
*/
public String getCommandLine() {
return commandLine;
}
/**
* Getter for the exit code
*
* @return exit code
*/
public int getExitCode() {
return exitCode;
}
/**
* Getter for stdOut
*
* @return stdOut
*/
public String getStdOut() {
return stdOut;
}
/**
* Getter for stdErr
*
* @return stdErr
*/
public String getStdErr() {
return stdErr;
}
}
/**
* Helper thread to asynchronously read and buffer an InputStream
*/
static final class AsyncStreamBuffer extends Thread {
protected InputStream in;
protected StringBuffer sb = new StringBuffer();
/**
* Constructor
*
* @param in the InputStream to buffer
*/
AsyncStreamBuffer(InputStream in) {
this.in = in;
}
/**
* Getter for the buffered result
*
* @return buffered result
*/
public String getResult() {
return sb.toString();
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null)
sb.append(line).append('\n');
} catch (IOException e) {
sb.append("[Error: ").append(e.getMessage()).append("]");
}
}
}
/**
* Execute a command on the operating system
*
* @param command name of the command
* @param arguments arguments to pass to the command (one argument per String!)
* @return result
*/
public static ProcessResult executeCommand(String command, String... arguments) {
Runtime r = Runtime.getRuntime();
String[] cmd = new String[arguments.length + (WINDOWS ? 3 : 1)];
if (WINDOWS) {
//have to run a shell on windows
cmd[0] = "cmd";
cmd[1] = "/c";
}
cmd[WINDOWS ? 2 : 0] = command;
System.arraycopy(arguments, 0, cmd, (WINDOWS ? 3 : 1), arguments.length);
StringBuilder cmdline = new StringBuilder(200);
cmdline.append(command);
for (String argument : arguments) cmdline.append(" ").append(argument);
Process p = null;
AsyncStreamBuffer out = null;
AsyncStreamBuffer err = null;
try {
p = r.exec(cmd);
// p = r.exec(cmdline);
out = new AsyncStreamBuffer(p.getInputStream());
err = new AsyncStreamBuffer(p.getErrorStream());
out.start();
err.start();
p.waitFor();
while (out.isAlive()) Thread.sleep(10);
while (err.isAlive()) Thread.sleep(10);
} catch (Exception e) {
String error = e.getMessage();
if (err != null && err.getResult() != null && err.getResult().trim().length() > 0)
error = error + "(" + err.getResult() + ")";
return new ProcessResult(cmdline.toString(), (p == null ? -1 : p.exitValue()), (out == null ? "" : out.getResult()), error);
} finally {
if (p != null) {
try {
p.getInputStream().close();
} catch (Exception e1) {
//bad luck
}
try {
p.getErrorStream().close();
} catch (Exception e1) {
//bad luck
}
try {
p.getOutputStream().close();
} catch (Exception e1) {
//bad luck
}
}
}
return new ProcessResult(cmdline.toString(), p.exitValue(), out.getResult(), err.getResult());
}
/**
* Load the contents of a file, returning it as a String.
* This method should only be used when really necessary since no real error handling is performed!!!
*
* @param file the File to load
* @return file contents
*/
public static String loadFile(File file) {
try {
return loadFromInputStream(new FileInputStream(file), (int) file.length());
} catch (FileNotFoundException e) {
LOG.error(e);
return "";
}
}
/**
* Load a String from an InputStream (until end of stream)
*
* @param in InputStream
* @return the input stream contents, or an empty string if {@code in} was null.
* @since 3.0.2
*/
public static String loadFromInputStream(InputStream in) {
return loadFromInputStream(in, -1);
}
/**
* Load a String from an InputStream (until end of stream)
*
* @param in InputStream
* @param length length of the string if > -1 (NOT number of bytes to read!)
* @return the input stream contents, or an empty string if {@code in} was null.
*/
public static String loadFromInputStream(InputStream in, int length) {
if (in == null) {
return "";
}
final BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charsets.UTF_8));
try {
return CharStreams.toString(reader);
} catch (IOException e) {
throw new IllegalStateException(e);
} finally {
close(reader);
}
}
/**
* Rather primitive "write String to file" helper, returns <code>false</code> if failed
*
* @param contents the String to store
* @param file the file, if existing it will be overwritten
* @return if successful
*/
public static boolean storeFile(String contents, File file) {
if (file.exists()) {
LOG.warn("Warning: " + file.getName() + " already exists! Overwriting!");
}
FileOutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(FxSharedUtils.getBytes(contents));
out.flush();
out.close();
return true;
} catch (IOException e) {
LOG.error("Failed to store " + file.getAbsolutePath() + ": " + e.getMessage());
return false;
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
//ignore
}
}
}
}
/**
* Get the flexive version
*
* @return flexive version
*/
public static String getFlexiveVersion() {
return fxVersion;
}
/**
* Returns true if this instance is a -SNAPSHOT version.
*
* @return true if this instance is a -SNAPSHOT version.
* @since 3.1
*/
public static boolean isSnapshotVersion() {
return fxSnapshotVersion;
}
/**
* Get the subversion build number
*
* @return subversion build number
*/
public static String getBuildNumber() {
return fxBuild;
}
/**
* Get the database version
*
* @return database version
*/
public static long getDBVersion() {
return fxDBVersion;
}
/**
* Get the date flexive was compiled
*
* @return compile date
*/
public static String getBuildDate() {
return fxBuildDate;
}
/**
* Get the name of this flexive edition
*
* @return flexive edition
*/
public static String getFlexiveEdition() {
return fxEdition;
}
/**
* Get the name of this flexive edition with the product name
*
* @return flexive edition with product name
*/
public static String getFlexiveEditionFull() {
return fxEdition + "." + fxProduct;
}
/**
* Get the name of the user that built flexive
*
* @return build user
*/
public static String getBuildUser() {
return fxBuildUser;
}
/**
* Get the default html header title
*
* @return html header title
*/
public static String getHeader() {
return fxHeader;
}
/**
* Get the version of the bundled groovy runtime
*
* @return version of the bundled groovy runtime
*/
public static synchronized String getBundledGroovyVersion() {
if (bundledGroovyVersion == null) {
// lazy loading to avoid Groovy initialization at deployment
bundledGroovyVersion = GroovySystem.getVersion();
}
return bundledGroovyVersion;
}
/**
* Returns the localized "empty" message for empty result fields
*
* @return the localized "empty" message for empty result fields
*/
public static String getEmptyResultMessage() {
final FxLanguage language = FxContext.getUserTicket().getLanguage();
return getLocalizedMessage(SHARED_BUNDLE, language.getId(), language.getIso2digit(), "shared.result.emptyValue");
}
/**
* Check if the given value is empty (empty string or null for String objects, empty collection,
* null for other objects) and throw an exception if empty.
*
* @param value value to check
* @param parameterName name of the value (for the exception)
*/
public static void checkParameterNull(Object value, String parameterName) {
if (value == null) {
throw new FxInvalidParameterException(parameterName, "ex.general.parameter.null", parameterName).asRuntimeException();
}
}
/**
* Check if the given value is empty (empty string or null for String objects, empty collection,
* null for other objects) and throw an exception if empty.
*
* @param value value to check
* @param parameterName name of the value (for the exception)
*/
public static void checkParameterEmpty(Object value, String parameterName) {
if (value == null
|| (value instanceof String && StringUtils.isBlank((String) value))
|| (value instanceof Collection && ((Collection) value).isEmpty())) {
throw new FxInvalidParameterException(parameterName, "ex.general.parameter.empty", parameterName).asRuntimeException();
}
}
/**
* Try to find a localized resource messages
*
* @param resourceBundle the name of the resource bundle to retrieve the message from
* @param key resource key
* @param localeIso locale of the resource bundle
* @return resource from a localized bundle
*/
public static String lookupResource(String resourceBundle, String key, String localeIso) {
String result = _lookupResource(resourceBundle, key, localeIso);
if (result == null) {
for (String drop : getDrops()) {
result = _lookupResource(drop + "Resources/" + resourceBundle, key, localeIso);
if (result != null)
return result;
}
}
return result;
}
private static String _lookupResource(String resourceBundle, String key, String localeIso) {
try {
String isoCode = localeIso != null ? localeIso : Locale.getDefault().getLanguage();
PropertyResourceBundle bundle = (PropertyResourceBundle) PropertyResourceBundle.getBundle(resourceBundle, new Locale(isoCode));
return bundle.getString(key);
} catch (MissingResourceException e) {
//try default (english) locale
try {
PropertyResourceBundle bundle = (PropertyResourceBundle) PropertyResourceBundle.getBundle(resourceBundle, Locale.ENGLISH);
return bundle.getString(key);
} catch (MissingResourceException e1) {
return null;
}
}
}
/**
* Get the localized message for a given language code and ISO
*
* @param resourceBundle the resource bundle to use
* @param localeId used locale if args contain FxString instances
* @param localeIso ISO code of the requested locale
* @param key the key in the resource bundle
* @param args arguments to replace in the message ({n})
* @return localized message
*/
public static String getLocalizedMessage(String resourceBundle, long localeId, String localeIso, String key, Object... args) {
if (key == null) {
//noinspection ThrowableInstanceNeverThrown
LOG.error("No key given!", new Throwable());
return "??NO_KEY_GIVEN";
}
String resource = lookupResource(resourceBundle, key, localeIso);
if (resource == null) {
//try to fallback to PluginMessages ...
resource = lookupResource("PluginMessages", key, localeIso);
if (resource == null) {
// LOG.warn("Called with unlocalized Message [" + key + "]. See StackTrace for origin!", new Throwable());
return key;
}
}
//lookup possible resource keys in values (they may not have placeholders like {n} though)
String tmp;
for (int i = 0; i < args.length; i++) {
Object o = args[i];
if (o instanceof String && ((String) o).indexOf(' ') == -1 && ((String) o).indexOf('.') > 0)
if ((tmp = lookupResource(resourceBundle, (String) o, localeIso)) != null)
args[i] = tmp;
}
return FxFormatUtils.formatResource(resource, localeId, args);
}
/**
* Returns true if the given locale is localized in the flexive application
* (compile-time parameter flexive.translatedLocales set in flexive.properties).
*
* @param localeIsoCode the locale ISO code, e.g. "en" or "de"
* @return true if the given locale is localized (at least for some messages).
* @since 3.1
*/
public static boolean isTranslatedLocale(String localeIsoCode) {
for (String locale : translatedLocales) {
if (locale.equalsIgnoreCase(localeIsoCode)) {
return true;
}
}
return false;
}
/**
* Returns the list of translated locales, as specified in flexive.properties
* (flexive.translatedLocales).
*
* @return the list of translated locales, in lowercase
* @since 3.1
*/
public static List<String> getTranslatedLocales() {
return translatedLocales;
}
/**
* Returns a multilingual FxString with all translations for the given property key.
*
* @param resourceBundle the resource bundle to be used
* @param key the message key
* @param args optional parameters to be replaced in the property translations
* @return a multilingual FxString with all translations for the given property key.
*/
public static FxString getMessage(String resourceBundle, String key, Object... args) {
Map<Long, String> translations = new HashMap<Long, String>();
for (String localeIso : translatedLocales) {
final long localeId = new FxLanguage(localeIso).getId();
translations.put(localeId, getLocalizedMessage(resourceBundle, localeId, localeIso, key, args));
}
return new FxString(translations);
}
/**
* Returns the localized label for the given enum value. The enum translations are
* stored in FxSharedMessages.properties and are standardized as
* {@code FQCN.value},
* e.g. {@code com.flexive.shared.search.query.ValueComparator.LIKE}.
*
* @param value the enum value to be translated
* @param args optional arguments to be replaced in the localized messages
* @return the localized label for the given enum value
*/
public static FxString getEnumLabel(Enum<?> value, Object... args) {
final Class<? extends Enum> valueClass = value.getClass();
final String clsName;
if (valueClass.getEnclosingClass() != null && Enum.class.isAssignableFrom(valueClass.getEnclosingClass())) {
// don't include anonymous inner class definitions often used by enums in class name
clsName = valueClass.getEnclosingClass().getName();
} else {
clsName = valueClass.getName();
}
return getMessage(SHARED_BUNDLE, clsName + "." + value.name(), args);
}
/**
* Returns a list of all used step definitions for the given steps
*
* @param steps list of steps to be examined
* @param stepDefinitions all defined step definitions
* @return a list of all used step definitions for this workflow
*/
public static List<StepDefinition> getUsedStepDefinitions(List<? extends Step> steps, List<? extends StepDefinition> stepDefinitions) {
List<StepDefinition> result = new ArrayList<StepDefinition>(steps.size());
for (Step step : steps) {
for (StepDefinition stepDefinition : stepDefinitions) {
if (step.getStepDefinitionId() == stepDefinition.getId()) {
result.add(stepDefinition);
break;
}
}
}
return result;
}
/**
* Splits the given text using separator. String literals are supported, e.g.
* abc,def yields two elements, but 'abc,def' yields one (stringDelims = ['\''], separator = ',').
*
* @param text the text to be splitted
* @param stringDelims delimiters for literal string values, usually ' and "
* @param separator separator between tokens
* @return split string
*/
public static String[] splitLiterals(String text, char[] stringDelims, char separator) {
if (text == null) {
return new String[0];
}
List<String> result = new ArrayList<String>();
Character currentStringDelim = null;
int startIndex = 0;
for (int i = 0; i < text.length(); i++) {
char character = text.charAt(i);
if (character == separator && currentStringDelim == null) {
// not in string
if (startIndex != -1) {
result.add(text.substring(startIndex, i).trim());
}
startIndex = i + 1;
} else if (currentStringDelim != null && currentStringDelim == character) {
// end string
result.add(text.substring(startIndex, i).trim());
currentStringDelim = null;
startIndex = -1;
} else if (currentStringDelim != null) {
// continue in string literal
} else if (ArrayUtils.contains(stringDelims, character)) {
// begin string literal
currentStringDelim = character;
// skip string delim
startIndex = i + 1;
}
}
if (startIndex != -1 && startIndex <= text.length()) {
// add last parameter
result.add(text.substring(startIndex, text.length()).trim());
}
return result.toArray(new String[result.size()]);
}
/**
* Splits the given comma-separated text. String literals are supported, e.g.
* abc,def yields two elements, but 'abc,def' yields one.
*
* @param text the text to be splitted
* @return split string
*/
public static String[] splitLiterals(String text) {
return splitLiterals(text, new char[]{'\'', '"'}, ',');
}
/**
* Projects a single-parameter function on a hashmap.
* Useful for calling parameterized functions from JSF-EL. Results are not cached by default, use
* {@link #getMappedFunction(com.flexive.shared.FxSharedUtils.ParameterMapper, boolean)}
* to create a caching mapper.
*
* @param mapper the parameter mapper wrapping the function to be called
* @return a hashmap projected on the given parameter mapper
*/
public static <K, V> Map<K, V> getMappedFunction(final ParameterMapper<K, V> mapper) {
return new HashMap<K, V>() {
private static final long serialVersionUID = 1051489436850755246L;
@Override
public V get(Object key) {
return mapper.get(key);
}
};
}
/**
* Projects a single-parameter function on a hashmap.
* Useful for calling parameterized functions from JSF-EL. Values returned by the mapper
* can be cached in the hash map.
*
* @param mapper the parameter mapper wrapping the function to be called
* @param cacheResults if the mapper results should be cached by the map
* @return a hashmap projected on the given parameter mapper
* @since 3.1
*/
public static <K, V> Map<K, V> getMappedFunction(final ParameterMapper<K, V> mapper, boolean cacheResults) {
if (cacheResults) {
return new HashMap<K, V>() {
private static final long serialVersionUID = 1051489436850755246L;
@SuppressWarnings({"unchecked"})
@Override
public V get(Object key) {
if (!containsKey(key)) {
put((K) key, mapper.get(key));
}
return super.get(key);
}
};
} else {
return getMappedFunction(mapper);
}
}
/**
* Escape a path for usage on the current operating systems shell
*
* @param path path to escape
* @return escaped path
*/
public static String escapePath(String path) {
if (WINDOWS)
return "\"" + path + "\"";
else
return path.replace(" ", "\\ ");
}
/**
* Escapes the given XPath for use in a public URI.
*
* @param xpath the xpath to be escaped
* @return the given XPath for use in a public URI.
* @see #decodeXPath(String)
*/
public static String escapeXPath(String xpath) {
return StringUtils.replace(xpath, "/", XPATH_ENCODEDSLASH);
}
/**
* Decodes a previously escaped XPath.
*
* @param escapedXPath the escaped XPath
* @return the decoded XPath
* @see #escapeXPath(String)
*/
public static String decodeXPath(String escapedXPath) {
return StringUtils.replace(escapedXPath, XPATH_ENCODEDSLASH, "/");
}
/**
* Returns <code>map.get(key)</code> if <code>key</code> exists, <code>defaultValue</code> otherwise.
*
* @param map a map
* @param key the required key
* @param defaultValue the default value to be returned if <code>key</code> does not exist in <code>map</code>
* @return <code>map.get(key)</code> if <code>key</code> exists, <code>defaultValue</code> otherwise.
*/
public static <K, V> V get(Map<K, V> map, K key, V defaultValue) {
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* Returns true if the given string value is quoted with the given character (e.g. 'value').
*
* @param value the string value to be checked
* @param quoteChar the quote character, for example '
* @return true if the given string value is quoted with the given character (e.g. 'value').
*/
public static boolean isQuoted(String value, char quoteChar) {
return value != null && value.length() >= 2
&& value.charAt(0) == quoteChar && value.charAt(value.length() - 1) == quoteChar;
}
/**
* Strips the quotes from the given string if it is quoted, otherwise it returns
* the input value itself.
*
* @param value the value to be "unquoted"
* @param quoteChar the quote character, for example '
* @return the unquoted string, or <code>value</code>, if it was not quoted
*/
public static String stripQuotes(String value, char quoteChar) {
if (isQuoted(value, quoteChar)) {
return value.substring(1, value.length() - 1);
}
return value;
}
/**
* Returns the UTF-8 byte representation of the given string. Use this instead of
* {@link String#getBytes()}, since the latter will fail if the system locale is not UTF-8.
*
* @param s the string to be processed
* @return the UTF-8 byte representation of the given string
*/
public static byte[] getBytes(String s) {
- return s.getBytes(Charsets.UTF_8);
+ try {
+ return s.getBytes("UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ if (LOG.isWarnEnabled()) {
+ LOG.warn("Failed to decode UTF-8 string: " + e.getMessage(), e);
+ }
+ return s.getBytes();
+ }
}
/**
* Extracts the names of the given enum elements and returns them as string.
* Useful if the toString() method of the Enum class was overwritten.
*
* @param values the enum values
* @return the names of the given enum elements
*/
public static List<String> getEnumNames(Collection<? extends Enum> values) {
final List<String> result = new ArrayList<String>(values.size());
for (final Enum value : values) {
result.add(value.name());
}
return result;
}
/**
* Extract the unique IDs of the given {@link SelectableObject} collection.
*
* @param values the input values
* @return the IDs of the input values
* @since 3.1
*/
public static List<Long> getSelectableObjectIdList(Iterable<? extends SelectableObject> values) {
final List<Long> result = new ArrayList<Long>();
for (SelectableObject value : values) {
result.add(value.getId());
}
return result;
}
/**
* Extract the unique names of the given {@link SelectableObject} collection.
*
* @param values the input values
* @return the IDs of the input values
* @since 3.1
*/
public static List<String> getSelectableObjectNameList(Iterable<? extends SelectableObjectWithName> values) {
final List<String> result = new ArrayList<String>();
for (SelectableObjectWithName value : values) {
result.add(value.getName());
}
return result;
}
/**
* Returns the index of the {@link SelectableObject} with the given ID, or -1 if none was found.
*
* @param values the values to be examined
* @param id the target ID
* @return the index of the {@link SelectableObject} with the given ID, or -1 if none was found.
*/
public static int indexOfSelectableObject(List<? extends SelectableObject> values, long id) {
for (int i = 0; i < values.size(); i++) {
final SelectableObject object = values.get(i);
if (object.getId() == id) {
return i;
}
}
return -1;
}
/**
* Return a {@link SelectableObject} by its ID.
*
* @param values the values to search
* @param id the ID to look for
* @param <T> the value type
* @return the first matching value
* @throws com.flexive.shared.exceptions.FxRuntimeException if no element with the given ID was found
* @since 3.2.0
*/
public static <T extends SelectableObject> T getSelectableObject(List<T> values, long id) {
for (T value : values) {
if (value.getId() == id) {
return value;
}
}
throw new FxNotFoundException("ex.selectable.id.notFound", id).asRuntimeException();
}
/**
* Return the elements of {@code values} that match the given {@code ids}.
*
* @param values the values to be search
* @param ids the required IDs
* @param <T> the value type
* @return the elements of {@code values} that match the given {@code ids}.
* @since 3.1
*/
public static <T extends SelectableObject> List<T> filterSelectableObjectsById(Iterable<T> values, Collection<Long> ids) {
final List<T> result = Lists.newArrayListWithCapacity(ids.size());
for (T value : values) {
if (ids.contains(value.getId())) {
result.add(value);
}
}
return result;
}
/**
* Return the elements of {@code values} that match the given {@code names}.
*
* @param values the values to be search
* @param names the required IDs
* @param <T> the value type
* @return the elements of {@code values} that match the given {@code names}.
* @since 3.1
*/
public static <T extends SelectableObjectWithName> List<T> filterSelectableObjectsByName(Iterable<T> values, Collection<String> names) {
final List<T> result = Lists.newArrayListWithCapacity(names.size());
for (T value : values) {
if (names.contains(value.getName())) {
result.add(value);
}
}
return result;
}
/**
* Primitive int comparison method (when JDK7's Integer#compare cannot be used).
* For float and double, see {@link org.apache.commons.lang.NumberUtils}.
*
* @param i1 the first value
* @param i2 the second value
* @return see {@link Integer#compareTo}
* @since 3.2.0
*/
public static int compare(int i1, int i2) {
if (i1 < i2) {
return -1;
} else if (i1 == i2) {
return 0;
} else {
return 1;
}
}
/**
* Primitive long comparison method (when JDK7's Long#compare cannot be used).
* For float and double, see {@link org.apache.commons.lang.NumberUtils}.
*
* @param i1 the first value
* @param i2 the second value
* @return see {@link Integer#compareTo}
* @since 3.2.0
*/
public static int compare(long i1, long i2) {
if (i1 < i2) {
return -1;
} else if (i1 == i2) {
return 0;
} else {
return 1;
}
}
/**
* Comparator for sorting Assignments according to their position.
*/
public static class AssignmentPositionSorter implements Comparator<FxAssignment>, Serializable {
private static final long serialVersionUID = 9197582519027523108L;
public int compare(FxAssignment o1, FxAssignment o2) {
return FxSharedUtils.compare(o1.getPosition(), o2.getPosition());
}
}
/**
* Comparator for sorting {@link SelectableObjectWithName} instances by ID.
*/
public static class SelectableObjectSorter implements Comparator<SelectableObject>, Serializable {
private static final long serialVersionUID = -1786371691872260074L;
public int compare(SelectableObject o1, SelectableObject o2) {
return FxSharedUtils.compare(o1.getId(), o2.getId());
}
}
/**
* Comparator for sorting {@link SelectableObjectWithName} instances by name.
*/
public static class SelectableObjectWithNameSorter implements Comparator<SelectableObjectWithName>, Serializable {
private static final long serialVersionUID = -1786371691872260074L;
public int compare(SelectableObjectWithName o1, SelectableObjectWithName o2) {
return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
}
}
/**
* Comparator for sorting {@link SelectableObjectWithLabel} instances by label.
*/
public static class SelectableObjectWithLabelSorter implements Comparator<SelectableObjectWithLabel>, Serializable {
public int compare(SelectableObjectWithLabel o1, SelectableObjectWithLabel o2) {
return o1.getLabel().getBestTranslation().toLowerCase().compareTo(o2.getLabel().getBestTranslation().toLowerCase());
}
}
/**
* Item sorter by position
*/
public static class ItemPositionSorter implements Comparator<FxSelectListItem>, Serializable {
private static final long serialVersionUID = 3366660003069358959L;
public int compare(FxSelectListItem i1, FxSelectListItem i2) {
return FxSharedUtils.compare(i1.getPosition(), i2.getPosition());
}
}
/**
* Item sorter by label
*/
public static class ItemLabelSorter implements Comparator<FxSelectListItem>, Serializable {
private static final long serialVersionUID = 2366364003069358945L;
private final FxLanguage language;
private final Collator collator;
private final Map<String, CollationKey> uppercaseLabels;
/**
* Ctor
*
* @param language the language used for sorting
*/
public ItemLabelSorter(FxLanguage language) {
this.language = language;
this.collator = Collator.getInstance(language.getLocale());
this.uppercaseLabels = Maps.newHashMap(); // cache collation keys for case-insensitive comparisons
}
/**
* {@inheritDoc}
*/
public int compare(FxSelectListItem i1, FxSelectListItem i2) {
final String label1 = i1.getLabel().getBestTranslation(language);
final String label2 = i2.getLabel().getBestTranslation(language);
if (!uppercaseLabels.containsKey(label1)) {
uppercaseLabels.put(label1, collator.getCollationKey(StringUtils.defaultString(label1).toUpperCase(language.getLocale())));
}
if (!uppercaseLabels.containsKey(label2)) {
uppercaseLabels.put(label2, collator.getCollationKey(StringUtils.defaultString(label2).toUpperCase(language.getLocale())));
}
return uppercaseLabels.get(label1).compareTo(uppercaseLabels.get(label2));
}
}
/**
* An SQL executor, similar to ant's sql task
* An important addition are raw blocks:
* lines starting with '-- @START@' indicate the start of a raw block and lines starting with '-- @END@'
* indicate the end of a raw block.
* Raw blocks are passed "as is" to the database as one string
*/
public static class SQLExecutor {
private Connection con;
private Statement stmt = null;
private String code;
private int count = 0;
private String delimiter;
private boolean keepformat;
private boolean rowDelimiter;
private PrintStream out;
/**
* Ctor
*
* @param con an open and valid connection
* @param code the source sql code
* @param delimiter delimiter to use
* @param rowDelimiter is the delimiter or row delimiter?
* @param keepformat keep original format?
* @param out stream for messages
*/
public SQLExecutor(Connection con, String code, String delimiter, boolean rowDelimiter, boolean keepformat, PrintStream out) {
this.con = con;
this.code = code;
this.delimiter = delimiter;
this.rowDelimiter = rowDelimiter;
this.keepformat = keepformat;
this.out = out;
}
/**
* Main execute method, returns number of updates
*
* @return number of updates
* @throws SQLException on errors
* @throws IOException on errors
*/
public int execute() throws SQLException, IOException {
stmt = con.createStatement();
try {
StringBuffer sql = new StringBuffer();
String line;
BufferedReader in = new BufferedReader(new StringReader(code));
boolean inRawBlock = false;
while ((line = in.readLine()) != null) {
line = line.trim();
if (inRawBlock) {
if (line.startsWith("--") && line.indexOf("@END@") > 0) {
inRawBlock = false;
if (sql.length() > 0) {
// System.out.println("Executing raw block:\n" + sql.toString());
execute(sql.toString());
sql.replace(0, sql.length(), "");
}
} else
sql.append(line).append('\n');
continue;
}
if (line.startsWith("//") || line.startsWith("--")) {
if (line.indexOf("@START@") > 0)
inRawBlock = true;
continue;
}
StringTokenizer st = new StringTokenizer(line);
if (st.hasMoreTokens()) {
String token = st.nextToken();
if ("REM".equalsIgnoreCase(token))
continue;
}
sql.append("\n").append(line);
if (!keepformat && line.indexOf("--") >= 0)
sql.append("\n");
if (!rowDelimiter && StringUtils.endsWith(sql.toString(), delimiter)
|| (rowDelimiter && line.equals(delimiter))) {
execute(sql.substring(0, sql.length() - delimiter.length()));
sql.replace(0, sql.length(), "");
}
}
if (sql.length() > 0)
execute(sql.toString());
} finally {
if (stmt != null)
stmt.close();
}
return count;
}
/**
* Execute a single SQL statement
*
* @param sql statement
* @throws SQLException on errors
*/
private void execute(String sql) throws SQLException {
if ("".equals(sql.trim()))
return;
ResultSet rs = null;
try {
count++;
boolean ret;
stmt.execute(sql);
rs = stmt.getResultSet();
do {
ret = stmt.getMoreResults();
if (ret) {
rs = stmt.getResultSet();
}
} while (ret);
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) SQLWarning warning = con.getWarnings();
while (warning != null) {
out.println("Warning: " + warning);
warning = warning.getNextWarning();
}
con.clearWarnings();
} catch (SQLException e) {
out.println("Failed to execute: " + sql);
throw e;
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
//ignore
}
}
}
}
}
/**
* A resource bundle reference.
*/
public static class BundleReference {
private final String baseName;
private final URL resourceURL;
/**
* Create a new bundle reference.
*
* @param baseName the fully qualified base name (e.g. "ApplicationResources")
* @param resourceURL the resource URL to be used for loading the resource bundle. If null,
* the context class loader will be used.
*/
public BundleReference(String baseName, URL resourceURL) {
this.baseName = baseName;
this.resourceURL = resourceURL;
}
/**
* Returns the base name of the resource bundle (e.g. "ApplicationResources").
*
* @return the base name of the resource bundle (e.g. "ApplicationResources").
*/
public String getBaseName() {
return baseName;
}
/**
* Returns the class loader to be used for loading the bundle.
*
* @return the class loader to be used for loading the bundle.
*/
public URL getResourceURL() {
return resourceURL;
}
/**
* Return the resource bundle in the given locale.
*
* @param locale the requested locale
* @return the resource bundle in the given locale.
*/
public ResourceBundle getBundle(Locale locale) {
if (this.resourceURL == null) {
return ResourceBundle.getBundle(baseName, locale);
} else {
try {
return ResourceBundle.getBundle(baseName, locale, new URLClassLoader(new URL[]{resourceURL}));
} catch (MissingResourceException mre) {
//fix for JBoss 5 vfs which doesn't work with classloader
try {
//try to find in the desired locale
Enumeration<URL> e = Thread.currentThread().getContextClassLoader().getResources(baseName + "_" + locale.getLanguage() + ".properties");
String orgPath = resourceURL.toExternalForm().substring(0, resourceURL.toExternalForm().lastIndexOf("/"));
while (e.hasMoreElements()) {
URL resource = e.nextElement();
if (orgPath.equals(resource.toExternalForm().substring(0, resource.toExternalForm().lastIndexOf("/")))) {
return new PropertyResourceBundle(resource.openStream());
}
}
//Fallback to the default locale
return new PropertyResourceBundle(resourceURL.openStream());
} catch (IOException e) {
LOG.warn("Failed to retrieve bundle " + baseName + " directly from stream");
}
//last resort
return ResourceBundle.getBundle(baseName, locale);
}
}
}
/**
* Return a cache key unique for this resource bundle and locale.
*
* @param locale the requested locale
* @return a cache key unique for this resource bundle and locale.
*/
public String getCacheKey(Locale locale) {
final String localeSuffix = locale == null ? "" : "_" + locale.toString();
if (this.resourceURL == null) {
return baseName + localeSuffix;
} else {
return baseName + this.toString() + localeSuffix;
}
}
}
/**
* Add a resource reference for the given resource base name.
*
* @param baseName the resource name (e.g. "ApplicationResources")
* @return a List of BundleReferences
* @throws IOException if an I/O error occured while looking for resources
*/
public static List<BundleReference> addMessageResources(String baseName) throws IOException {
// scan classpath
final Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(baseName + ".properties");
List<FxSharedUtils.BundleReference> refs = new ArrayList<FxSharedUtils.BundleReference>(5);
while (resources.hasMoreElements()) {
final URL resourceURL = resources.nextElement();
try {
if ("vfszip".equals(resourceURL.getProtocol()) || "vfs".equals(resourceURL.getProtocol())) {
refs.add(new BundleReference(baseName, resourceURL));
continue;
}
// expected format: file:/some/path/to/file.jar!{baseName}.properties if this is no JBoss 5 vfs zipfile
final int jarDelim = resourceURL.getPath().lastIndexOf(".jar!");
String path = resourceURL.getPath();
if (!path.startsWith("file:")) {
if (path.startsWith("/") || path.charAt(1) == ':') {
LOG.warn("Trying a filesystem message resource without an explicit file: protocol identifier for " + path);
refs.add(new BundleReference(baseName, resourceURL));
continue;
} else {
LOG.warn("Cannot use message resources because they are not served from the file system: " + resourceURL.getPath());
continue;
}
} else if (jarDelim != -1) {
path = path.substring("file:".length(), jarDelim + 4);
}
// "file:" and everything after ".jar" gets stripped for the class loader URL
final URL jarURL = new URL("file", null, path);
refs.add(new BundleReference(baseName, jarURL));
LOG.info("Added message resources for " + resourceURL.getPath());
} catch (Exception e) {
LOG.error("Failed to add message resources for URL " + resourceURL.getPath() + ": " + e.getMessage(), e);
}
}
return refs;
}
/**
* Close the given resources and log a warning message if closing fails.
*
* @param resources the resource(s) to be closed
* @since 3.1
*/
public static void close(Closeable... resources) {
if (resources != null) {
for (Closeable resource : resources) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Failed to close resource " + resource + ": " + e.getMessage(), e);
}
}
}
}
}
}
/**
* @return true if only a minimum set of runonce scripts should be installed.
* @see #PROP_RUNONCE_MINIMAL
* @since 3.1
*/
public static boolean isMinimalRunOnceScripts() {
return FxContext.get().getDivisionId() == DivisionData.DIVISION_TEST
&& System.getProperty(PROP_RUNONCE_MINIMAL) != null;
}
/**
* Resource message key for caching
*/
public static class MessageKey {
private final Locale locale;
private final String key;
public MessageKey(Locale locale, String key) {
this.locale = locale;
this.key = key;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MessageKey that = (MessageKey) o;
if (key != null ? !key.equals(that.key) : that.key != null) return false;
if (locale != null ? !locale.equals(that.locale) : that.locale != null) return false;
return true;
}
@Override
public int hashCode() {
int result = locale != null ? locale.hashCode() : 0;
result = 31 * result + (key != null ? key.hashCode() : 0);
return result;
}
}
/**
* This method checks if the current assignment is a derived assignment subject to the following conditions:
* 1.) must be assigned to a derived type
* 2.) must be inherited from the derived type's parent
* 3.) XPaths must match
*
* @param assignment an FxAssignment
* @param <T> extends FxAssignment
* @return true if conditions are met
* @since 3.1.1
*/
public static <T extends FxAssignment> boolean checkAssignmentInherited(T assignment) {
if (assignment == null)
return false;
// "REAL" inheritance only works for derived types
if (assignment.getAssignedType().isDerived()) {
final FxAssignment baseAssignment;
// temp. assignments might not be found (id = -1)
try {
baseAssignment = CacheAdmin.getEnvironment().getAssignment(assignment.getBaseAssignmentId());
long baseTypeId = baseAssignment.getAssignedType().getId();
// type must be derived and the assignment must be part of the inheritance chain
return assignment.getAssignedType().isDerivedFrom(baseTypeId) &&
XPathElement.stripType(baseAssignment.getXPath()).equals(XPathElement.stripType(assignment.getXPath()));
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Assignment inheritance could not be determined (probably due to a temp. assignment id of -1");
}
}
}
return false;
}
/**
* @return the name of the current network node (used by flexive for the {@link com.flexive.shared.interfaces.NodeConfigurationEngine}.
* @since 3.2.0
*/
public static synchronized String getNodeId() {
if (NODE_ID == null) {
NODE_ID = System.getProperty("flexive.nodename");
if (StringUtils.isBlank(NODE_ID)) {
NODE_ID = getHostName();
}
if (LOG.isInfoEnabled()) {
LOG.info("Determined nodename (override with system property flexive.nodename): " + NODE_ID);
}
}
return NODE_ID;
}
}
| true | true | public static String[] splitLiterals(String text) {
return splitLiterals(text, new char[]{'\'', '"'}, ',');
}
/**
* Projects a single-parameter function on a hashmap.
* Useful for calling parameterized functions from JSF-EL. Results are not cached by default, use
* {@link #getMappedFunction(com.flexive.shared.FxSharedUtils.ParameterMapper, boolean)}
* to create a caching mapper.
*
* @param mapper the parameter mapper wrapping the function to be called
* @return a hashmap projected on the given parameter mapper
*/
public static <K, V> Map<K, V> getMappedFunction(final ParameterMapper<K, V> mapper) {
return new HashMap<K, V>() {
private static final long serialVersionUID = 1051489436850755246L;
@Override
public V get(Object key) {
return mapper.get(key);
}
};
}
/**
* Projects a single-parameter function on a hashmap.
* Useful for calling parameterized functions from JSF-EL. Values returned by the mapper
* can be cached in the hash map.
*
* @param mapper the parameter mapper wrapping the function to be called
* @param cacheResults if the mapper results should be cached by the map
* @return a hashmap projected on the given parameter mapper
* @since 3.1
*/
public static <K, V> Map<K, V> getMappedFunction(final ParameterMapper<K, V> mapper, boolean cacheResults) {
if (cacheResults) {
return new HashMap<K, V>() {
private static final long serialVersionUID = 1051489436850755246L;
@SuppressWarnings({"unchecked"})
@Override
public V get(Object key) {
if (!containsKey(key)) {
put((K) key, mapper.get(key));
}
return super.get(key);
}
};
} else {
return getMappedFunction(mapper);
}
}
/**
* Escape a path for usage on the current operating systems shell
*
* @param path path to escape
* @return escaped path
*/
public static String escapePath(String path) {
if (WINDOWS)
return "\"" + path + "\"";
else
return path.replace(" ", "\\ ");
}
/**
* Escapes the given XPath for use in a public URI.
*
* @param xpath the xpath to be escaped
* @return the given XPath for use in a public URI.
* @see #decodeXPath(String)
*/
public static String escapeXPath(String xpath) {
return StringUtils.replace(xpath, "/", XPATH_ENCODEDSLASH);
}
/**
* Decodes a previously escaped XPath.
*
* @param escapedXPath the escaped XPath
* @return the decoded XPath
* @see #escapeXPath(String)
*/
public static String decodeXPath(String escapedXPath) {
return StringUtils.replace(escapedXPath, XPATH_ENCODEDSLASH, "/");
}
/**
* Returns <code>map.get(key)</code> if <code>key</code> exists, <code>defaultValue</code> otherwise.
*
* @param map a map
* @param key the required key
* @param defaultValue the default value to be returned if <code>key</code> does not exist in <code>map</code>
* @return <code>map.get(key)</code> if <code>key</code> exists, <code>defaultValue</code> otherwise.
*/
public static <K, V> V get(Map<K, V> map, K key, V defaultValue) {
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* Returns true if the given string value is quoted with the given character (e.g. 'value').
*
* @param value the string value to be checked
* @param quoteChar the quote character, for example '
* @return true if the given string value is quoted with the given character (e.g. 'value').
*/
public static boolean isQuoted(String value, char quoteChar) {
return value != null && value.length() >= 2
&& value.charAt(0) == quoteChar && value.charAt(value.length() - 1) == quoteChar;
}
/**
* Strips the quotes from the given string if it is quoted, otherwise it returns
* the input value itself.
*
* @param value the value to be "unquoted"
* @param quoteChar the quote character, for example '
* @return the unquoted string, or <code>value</code>, if it was not quoted
*/
public static String stripQuotes(String value, char quoteChar) {
if (isQuoted(value, quoteChar)) {
return value.substring(1, value.length() - 1);
}
return value;
}
/**
* Returns the UTF-8 byte representation of the given string. Use this instead of
* {@link String#getBytes()}, since the latter will fail if the system locale is not UTF-8.
*
* @param s the string to be processed
* @return the UTF-8 byte representation of the given string
*/
public static byte[] getBytes(String s) {
return s.getBytes(Charsets.UTF_8);
}
/**
* Extracts the names of the given enum elements and returns them as string.
* Useful if the toString() method of the Enum class was overwritten.
*
* @param values the enum values
* @return the names of the given enum elements
*/
public static List<String> getEnumNames(Collection<? extends Enum> values) {
final List<String> result = new ArrayList<String>(values.size());
for (final Enum value : values) {
result.add(value.name());
}
return result;
}
/**
* Extract the unique IDs of the given {@link SelectableObject} collection.
*
* @param values the input values
* @return the IDs of the input values
* @since 3.1
*/
public static List<Long> getSelectableObjectIdList(Iterable<? extends SelectableObject> values) {
final List<Long> result = new ArrayList<Long>();
for (SelectableObject value : values) {
result.add(value.getId());
}
return result;
}
/**
* Extract the unique names of the given {@link SelectableObject} collection.
*
* @param values the input values
* @return the IDs of the input values
* @since 3.1
*/
public static List<String> getSelectableObjectNameList(Iterable<? extends SelectableObjectWithName> values) {
final List<String> result = new ArrayList<String>();
for (SelectableObjectWithName value : values) {
result.add(value.getName());
}
return result;
}
/**
* Returns the index of the {@link SelectableObject} with the given ID, or -1 if none was found.
*
* @param values the values to be examined
* @param id the target ID
* @return the index of the {@link SelectableObject} with the given ID, or -1 if none was found.
*/
public static int indexOfSelectableObject(List<? extends SelectableObject> values, long id) {
for (int i = 0; i < values.size(); i++) {
final SelectableObject object = values.get(i);
if (object.getId() == id) {
return i;
}
}
return -1;
}
/**
* Return a {@link SelectableObject} by its ID.
*
* @param values the values to search
* @param id the ID to look for
* @param <T> the value type
* @return the first matching value
* @throws com.flexive.shared.exceptions.FxRuntimeException if no element with the given ID was found
* @since 3.2.0
*/
public static <T extends SelectableObject> T getSelectableObject(List<T> values, long id) {
for (T value : values) {
if (value.getId() == id) {
return value;
}
}
throw new FxNotFoundException("ex.selectable.id.notFound", id).asRuntimeException();
}
/**
* Return the elements of {@code values} that match the given {@code ids}.
*
* @param values the values to be search
* @param ids the required IDs
* @param <T> the value type
* @return the elements of {@code values} that match the given {@code ids}.
* @since 3.1
*/
public static <T extends SelectableObject> List<T> filterSelectableObjectsById(Iterable<T> values, Collection<Long> ids) {
final List<T> result = Lists.newArrayListWithCapacity(ids.size());
for (T value : values) {
if (ids.contains(value.getId())) {
result.add(value);
}
}
return result;
}
/**
* Return the elements of {@code values} that match the given {@code names}.
*
* @param values the values to be search
* @param names the required IDs
* @param <T> the value type
* @return the elements of {@code values} that match the given {@code names}.
* @since 3.1
*/
public static <T extends SelectableObjectWithName> List<T> filterSelectableObjectsByName(Iterable<T> values, Collection<String> names) {
final List<T> result = Lists.newArrayListWithCapacity(names.size());
for (T value : values) {
if (names.contains(value.getName())) {
result.add(value);
}
}
return result;
}
/**
* Primitive int comparison method (when JDK7's Integer#compare cannot be used).
* For float and double, see {@link org.apache.commons.lang.NumberUtils}.
*
* @param i1 the first value
* @param i2 the second value
* @return see {@link Integer#compareTo}
* @since 3.2.0
*/
public static int compare(int i1, int i2) {
if (i1 < i2) {
return -1;
} else if (i1 == i2) {
return 0;
} else {
return 1;
}
}
/**
* Primitive long comparison method (when JDK7's Long#compare cannot be used).
* For float and double, see {@link org.apache.commons.lang.NumberUtils}.
*
* @param i1 the first value
* @param i2 the second value
* @return see {@link Integer#compareTo}
* @since 3.2.0
*/
public static int compare(long i1, long i2) {
if (i1 < i2) {
return -1;
} else if (i1 == i2) {
return 0;
} else {
return 1;
}
}
/**
* Comparator for sorting Assignments according to their position.
*/
public static class AssignmentPositionSorter implements Comparator<FxAssignment>, Serializable {
private static final long serialVersionUID = 9197582519027523108L;
public int compare(FxAssignment o1, FxAssignment o2) {
return FxSharedUtils.compare(o1.getPosition(), o2.getPosition());
}
}
/**
* Comparator for sorting {@link SelectableObjectWithName} instances by ID.
*/
public static class SelectableObjectSorter implements Comparator<SelectableObject>, Serializable {
private static final long serialVersionUID = -1786371691872260074L;
public int compare(SelectableObject o1, SelectableObject o2) {
return FxSharedUtils.compare(o1.getId(), o2.getId());
}
}
/**
* Comparator for sorting {@link SelectableObjectWithName} instances by name.
*/
public static class SelectableObjectWithNameSorter implements Comparator<SelectableObjectWithName>, Serializable {
private static final long serialVersionUID = -1786371691872260074L;
public int compare(SelectableObjectWithName o1, SelectableObjectWithName o2) {
return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
}
}
/**
* Comparator for sorting {@link SelectableObjectWithLabel} instances by label.
*/
public static class SelectableObjectWithLabelSorter implements Comparator<SelectableObjectWithLabel>, Serializable {
public int compare(SelectableObjectWithLabel o1, SelectableObjectWithLabel o2) {
return o1.getLabel().getBestTranslation().toLowerCase().compareTo(o2.getLabel().getBestTranslation().toLowerCase());
}
}
/**
* Item sorter by position
*/
public static class ItemPositionSorter implements Comparator<FxSelectListItem>, Serializable {
private static final long serialVersionUID = 3366660003069358959L;
public int compare(FxSelectListItem i1, FxSelectListItem i2) {
return FxSharedUtils.compare(i1.getPosition(), i2.getPosition());
}
}
/**
* Item sorter by label
*/
public static class ItemLabelSorter implements Comparator<FxSelectListItem>, Serializable {
private static final long serialVersionUID = 2366364003069358945L;
private final FxLanguage language;
private final Collator collator;
private final Map<String, CollationKey> uppercaseLabels;
/**
* Ctor
*
* @param language the language used for sorting
*/
public ItemLabelSorter(FxLanguage language) {
this.language = language;
this.collator = Collator.getInstance(language.getLocale());
this.uppercaseLabels = Maps.newHashMap(); // cache collation keys for case-insensitive comparisons
}
/**
* {@inheritDoc}
*/
public int compare(FxSelectListItem i1, FxSelectListItem i2) {
final String label1 = i1.getLabel().getBestTranslation(language);
final String label2 = i2.getLabel().getBestTranslation(language);
if (!uppercaseLabels.containsKey(label1)) {
uppercaseLabels.put(label1, collator.getCollationKey(StringUtils.defaultString(label1).toUpperCase(language.getLocale())));
}
if (!uppercaseLabels.containsKey(label2)) {
uppercaseLabels.put(label2, collator.getCollationKey(StringUtils.defaultString(label2).toUpperCase(language.getLocale())));
}
return uppercaseLabels.get(label1).compareTo(uppercaseLabels.get(label2));
}
}
/**
* An SQL executor, similar to ant's sql task
* An important addition are raw blocks:
* lines starting with '-- @START@' indicate the start of a raw block and lines starting with '-- @END@'
* indicate the end of a raw block.
* Raw blocks are passed "as is" to the database as one string
*/
public static class SQLExecutor {
private Connection con;
private Statement stmt = null;
private String code;
private int count = 0;
private String delimiter;
private boolean keepformat;
private boolean rowDelimiter;
private PrintStream out;
/**
* Ctor
*
* @param con an open and valid connection
* @param code the source sql code
* @param delimiter delimiter to use
* @param rowDelimiter is the delimiter or row delimiter?
* @param keepformat keep original format?
* @param out stream for messages
*/
public SQLExecutor(Connection con, String code, String delimiter, boolean rowDelimiter, boolean keepformat, PrintStream out) {
this.con = con;
this.code = code;
this.delimiter = delimiter;
this.rowDelimiter = rowDelimiter;
this.keepformat = keepformat;
this.out = out;
}
/**
* Main execute method, returns number of updates
*
* @return number of updates
* @throws SQLException on errors
* @throws IOException on errors
*/
public int execute() throws SQLException, IOException {
stmt = con.createStatement();
try {
StringBuffer sql = new StringBuffer();
String line;
BufferedReader in = new BufferedReader(new StringReader(code));
boolean inRawBlock = false;
while ((line = in.readLine()) != null) {
line = line.trim();
if (inRawBlock) {
if (line.startsWith("--") && line.indexOf("@END@") > 0) {
inRawBlock = false;
if (sql.length() > 0) {
// System.out.println("Executing raw block:\n" + sql.toString());
execute(sql.toString());
sql.replace(0, sql.length(), "");
}
} else
sql.append(line).append('\n');
continue;
}
if (line.startsWith("//") || line.startsWith("--")) {
if (line.indexOf("@START@") > 0)
inRawBlock = true;
continue;
}
StringTokenizer st = new StringTokenizer(line);
if (st.hasMoreTokens()) {
String token = st.nextToken();
if ("REM".equalsIgnoreCase(token))
continue;
}
sql.append("\n").append(line);
if (!keepformat && line.indexOf("--") >= 0)
sql.append("\n");
if (!rowDelimiter && StringUtils.endsWith(sql.toString(), delimiter)
|| (rowDelimiter && line.equals(delimiter))) {
execute(sql.substring(0, sql.length() - delimiter.length()));
sql.replace(0, sql.length(), "");
}
}
if (sql.length() > 0)
execute(sql.toString());
} finally {
if (stmt != null)
stmt.close();
}
return count;
}
/**
* Execute a single SQL statement
*
* @param sql statement
* @throws SQLException on errors
*/
private void execute(String sql) throws SQLException {
if ("".equals(sql.trim()))
return;
ResultSet rs = null;
try {
count++;
boolean ret;
stmt.execute(sql);
rs = stmt.getResultSet();
do {
ret = stmt.getMoreResults();
if (ret) {
rs = stmt.getResultSet();
}
} while (ret);
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) SQLWarning warning = con.getWarnings();
while (warning != null) {
out.println("Warning: " + warning);
warning = warning.getNextWarning();
}
con.clearWarnings();
} catch (SQLException e) {
out.println("Failed to execute: " + sql);
throw e;
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
//ignore
}
}
}
}
}
/**
* A resource bundle reference.
*/
public static class BundleReference {
private final String baseName;
private final URL resourceURL;
/**
* Create a new bundle reference.
*
* @param baseName the fully qualified base name (e.g. "ApplicationResources")
* @param resourceURL the resource URL to be used for loading the resource bundle. If null,
* the context class loader will be used.
*/
public BundleReference(String baseName, URL resourceURL) {
this.baseName = baseName;
this.resourceURL = resourceURL;
}
/**
* Returns the base name of the resource bundle (e.g. "ApplicationResources").
*
* @return the base name of the resource bundle (e.g. "ApplicationResources").
*/
public String getBaseName() {
return baseName;
}
/**
* Returns the class loader to be used for loading the bundle.
*
* @return the class loader to be used for loading the bundle.
*/
public URL getResourceURL() {
return resourceURL;
}
/**
* Return the resource bundle in the given locale.
*
* @param locale the requested locale
* @return the resource bundle in the given locale.
*/
public ResourceBundle getBundle(Locale locale) {
if (this.resourceURL == null) {
return ResourceBundle.getBundle(baseName, locale);
} else {
try {
return ResourceBundle.getBundle(baseName, locale, new URLClassLoader(new URL[]{resourceURL}));
} catch (MissingResourceException mre) {
//fix for JBoss 5 vfs which doesn't work with classloader
try {
//try to find in the desired locale
Enumeration<URL> e = Thread.currentThread().getContextClassLoader().getResources(baseName + "_" + locale.getLanguage() + ".properties");
String orgPath = resourceURL.toExternalForm().substring(0, resourceURL.toExternalForm().lastIndexOf("/"));
while (e.hasMoreElements()) {
URL resource = e.nextElement();
if (orgPath.equals(resource.toExternalForm().substring(0, resource.toExternalForm().lastIndexOf("/")))) {
return new PropertyResourceBundle(resource.openStream());
}
}
//Fallback to the default locale
return new PropertyResourceBundle(resourceURL.openStream());
} catch (IOException e) {
LOG.warn("Failed to retrieve bundle " + baseName + " directly from stream");
}
//last resort
return ResourceBundle.getBundle(baseName, locale);
}
}
}
/**
* Return a cache key unique for this resource bundle and locale.
*
* @param locale the requested locale
* @return a cache key unique for this resource bundle and locale.
*/
public String getCacheKey(Locale locale) {
final String localeSuffix = locale == null ? "" : "_" + locale.toString();
if (this.resourceURL == null) {
return baseName + localeSuffix;
} else {
return baseName + this.toString() + localeSuffix;
}
}
}
/**
* Add a resource reference for the given resource base name.
*
* @param baseName the resource name (e.g. "ApplicationResources")
* @return a List of BundleReferences
* @throws IOException if an I/O error occured while looking for resources
*/
public static List<BundleReference> addMessageResources(String baseName) throws IOException {
// scan classpath
final Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(baseName + ".properties");
List<FxSharedUtils.BundleReference> refs = new ArrayList<FxSharedUtils.BundleReference>(5);
while (resources.hasMoreElements()) {
final URL resourceURL = resources.nextElement();
try {
if ("vfszip".equals(resourceURL.getProtocol()) || "vfs".equals(resourceURL.getProtocol())) {
refs.add(new BundleReference(baseName, resourceURL));
continue;
}
// expected format: file:/some/path/to/file.jar!{baseName}.properties if this is no JBoss 5 vfs zipfile
final int jarDelim = resourceURL.getPath().lastIndexOf(".jar!");
String path = resourceURL.getPath();
if (!path.startsWith("file:")) {
if (path.startsWith("/") || path.charAt(1) == ':') {
LOG.warn("Trying a filesystem message resource without an explicit file: protocol identifier for " + path);
refs.add(new BundleReference(baseName, resourceURL));
continue;
} else {
LOG.warn("Cannot use message resources because they are not served from the file system: " + resourceURL.getPath());
continue;
}
} else if (jarDelim != -1) {
path = path.substring("file:".length(), jarDelim + 4);
}
// "file:" and everything after ".jar" gets stripped for the class loader URL
final URL jarURL = new URL("file", null, path);
refs.add(new BundleReference(baseName, jarURL));
LOG.info("Added message resources for " + resourceURL.getPath());
} catch (Exception e) {
LOG.error("Failed to add message resources for URL " + resourceURL.getPath() + ": " + e.getMessage(), e);
}
}
return refs;
}
/**
* Close the given resources and log a warning message if closing fails.
*
* @param resources the resource(s) to be closed
* @since 3.1
*/
public static void close(Closeable... resources) {
if (resources != null) {
for (Closeable resource : resources) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Failed to close resource " + resource + ": " + e.getMessage(), e);
}
}
}
}
}
}
/**
* @return true if only a minimum set of runonce scripts should be installed.
* @see #PROP_RUNONCE_MINIMAL
* @since 3.1
*/
public static boolean isMinimalRunOnceScripts() {
return FxContext.get().getDivisionId() == DivisionData.DIVISION_TEST
&& System.getProperty(PROP_RUNONCE_MINIMAL) != null;
}
/**
* Resource message key for caching
*/
public static class MessageKey {
private final Locale locale;
private final String key;
public MessageKey(Locale locale, String key) {
this.locale = locale;
this.key = key;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MessageKey that = (MessageKey) o;
if (key != null ? !key.equals(that.key) : that.key != null) return false;
if (locale != null ? !locale.equals(that.locale) : that.locale != null) return false;
return true;
}
@Override
public int hashCode() {
int result = locale != null ? locale.hashCode() : 0;
result = 31 * result + (key != null ? key.hashCode() : 0);
return result;
}
}
/**
* This method checks if the current assignment is a derived assignment subject to the following conditions:
* 1.) must be assigned to a derived type
* 2.) must be inherited from the derived type's parent
* 3.) XPaths must match
*
* @param assignment an FxAssignment
* @param <T> extends FxAssignment
* @return true if conditions are met
* @since 3.1.1
*/
public static <T extends FxAssignment> boolean checkAssignmentInherited(T assignment) {
if (assignment == null)
return false;
// "REAL" inheritance only works for derived types
if (assignment.getAssignedType().isDerived()) {
final FxAssignment baseAssignment;
// temp. assignments might not be found (id = -1)
try {
baseAssignment = CacheAdmin.getEnvironment().getAssignment(assignment.getBaseAssignmentId());
long baseTypeId = baseAssignment.getAssignedType().getId();
// type must be derived and the assignment must be part of the inheritance chain
return assignment.getAssignedType().isDerivedFrom(baseTypeId) &&
XPathElement.stripType(baseAssignment.getXPath()).equals(XPathElement.stripType(assignment.getXPath()));
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Assignment inheritance could not be determined (probably due to a temp. assignment id of -1");
}
}
}
return false;
}
/**
* @return the name of the current network node (used by flexive for the {@link com.flexive.shared.interfaces.NodeConfigurationEngine}.
* @since 3.2.0
*/
public static synchronized String getNodeId() {
if (NODE_ID == null) {
NODE_ID = System.getProperty("flexive.nodename");
if (StringUtils.isBlank(NODE_ID)) {
NODE_ID = getHostName();
}
if (LOG.isInfoEnabled()) {
LOG.info("Determined nodename (override with system property flexive.nodename): " + NODE_ID);
}
}
return NODE_ID;
}
}
| public static String[] splitLiterals(String text) {
return splitLiterals(text, new char[]{'\'', '"'}, ',');
}
/**
* Projects a single-parameter function on a hashmap.
* Useful for calling parameterized functions from JSF-EL. Results are not cached by default, use
* {@link #getMappedFunction(com.flexive.shared.FxSharedUtils.ParameterMapper, boolean)}
* to create a caching mapper.
*
* @param mapper the parameter mapper wrapping the function to be called
* @return a hashmap projected on the given parameter mapper
*/
public static <K, V> Map<K, V> getMappedFunction(final ParameterMapper<K, V> mapper) {
return new HashMap<K, V>() {
private static final long serialVersionUID = 1051489436850755246L;
@Override
public V get(Object key) {
return mapper.get(key);
}
};
}
/**
* Projects a single-parameter function on a hashmap.
* Useful for calling parameterized functions from JSF-EL. Values returned by the mapper
* can be cached in the hash map.
*
* @param mapper the parameter mapper wrapping the function to be called
* @param cacheResults if the mapper results should be cached by the map
* @return a hashmap projected on the given parameter mapper
* @since 3.1
*/
public static <K, V> Map<K, V> getMappedFunction(final ParameterMapper<K, V> mapper, boolean cacheResults) {
if (cacheResults) {
return new HashMap<K, V>() {
private static final long serialVersionUID = 1051489436850755246L;
@SuppressWarnings({"unchecked"})
@Override
public V get(Object key) {
if (!containsKey(key)) {
put((K) key, mapper.get(key));
}
return super.get(key);
}
};
} else {
return getMappedFunction(mapper);
}
}
/**
* Escape a path for usage on the current operating systems shell
*
* @param path path to escape
* @return escaped path
*/
public static String escapePath(String path) {
if (WINDOWS)
return "\"" + path + "\"";
else
return path.replace(" ", "\\ ");
}
/**
* Escapes the given XPath for use in a public URI.
*
* @param xpath the xpath to be escaped
* @return the given XPath for use in a public URI.
* @see #decodeXPath(String)
*/
public static String escapeXPath(String xpath) {
return StringUtils.replace(xpath, "/", XPATH_ENCODEDSLASH);
}
/**
* Decodes a previously escaped XPath.
*
* @param escapedXPath the escaped XPath
* @return the decoded XPath
* @see #escapeXPath(String)
*/
public static String decodeXPath(String escapedXPath) {
return StringUtils.replace(escapedXPath, XPATH_ENCODEDSLASH, "/");
}
/**
* Returns <code>map.get(key)</code> if <code>key</code> exists, <code>defaultValue</code> otherwise.
*
* @param map a map
* @param key the required key
* @param defaultValue the default value to be returned if <code>key</code> does not exist in <code>map</code>
* @return <code>map.get(key)</code> if <code>key</code> exists, <code>defaultValue</code> otherwise.
*/
public static <K, V> V get(Map<K, V> map, K key, V defaultValue) {
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* Returns true if the given string value is quoted with the given character (e.g. 'value').
*
* @param value the string value to be checked
* @param quoteChar the quote character, for example '
* @return true if the given string value is quoted with the given character (e.g. 'value').
*/
public static boolean isQuoted(String value, char quoteChar) {
return value != null && value.length() >= 2
&& value.charAt(0) == quoteChar && value.charAt(value.length() - 1) == quoteChar;
}
/**
* Strips the quotes from the given string if it is quoted, otherwise it returns
* the input value itself.
*
* @param value the value to be "unquoted"
* @param quoteChar the quote character, for example '
* @return the unquoted string, or <code>value</code>, if it was not quoted
*/
public static String stripQuotes(String value, char quoteChar) {
if (isQuoted(value, quoteChar)) {
return value.substring(1, value.length() - 1);
}
return value;
}
/**
* Returns the UTF-8 byte representation of the given string. Use this instead of
* {@link String#getBytes()}, since the latter will fail if the system locale is not UTF-8.
*
* @param s the string to be processed
* @return the UTF-8 byte representation of the given string
*/
public static byte[] getBytes(String s) {
try {
return s.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Failed to decode UTF-8 string: " + e.getMessage(), e);
}
return s.getBytes();
}
}
/**
* Extracts the names of the given enum elements and returns them as string.
* Useful if the toString() method of the Enum class was overwritten.
*
* @param values the enum values
* @return the names of the given enum elements
*/
public static List<String> getEnumNames(Collection<? extends Enum> values) {
final List<String> result = new ArrayList<String>(values.size());
for (final Enum value : values) {
result.add(value.name());
}
return result;
}
/**
* Extract the unique IDs of the given {@link SelectableObject} collection.
*
* @param values the input values
* @return the IDs of the input values
* @since 3.1
*/
public static List<Long> getSelectableObjectIdList(Iterable<? extends SelectableObject> values) {
final List<Long> result = new ArrayList<Long>();
for (SelectableObject value : values) {
result.add(value.getId());
}
return result;
}
/**
* Extract the unique names of the given {@link SelectableObject} collection.
*
* @param values the input values
* @return the IDs of the input values
* @since 3.1
*/
public static List<String> getSelectableObjectNameList(Iterable<? extends SelectableObjectWithName> values) {
final List<String> result = new ArrayList<String>();
for (SelectableObjectWithName value : values) {
result.add(value.getName());
}
return result;
}
/**
* Returns the index of the {@link SelectableObject} with the given ID, or -1 if none was found.
*
* @param values the values to be examined
* @param id the target ID
* @return the index of the {@link SelectableObject} with the given ID, or -1 if none was found.
*/
public static int indexOfSelectableObject(List<? extends SelectableObject> values, long id) {
for (int i = 0; i < values.size(); i++) {
final SelectableObject object = values.get(i);
if (object.getId() == id) {
return i;
}
}
return -1;
}
/**
* Return a {@link SelectableObject} by its ID.
*
* @param values the values to search
* @param id the ID to look for
* @param <T> the value type
* @return the first matching value
* @throws com.flexive.shared.exceptions.FxRuntimeException if no element with the given ID was found
* @since 3.2.0
*/
public static <T extends SelectableObject> T getSelectableObject(List<T> values, long id) {
for (T value : values) {
if (value.getId() == id) {
return value;
}
}
throw new FxNotFoundException("ex.selectable.id.notFound", id).asRuntimeException();
}
/**
* Return the elements of {@code values} that match the given {@code ids}.
*
* @param values the values to be search
* @param ids the required IDs
* @param <T> the value type
* @return the elements of {@code values} that match the given {@code ids}.
* @since 3.1
*/
public static <T extends SelectableObject> List<T> filterSelectableObjectsById(Iterable<T> values, Collection<Long> ids) {
final List<T> result = Lists.newArrayListWithCapacity(ids.size());
for (T value : values) {
if (ids.contains(value.getId())) {
result.add(value);
}
}
return result;
}
/**
* Return the elements of {@code values} that match the given {@code names}.
*
* @param values the values to be search
* @param names the required IDs
* @param <T> the value type
* @return the elements of {@code values} that match the given {@code names}.
* @since 3.1
*/
public static <T extends SelectableObjectWithName> List<T> filterSelectableObjectsByName(Iterable<T> values, Collection<String> names) {
final List<T> result = Lists.newArrayListWithCapacity(names.size());
for (T value : values) {
if (names.contains(value.getName())) {
result.add(value);
}
}
return result;
}
/**
* Primitive int comparison method (when JDK7's Integer#compare cannot be used).
* For float and double, see {@link org.apache.commons.lang.NumberUtils}.
*
* @param i1 the first value
* @param i2 the second value
* @return see {@link Integer#compareTo}
* @since 3.2.0
*/
public static int compare(int i1, int i2) {
if (i1 < i2) {
return -1;
} else if (i1 == i2) {
return 0;
} else {
return 1;
}
}
/**
* Primitive long comparison method (when JDK7's Long#compare cannot be used).
* For float and double, see {@link org.apache.commons.lang.NumberUtils}.
*
* @param i1 the first value
* @param i2 the second value
* @return see {@link Integer#compareTo}
* @since 3.2.0
*/
public static int compare(long i1, long i2) {
if (i1 < i2) {
return -1;
} else if (i1 == i2) {
return 0;
} else {
return 1;
}
}
/**
* Comparator for sorting Assignments according to their position.
*/
public static class AssignmentPositionSorter implements Comparator<FxAssignment>, Serializable {
private static final long serialVersionUID = 9197582519027523108L;
public int compare(FxAssignment o1, FxAssignment o2) {
return FxSharedUtils.compare(o1.getPosition(), o2.getPosition());
}
}
/**
* Comparator for sorting {@link SelectableObjectWithName} instances by ID.
*/
public static class SelectableObjectSorter implements Comparator<SelectableObject>, Serializable {
private static final long serialVersionUID = -1786371691872260074L;
public int compare(SelectableObject o1, SelectableObject o2) {
return FxSharedUtils.compare(o1.getId(), o2.getId());
}
}
/**
* Comparator for sorting {@link SelectableObjectWithName} instances by name.
*/
public static class SelectableObjectWithNameSorter implements Comparator<SelectableObjectWithName>, Serializable {
private static final long serialVersionUID = -1786371691872260074L;
public int compare(SelectableObjectWithName o1, SelectableObjectWithName o2) {
return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
}
}
/**
* Comparator for sorting {@link SelectableObjectWithLabel} instances by label.
*/
public static class SelectableObjectWithLabelSorter implements Comparator<SelectableObjectWithLabel>, Serializable {
public int compare(SelectableObjectWithLabel o1, SelectableObjectWithLabel o2) {
return o1.getLabel().getBestTranslation().toLowerCase().compareTo(o2.getLabel().getBestTranslation().toLowerCase());
}
}
/**
* Item sorter by position
*/
public static class ItemPositionSorter implements Comparator<FxSelectListItem>, Serializable {
private static final long serialVersionUID = 3366660003069358959L;
public int compare(FxSelectListItem i1, FxSelectListItem i2) {
return FxSharedUtils.compare(i1.getPosition(), i2.getPosition());
}
}
/**
* Item sorter by label
*/
public static class ItemLabelSorter implements Comparator<FxSelectListItem>, Serializable {
private static final long serialVersionUID = 2366364003069358945L;
private final FxLanguage language;
private final Collator collator;
private final Map<String, CollationKey> uppercaseLabels;
/**
* Ctor
*
* @param language the language used for sorting
*/
public ItemLabelSorter(FxLanguage language) {
this.language = language;
this.collator = Collator.getInstance(language.getLocale());
this.uppercaseLabels = Maps.newHashMap(); // cache collation keys for case-insensitive comparisons
}
/**
* {@inheritDoc}
*/
public int compare(FxSelectListItem i1, FxSelectListItem i2) {
final String label1 = i1.getLabel().getBestTranslation(language);
final String label2 = i2.getLabel().getBestTranslation(language);
if (!uppercaseLabels.containsKey(label1)) {
uppercaseLabels.put(label1, collator.getCollationKey(StringUtils.defaultString(label1).toUpperCase(language.getLocale())));
}
if (!uppercaseLabels.containsKey(label2)) {
uppercaseLabels.put(label2, collator.getCollationKey(StringUtils.defaultString(label2).toUpperCase(language.getLocale())));
}
return uppercaseLabels.get(label1).compareTo(uppercaseLabels.get(label2));
}
}
/**
* An SQL executor, similar to ant's sql task
* An important addition are raw blocks:
* lines starting with '-- @START@' indicate the start of a raw block and lines starting with '-- @END@'
* indicate the end of a raw block.
* Raw blocks are passed "as is" to the database as one string
*/
public static class SQLExecutor {
private Connection con;
private Statement stmt = null;
private String code;
private int count = 0;
private String delimiter;
private boolean keepformat;
private boolean rowDelimiter;
private PrintStream out;
/**
* Ctor
*
* @param con an open and valid connection
* @param code the source sql code
* @param delimiter delimiter to use
* @param rowDelimiter is the delimiter or row delimiter?
* @param keepformat keep original format?
* @param out stream for messages
*/
public SQLExecutor(Connection con, String code, String delimiter, boolean rowDelimiter, boolean keepformat, PrintStream out) {
this.con = con;
this.code = code;
this.delimiter = delimiter;
this.rowDelimiter = rowDelimiter;
this.keepformat = keepformat;
this.out = out;
}
/**
* Main execute method, returns number of updates
*
* @return number of updates
* @throws SQLException on errors
* @throws IOException on errors
*/
public int execute() throws SQLException, IOException {
stmt = con.createStatement();
try {
StringBuffer sql = new StringBuffer();
String line;
BufferedReader in = new BufferedReader(new StringReader(code));
boolean inRawBlock = false;
while ((line = in.readLine()) != null) {
line = line.trim();
if (inRawBlock) {
if (line.startsWith("--") && line.indexOf("@END@") > 0) {
inRawBlock = false;
if (sql.length() > 0) {
// System.out.println("Executing raw block:\n" + sql.toString());
execute(sql.toString());
sql.replace(0, sql.length(), "");
}
} else
sql.append(line).append('\n');
continue;
}
if (line.startsWith("//") || line.startsWith("--")) {
if (line.indexOf("@START@") > 0)
inRawBlock = true;
continue;
}
StringTokenizer st = new StringTokenizer(line);
if (st.hasMoreTokens()) {
String token = st.nextToken();
if ("REM".equalsIgnoreCase(token))
continue;
}
sql.append("\n").append(line);
if (!keepformat && line.indexOf("--") >= 0)
sql.append("\n");
if (!rowDelimiter && StringUtils.endsWith(sql.toString(), delimiter)
|| (rowDelimiter && line.equals(delimiter))) {
execute(sql.substring(0, sql.length() - delimiter.length()));
sql.replace(0, sql.length(), "");
}
}
if (sql.length() > 0)
execute(sql.toString());
} finally {
if (stmt != null)
stmt.close();
}
return count;
}
/**
* Execute a single SQL statement
*
* @param sql statement
* @throws SQLException on errors
*/
private void execute(String sql) throws SQLException {
if ("".equals(sql.trim()))
return;
ResultSet rs = null;
try {
count++;
boolean ret;
stmt.execute(sql);
rs = stmt.getResultSet();
do {
ret = stmt.getMoreResults();
if (ret) {
rs = stmt.getResultSet();
}
} while (ret);
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) SQLWarning warning = con.getWarnings();
while (warning != null) {
out.println("Warning: " + warning);
warning = warning.getNextWarning();
}
con.clearWarnings();
} catch (SQLException e) {
out.println("Failed to execute: " + sql);
throw e;
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
//ignore
}
}
}
}
}
/**
* A resource bundle reference.
*/
public static class BundleReference {
private final String baseName;
private final URL resourceURL;
/**
* Create a new bundle reference.
*
* @param baseName the fully qualified base name (e.g. "ApplicationResources")
* @param resourceURL the resource URL to be used for loading the resource bundle. If null,
* the context class loader will be used.
*/
public BundleReference(String baseName, URL resourceURL) {
this.baseName = baseName;
this.resourceURL = resourceURL;
}
/**
* Returns the base name of the resource bundle (e.g. "ApplicationResources").
*
* @return the base name of the resource bundle (e.g. "ApplicationResources").
*/
public String getBaseName() {
return baseName;
}
/**
* Returns the class loader to be used for loading the bundle.
*
* @return the class loader to be used for loading the bundle.
*/
public URL getResourceURL() {
return resourceURL;
}
/**
* Return the resource bundle in the given locale.
*
* @param locale the requested locale
* @return the resource bundle in the given locale.
*/
public ResourceBundle getBundle(Locale locale) {
if (this.resourceURL == null) {
return ResourceBundle.getBundle(baseName, locale);
} else {
try {
return ResourceBundle.getBundle(baseName, locale, new URLClassLoader(new URL[]{resourceURL}));
} catch (MissingResourceException mre) {
//fix for JBoss 5 vfs which doesn't work with classloader
try {
//try to find in the desired locale
Enumeration<URL> e = Thread.currentThread().getContextClassLoader().getResources(baseName + "_" + locale.getLanguage() + ".properties");
String orgPath = resourceURL.toExternalForm().substring(0, resourceURL.toExternalForm().lastIndexOf("/"));
while (e.hasMoreElements()) {
URL resource = e.nextElement();
if (orgPath.equals(resource.toExternalForm().substring(0, resource.toExternalForm().lastIndexOf("/")))) {
return new PropertyResourceBundle(resource.openStream());
}
}
//Fallback to the default locale
return new PropertyResourceBundle(resourceURL.openStream());
} catch (IOException e) {
LOG.warn("Failed to retrieve bundle " + baseName + " directly from stream");
}
//last resort
return ResourceBundle.getBundle(baseName, locale);
}
}
}
/**
* Return a cache key unique for this resource bundle and locale.
*
* @param locale the requested locale
* @return a cache key unique for this resource bundle and locale.
*/
public String getCacheKey(Locale locale) {
final String localeSuffix = locale == null ? "" : "_" + locale.toString();
if (this.resourceURL == null) {
return baseName + localeSuffix;
} else {
return baseName + this.toString() + localeSuffix;
}
}
}
/**
* Add a resource reference for the given resource base name.
*
* @param baseName the resource name (e.g. "ApplicationResources")
* @return a List of BundleReferences
* @throws IOException if an I/O error occured while looking for resources
*/
public static List<BundleReference> addMessageResources(String baseName) throws IOException {
// scan classpath
final Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(baseName + ".properties");
List<FxSharedUtils.BundleReference> refs = new ArrayList<FxSharedUtils.BundleReference>(5);
while (resources.hasMoreElements()) {
final URL resourceURL = resources.nextElement();
try {
if ("vfszip".equals(resourceURL.getProtocol()) || "vfs".equals(resourceURL.getProtocol())) {
refs.add(new BundleReference(baseName, resourceURL));
continue;
}
// expected format: file:/some/path/to/file.jar!{baseName}.properties if this is no JBoss 5 vfs zipfile
final int jarDelim = resourceURL.getPath().lastIndexOf(".jar!");
String path = resourceURL.getPath();
if (!path.startsWith("file:")) {
if (path.startsWith("/") || path.charAt(1) == ':') {
LOG.warn("Trying a filesystem message resource without an explicit file: protocol identifier for " + path);
refs.add(new BundleReference(baseName, resourceURL));
continue;
} else {
LOG.warn("Cannot use message resources because they are not served from the file system: " + resourceURL.getPath());
continue;
}
} else if (jarDelim != -1) {
path = path.substring("file:".length(), jarDelim + 4);
}
// "file:" and everything after ".jar" gets stripped for the class loader URL
final URL jarURL = new URL("file", null, path);
refs.add(new BundleReference(baseName, jarURL));
LOG.info("Added message resources for " + resourceURL.getPath());
} catch (Exception e) {
LOG.error("Failed to add message resources for URL " + resourceURL.getPath() + ": " + e.getMessage(), e);
}
}
return refs;
}
/**
* Close the given resources and log a warning message if closing fails.
*
* @param resources the resource(s) to be closed
* @since 3.1
*/
public static void close(Closeable... resources) {
if (resources != null) {
for (Closeable resource : resources) {
if (resource != null) {
try {
resource.close();
} catch (IOException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Failed to close resource " + resource + ": " + e.getMessage(), e);
}
}
}
}
}
}
/**
* @return true if only a minimum set of runonce scripts should be installed.
* @see #PROP_RUNONCE_MINIMAL
* @since 3.1
*/
public static boolean isMinimalRunOnceScripts() {
return FxContext.get().getDivisionId() == DivisionData.DIVISION_TEST
&& System.getProperty(PROP_RUNONCE_MINIMAL) != null;
}
/**
* Resource message key for caching
*/
public static class MessageKey {
private final Locale locale;
private final String key;
public MessageKey(Locale locale, String key) {
this.locale = locale;
this.key = key;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MessageKey that = (MessageKey) o;
if (key != null ? !key.equals(that.key) : that.key != null) return false;
if (locale != null ? !locale.equals(that.locale) : that.locale != null) return false;
return true;
}
@Override
public int hashCode() {
int result = locale != null ? locale.hashCode() : 0;
result = 31 * result + (key != null ? key.hashCode() : 0);
return result;
}
}
/**
* This method checks if the current assignment is a derived assignment subject to the following conditions:
* 1.) must be assigned to a derived type
* 2.) must be inherited from the derived type's parent
* 3.) XPaths must match
*
* @param assignment an FxAssignment
* @param <T> extends FxAssignment
* @return true if conditions are met
* @since 3.1.1
*/
public static <T extends FxAssignment> boolean checkAssignmentInherited(T assignment) {
if (assignment == null)
return false;
// "REAL" inheritance only works for derived types
if (assignment.getAssignedType().isDerived()) {
final FxAssignment baseAssignment;
// temp. assignments might not be found (id = -1)
try {
baseAssignment = CacheAdmin.getEnvironment().getAssignment(assignment.getBaseAssignmentId());
long baseTypeId = baseAssignment.getAssignedType().getId();
// type must be derived and the assignment must be part of the inheritance chain
return assignment.getAssignedType().isDerivedFrom(baseTypeId) &&
XPathElement.stripType(baseAssignment.getXPath()).equals(XPathElement.stripType(assignment.getXPath()));
} catch (Exception e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Assignment inheritance could not be determined (probably due to a temp. assignment id of -1");
}
}
}
return false;
}
/**
* @return the name of the current network node (used by flexive for the {@link com.flexive.shared.interfaces.NodeConfigurationEngine}.
* @since 3.2.0
*/
public static synchronized String getNodeId() {
if (NODE_ID == null) {
NODE_ID = System.getProperty("flexive.nodename");
if (StringUtils.isBlank(NODE_ID)) {
NODE_ID = getHostName();
}
if (LOG.isInfoEnabled()) {
LOG.info("Determined nodename (override with system property flexive.nodename): " + NODE_ID);
}
}
return NODE_ID;
}
}
|
diff --git a/src/main/java/fr/ribesg/alix/api/bot/command/HelpCommand.java b/src/main/java/fr/ribesg/alix/api/bot/command/HelpCommand.java
index 1a8733a..abe11f6 100644
--- a/src/main/java/fr/ribesg/alix/api/bot/command/HelpCommand.java
+++ b/src/main/java/fr/ribesg/alix/api/bot/command/HelpCommand.java
@@ -1,37 +1,37 @@
package fr.ribesg.alix.api.bot.command;
import fr.ribesg.alix.api.Channel;
import fr.ribesg.alix.api.Server;
import fr.ribesg.alix.api.Source;
import fr.ribesg.alix.api.enums.Codes;
public class HelpCommand extends Command {
public HelpCommand(final CommandManager manager) {
super(manager, "help", new String[] {"[command] - Get help about a command, or list every commands"}, "h");
}
@Override
public void exec(final Server server, final Channel channel, final Source user, final String primaryArgument, final String[] args) {
- if (args.length == 0 && primaryArgument == null || args.length == 1 && primaryArgument != null || args.length > 1) {
+ if (args.length == 1 && primaryArgument != null || args.length > 1) {
sendUsage(user);
return;
}
- final String arg = primaryArgument == null ? args[0] : primaryArgument;
+ final String arg = args.length == 1 ? args[0] : primaryArgument;
- if (args.length == 1) {
+ if (arg != null) {
final String cmdName = arg.toLowerCase();
final String realCmd = manager.aliases.get(cmdName) == null ? cmdName : manager.aliases.get(cmdName);
final Command cmd = manager.commands.get(realCmd);
if (cmd == null) {
user.sendMessage(Codes.RED + "Unknown command: " + cmdName);
return;
}
cmd.sendUsage(user);
} else {
for (final Command cmd : manager.commands.values()) {
cmd.sendUsage(user);
}
}
}
}
| false | true | public void exec(final Server server, final Channel channel, final Source user, final String primaryArgument, final String[] args) {
if (args.length == 0 && primaryArgument == null || args.length == 1 && primaryArgument != null || args.length > 1) {
sendUsage(user);
return;
}
final String arg = primaryArgument == null ? args[0] : primaryArgument;
if (args.length == 1) {
final String cmdName = arg.toLowerCase();
final String realCmd = manager.aliases.get(cmdName) == null ? cmdName : manager.aliases.get(cmdName);
final Command cmd = manager.commands.get(realCmd);
if (cmd == null) {
user.sendMessage(Codes.RED + "Unknown command: " + cmdName);
return;
}
cmd.sendUsage(user);
} else {
for (final Command cmd : manager.commands.values()) {
cmd.sendUsage(user);
}
}
}
| public void exec(final Server server, final Channel channel, final Source user, final String primaryArgument, final String[] args) {
if (args.length == 1 && primaryArgument != null || args.length > 1) {
sendUsage(user);
return;
}
final String arg = args.length == 1 ? args[0] : primaryArgument;
if (arg != null) {
final String cmdName = arg.toLowerCase();
final String realCmd = manager.aliases.get(cmdName) == null ? cmdName : manager.aliases.get(cmdName);
final Command cmd = manager.commands.get(realCmd);
if (cmd == null) {
user.sendMessage(Codes.RED + "Unknown command: " + cmdName);
return;
}
cmd.sendUsage(user);
} else {
for (final Command cmd : manager.commands.values()) {
cmd.sendUsage(user);
}
}
}
|
diff --git a/plugins/org.python.pydev/src/org/python/pydev/editor/actions/PyConvertSpaceToTab.java b/plugins/org.python.pydev/src/org/python/pydev/editor/actions/PyConvertSpaceToTab.java
index 9aee8f008..701ab9dda 100644
--- a/plugins/org.python.pydev/src/org/python/pydev/editor/actions/PyConvertSpaceToTab.java
+++ b/plugins/org.python.pydev/src/org/python/pydev/editor/actions/PyConvertSpaceToTab.java
@@ -1,145 +1,145 @@
/**
* Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
/*
* @author: ptoofani
* Created: June 2004
*/
package org.python.pydev.editor.actions;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.IInputValidator;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;
import org.python.pydev.core.docutils.PySelection;
import org.python.pydev.editor.autoedit.DefaultIndentPrefs;
import org.python.pydev.shared_core.string.FastStringBuffer;
import org.python.pydev.shared_ui.EditorUtils;
/**
* Converts tab-width spacing to tab characters in selection or entire document,
* if nothing selected.
*
* @author Parhaum Toofanian
*/
public class PyConvertSpaceToTab extends PyAction {
/* Selection element */
private PySelection ps;
/**
* Grabs the selection information and performs the action.
*/
public void run(IAction action) {
try {
if (!canModifyEditor()) {
return;
}
// Select from text editor
ps = new PySelection(getTextEditor());
ps.selectAll(false);
// Perform the action
perform(ps);
// Put cursor at the first area of the selection
getTextEditor().selectAndReveal(ps.getLineOffset(), 0);
} catch (Exception e) {
beep(e);
}
}
/**
* Performs the action with a given PySelection
*
* @param ps
* Given PySelection
* @return boolean The success or failure of the action
*/
public static boolean perform(PySelection ps) {
// What we'll be replacing the selected text with
FastStringBuffer strbuf = new FastStringBuffer();
// If they selected a partial line, count it as a full one
ps.selectCompleteLine();
int i;
try {
// For each line, strip their whitespace
String tabSpace = getTabSpace();
if (tabSpace == null) {
return false; //could not get it
}
IDocument doc = ps.getDoc();
int endLineIndex = ps.getEndLineIndex();
String endLineDelim = ps.getEndLineDelim();
for (i = ps.getStartLineIndex(); i <= endLineIndex; i++) {
IRegion lineInformation = doc.getLineInformation(i);
String line = doc.get(lineInformation.getOffset(), lineInformation.getLength());
strbuf.append(line.replaceAll(tabSpace, "\t")).append((i < endLineIndex ? endLineDelim : ""));
}
// If all goes well, replace the text with the modified information
doc.replace(ps.getStartLine().getOffset(), ps.getSelLength(), strbuf.toString());
return true;
} catch (Exception e) {
beep(e);
}
// In event of problems, return false
return false;
}
/**
* Currently returns an int of the Preferences' Tab Width.
*
* @return Tab width in preferences
*/
protected static String getTabSpace() {
class NumberValidator implements IInputValidator {
/*
* @see IInputValidator#isValid(String)
*/
public String isValid(String input) {
if (input == null || input.length() == 0)
return " ";
try {
int i = Integer.parseInt(input);
if (i <= 0)
return "Must be more than 0.";
} catch (NumberFormatException x) {
return x.getMessage();
}
return null;
}
}
- InputDialog inputDialog = new InputDialog(EditorUtils.getShell(), "Tab lenght",
+ InputDialog inputDialog = new InputDialog(EditorUtils.getShell(), "Tab length",
"How many spaces should be considered for each tab?", "" + DefaultIndentPrefs.getStaticTabWidth(),
new NumberValidator());
if (inputDialog.open() != InputDialog.OK) {
return null;
}
StringBuffer sbuf = new StringBuffer();
int tabWidth = Integer.parseInt(inputDialog.getValue());
for (int i = 0; i < tabWidth; i++) {
sbuf.append(" ");
}
return sbuf.toString();
}
}
| true | true | protected static String getTabSpace() {
class NumberValidator implements IInputValidator {
/*
* @see IInputValidator#isValid(String)
*/
public String isValid(String input) {
if (input == null || input.length() == 0)
return " ";
try {
int i = Integer.parseInt(input);
if (i <= 0)
return "Must be more than 0.";
} catch (NumberFormatException x) {
return x.getMessage();
}
return null;
}
}
InputDialog inputDialog = new InputDialog(EditorUtils.getShell(), "Tab lenght",
"How many spaces should be considered for each tab?", "" + DefaultIndentPrefs.getStaticTabWidth(),
new NumberValidator());
if (inputDialog.open() != InputDialog.OK) {
return null;
}
StringBuffer sbuf = new StringBuffer();
int tabWidth = Integer.parseInt(inputDialog.getValue());
for (int i = 0; i < tabWidth; i++) {
sbuf.append(" ");
}
return sbuf.toString();
}
| protected static String getTabSpace() {
class NumberValidator implements IInputValidator {
/*
* @see IInputValidator#isValid(String)
*/
public String isValid(String input) {
if (input == null || input.length() == 0)
return " ";
try {
int i = Integer.parseInt(input);
if (i <= 0)
return "Must be more than 0.";
} catch (NumberFormatException x) {
return x.getMessage();
}
return null;
}
}
InputDialog inputDialog = new InputDialog(EditorUtils.getShell(), "Tab length",
"How many spaces should be considered for each tab?", "" + DefaultIndentPrefs.getStaticTabWidth(),
new NumberValidator());
if (inputDialog.open() != InputDialog.OK) {
return null;
}
StringBuffer sbuf = new StringBuffer();
int tabWidth = Integer.parseInt(inputDialog.getValue());
for (int i = 0; i < tabWidth; i++) {
sbuf.append(" ");
}
return sbuf.toString();
}
|
diff --git a/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/JRubyInstallType.java b/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/JRubyInstallType.java
index 8f9cef8e..6cd1cbf2 100644
--- a/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/JRubyInstallType.java
+++ b/plugins/org.eclipse.dltk.ruby.launching/src/org/eclipse/dltk/ruby/internal/launching/JRubyInstallType.java
@@ -1,66 +1,66 @@
package org.eclipse.dltk.ruby.internal.launching;
import java.io.File;
import java.io.IOException;
import org.eclipse.core.runtime.ILog;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.dltk.internal.launching.AbstractInterpreterInstallType;
import org.eclipse.dltk.internal.launching.InterpreterMessages;
import org.eclipse.dltk.launching.IInterpreterInstall;
import org.eclipse.dltk.ruby.core.RubyNature;
import org.eclipse.dltk.ruby.launching.RubyLaunchingPlugin;
import org.osgi.framework.Bundle;
public class JRubyInstallType extends AbstractInterpreterInstallType {
private static final String INSTALL_TYPE_NAME = "JRuby";
private static final String[] INTERPRETER_NAMES = { "jruby" };
public String getNatureId() {
return RubyNature.NATURE_ID;
}
public String getName() {
return INSTALL_TYPE_NAME;
}
protected String getPluginId() {
return RubyLaunchingPlugin.PLUGIN_ID;
}
protected String[] getPossibleInterpreterNames() {
return INTERPRETER_NAMES;
}
protected IInterpreterInstall doCreateInterpreterInstall(String id) {
return new RubyGenericInstall(this, id);
}
protected File createPathFile() throws IOException {
Bundle bundle = RubyLaunchingPlugin.getDefault().getBundle();
return storeToMetadata(bundle, "path.rb", "scripts/path.rb");
}
protected String getBuildPathDelimeter() {
return ";:";
}
protected ILog getLog() {
return RubyLaunchingPlugin.getDefault().getLog();
}
public IStatus validateInstallLocation(File installLocation) {
if (!Platform.getOS().equals(Platform.OS_WIN32)) {
- if (installLocation.getName().indexOf(".bat") != 0) {
+ if (installLocation.getName().indexOf(".bat") != -1) {
return createStatus(
IStatus.ERROR,
InterpreterMessages.errNonExistentOrInvalidInstallLocation,
null);
}
}
return super.validateInstallLocation(installLocation);
}
}
| true | true | public IStatus validateInstallLocation(File installLocation) {
if (!Platform.getOS().equals(Platform.OS_WIN32)) {
if (installLocation.getName().indexOf(".bat") != 0) {
return createStatus(
IStatus.ERROR,
InterpreterMessages.errNonExistentOrInvalidInstallLocation,
null);
}
}
return super.validateInstallLocation(installLocation);
}
| public IStatus validateInstallLocation(File installLocation) {
if (!Platform.getOS().equals(Platform.OS_WIN32)) {
if (installLocation.getName().indexOf(".bat") != -1) {
return createStatus(
IStatus.ERROR,
InterpreterMessages.errNonExistentOrInvalidInstallLocation,
null);
}
}
return super.validateInstallLocation(installLocation);
}
|
diff --git a/sdkmanager/libs/sdklib/src/com/android/sdklib/AddOnTarget.java b/sdkmanager/libs/sdklib/src/com/android/sdklib/AddOnTarget.java
index d72cd9430..f5fcf9024 100644
--- a/sdkmanager/libs/sdklib/src/com/android/sdklib/AddOnTarget.java
+++ b/sdkmanager/libs/sdklib/src/com/android/sdklib/AddOnTarget.java
@@ -1,329 +1,329 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.sdklib;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
/**
* Represents an add-on target in the SDK.
* An add-on extends a standard {@link PlatformTarget}.
*/
final class AddOnTarget implements IAndroidTarget {
/**
* String to compute hash for add-on targets.
* Format is vendor:name:apiVersion
* */
private final static String ADD_ON_FORMAT = "%s:%s:%s"; //$NON-NLS-1$
private final static class OptionalLibrary implements IOptionalLibrary {
private final String mJarName;
private final String mJarPath;
private final String mName;
private final String mDescription;
OptionalLibrary(String jarName, String jarPath, String name, String description) {
mJarName = jarName;
mJarPath = jarPath;
mName = name;
mDescription = description;
}
public String getJarName() {
return mJarName;
}
public String getJarPath() {
return mJarPath;
}
public String getName() {
return mName;
}
public String getDescription() {
return mDescription;
}
}
private final String mLocation;
private final PlatformTarget mBasePlatform;
private final String mName;
private final String mVendor;
private final int mRevision;
private final String mDescription;
private String[] mSkins;
private String mDefaultSkin;
private IOptionalLibrary[] mLibraries;
private int mVendorId = NO_USB_ID;
/**
* Creates a new add-on
* @param location the OS path location of the add-on
* @param name the name of the add-on
* @param vendor the vendor name of the add-on
* @param revision the revision of the add-on
* @param description the add-on description
* @param libMap A map containing the optional libraries. The map key is the fully-qualified
* library name. The value is a 2 string array with the .jar filename, and the description.
* @param basePlatform the platform the add-on is extending.
*/
AddOnTarget(String location, String name, String vendor, int revision, String description,
Map<String, String[]> libMap, PlatformTarget basePlatform) {
if (location.endsWith(File.separator) == false) {
location = location + File.separator;
}
mLocation = location;
mName = name;
mVendor = vendor;
mRevision = revision;
mDescription = description;
mBasePlatform = basePlatform;
// handle the optional libraries.
if (libMap != null) {
mLibraries = new IOptionalLibrary[libMap.size()];
int index = 0;
for (Entry<String, String[]> entry : libMap.entrySet()) {
String jarFile = entry.getValue()[0];
String desc = entry.getValue()[1];
mLibraries[index++] = new OptionalLibrary(jarFile,
mLocation + SdkConstants.OS_ADDON_LIBS_FOLDER + jarFile,
entry.getKey(), desc);
}
}
}
public String getLocation() {
return mLocation;
}
public String getName() {
return mName;
}
public String getVendor() {
return mVendor;
}
public String getFullName() {
return String.format("%1$s (%2$s)", mName, mVendor);
}
public String getClasspathName() {
return String.format("%1$s [%2$s]", mName, mBasePlatform.getName());
}
public String getDescription() {
return mDescription;
}
public AndroidVersion getVersion() {
// this is always defined by the base platform
return mBasePlatform.getVersion();
}
public String getVersionName() {
return mBasePlatform.getVersionName();
}
public int getRevision() {
return mRevision;
}
public boolean isPlatform() {
return false;
}
public IAndroidTarget getParent() {
return mBasePlatform;
}
public String getPath(int pathId) {
switch (pathId) {
case IMAGES:
return mLocation + SdkConstants.OS_IMAGES_FOLDER;
case SKINS:
return mLocation + SdkConstants.OS_SKINS_FOLDER;
case DOCS:
return mLocation + SdkConstants.FD_DOCS + File.separator
+ SdkConstants.FD_DOCS_REFERENCE;
case SAMPLES:
// only return the add-on samples folder if there is actually a sample (or more)
File sampleLoc = new File(mLocation, SdkConstants.FD_SAMPLES);
if (sampleLoc.isDirectory()) {
File[] files = sampleLoc.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
if (files != null && files.length > 0) {
return sampleLoc.getAbsolutePath();
}
}
// INTENDED FALL-THROUGH
default :
return mBasePlatform.getPath(pathId);
}
}
public String[] getSkins() {
return mSkins;
}
public String getDefaultSkin() {
return mDefaultSkin;
}
public IOptionalLibrary[] getOptionalLibraries() {
return mLibraries;
}
/**
* Returns the list of libraries of the underlying platform.
*
* {@inheritDoc}
*/
public String[] getPlatformLibraries() {
return mBasePlatform.getPlatformLibraries();
}
public int getUsbVendorId() {
return mVendorId;
}
public boolean isCompatibleBaseFor(IAndroidTarget target) {
// basic test
if (target == this) {
return true;
}
/*
* The method javadoc indicates:
* Returns whether the given target is compatible with the receiver.
* <p/>A target is considered compatible if applications developed for the receiver can
* run on the given target.
*/
// The receiver is an add-on. There are 2 big use cases: The add-on has libraries
// or the add-on doesn't (in which case we consider it a platform).
- if (mLibraries.length == 0) {
+ if (mLibraries == null || mLibraries.length == 0) {
return mBasePlatform.isCompatibleBaseFor(target);
} else {
// the only targets that can run the receiver are the same add-on in the same or later
// versions.
// first check: vendor/name
if (mVendor.equals(target.getVendor()) == false ||
mName.equals(target.getName()) == false) {
return false;
}
// now check the version. At this point since we checked the add-on part,
// we can revert to the basic check on version/codename which are done by the
// base platform already.
return mBasePlatform.isCompatibleBaseFor(target);
}
}
public String hashString() {
return String.format(ADD_ON_FORMAT, mVendor, mName,
mBasePlatform.getVersion().getApiString());
}
@Override
public int hashCode() {
return hashString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddOnTarget) {
AddOnTarget addon = (AddOnTarget)obj;
return mVendor.equals(addon.mVendor) && mName.equals(addon.mName) &&
mBasePlatform.getVersion().equals(addon.mBasePlatform.getVersion());
}
return false;
}
/*
* Always return +1 if the object we compare to is a platform.
* Otherwise, do vendor then name then api version comparison.
* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(IAndroidTarget target) {
if (target.isPlatform()) {
return +1;
}
// compare vendor
int value = mVendor.compareTo(target.getVendor());
// if same vendor, compare name
if (value == 0) {
value = mName.compareTo(target.getName());
}
// if same vendor/name, compare version
if (value == 0) {
if (getVersion().isPreview() == true) {
value = target.getVersion().isPreview() == true ?
getVersion().getApiString().compareTo(target.getVersion().getApiString()) :
+1; // put the preview at the end.
} else {
value = target.getVersion().isPreview() == true ?
-1 : // put the preview at the end :
getVersion().getApiLevel() - target.getVersion().getApiLevel();
}
}
return value;
}
// ---- local methods.
void setSkins(String[] skins, String defaultSkin) {
mDefaultSkin = defaultSkin;
// we mix the add-on and base platform skins
HashSet<String> skinSet = new HashSet<String>();
skinSet.addAll(Arrays.asList(skins));
skinSet.addAll(Arrays.asList(mBasePlatform.getSkins()));
mSkins = skinSet.toArray(new String[skinSet.size()]);
}
/**
* Sets the USB vendor id in the add-on.
*/
void setUsbVendorId(int vendorId) {
if (vendorId == 0) {
throw new IllegalArgumentException( "VendorId must be > 0");
}
mVendorId = vendorId;
}
}
| true | true | public boolean isCompatibleBaseFor(IAndroidTarget target) {
// basic test
if (target == this) {
return true;
}
/*
* The method javadoc indicates:
* Returns whether the given target is compatible with the receiver.
* <p/>A target is considered compatible if applications developed for the receiver can
* run on the given target.
*/
// The receiver is an add-on. There are 2 big use cases: The add-on has libraries
// or the add-on doesn't (in which case we consider it a platform).
if (mLibraries.length == 0) {
return mBasePlatform.isCompatibleBaseFor(target);
} else {
// the only targets that can run the receiver are the same add-on in the same or later
// versions.
// first check: vendor/name
if (mVendor.equals(target.getVendor()) == false ||
mName.equals(target.getName()) == false) {
return false;
}
// now check the version. At this point since we checked the add-on part,
// we can revert to the basic check on version/codename which are done by the
// base platform already.
return mBasePlatform.isCompatibleBaseFor(target);
}
}
| public boolean isCompatibleBaseFor(IAndroidTarget target) {
// basic test
if (target == this) {
return true;
}
/*
* The method javadoc indicates:
* Returns whether the given target is compatible with the receiver.
* <p/>A target is considered compatible if applications developed for the receiver can
* run on the given target.
*/
// The receiver is an add-on. There are 2 big use cases: The add-on has libraries
// or the add-on doesn't (in which case we consider it a platform).
if (mLibraries == null || mLibraries.length == 0) {
return mBasePlatform.isCompatibleBaseFor(target);
} else {
// the only targets that can run the receiver are the same add-on in the same or later
// versions.
// first check: vendor/name
if (mVendor.equals(target.getVendor()) == false ||
mName.equals(target.getName()) == false) {
return false;
}
// now check the version. At this point since we checked the add-on part,
// we can revert to the basic check on version/codename which are done by the
// base platform already.
return mBasePlatform.isCompatibleBaseFor(target);
}
}
|
diff --git a/test/org/encog/neural/activation/TestActivationSoftMax.java b/test/org/encog/neural/activation/TestActivationSoftMax.java
index bdee091aa..369030bd5 100644
--- a/test/org/encog/neural/activation/TestActivationSoftMax.java
+++ b/test/org/encog/neural/activation/TestActivationSoftMax.java
@@ -1,45 +1,45 @@
package org.encog.neural.activation;
import junit.framework.TestCase;
import org.encog.EncogError;
import org.encog.persist.persistors.ActivationBiPolarPersistor;
import org.encog.persist.persistors.ActivationSoftMaxPersistor;
import org.junit.Assert;
import org.junit.Test;
public class TestActivationSoftMax extends TestCase {
@Test
public void testSoftMax() throws Throwable
{
ActivationSoftMax activation = new ActivationSoftMax();
- Assert.assertFalse(activation.hasDerivative());
+ Assert.assertTrue(activation.hasDerivative());
ActivationSoftMax clone = (ActivationSoftMax)activation.clone();
Assert.assertNotNull(clone);
double[] input = {1.0,1.0,1.0,1.0 };
activation.activationFunction(input);
Assert.assertEquals(0.25,input[0],0.1);
Assert.assertEquals(0.25,input[1],0.1);
// this will throw an error if it does not work
ActivationSoftMaxPersistor p = (ActivationSoftMaxPersistor)activation.createPersistor();
// test derivative
activation.derivativeFunction(input);
// test name and description
// names and descriptions are not stored for these
activation.setName("name");
activation.setDescription("name");
Assert.assertEquals(null, activation.getName());
Assert.assertEquals(null, activation.getDescription() );
}
}
| true | true | public void testSoftMax() throws Throwable
{
ActivationSoftMax activation = new ActivationSoftMax();
Assert.assertFalse(activation.hasDerivative());
ActivationSoftMax clone = (ActivationSoftMax)activation.clone();
Assert.assertNotNull(clone);
double[] input = {1.0,1.0,1.0,1.0 };
activation.activationFunction(input);
Assert.assertEquals(0.25,input[0],0.1);
Assert.assertEquals(0.25,input[1],0.1);
// this will throw an error if it does not work
ActivationSoftMaxPersistor p = (ActivationSoftMaxPersistor)activation.createPersistor();
// test derivative
activation.derivativeFunction(input);
// test name and description
// names and descriptions are not stored for these
activation.setName("name");
activation.setDescription("name");
Assert.assertEquals(null, activation.getName());
Assert.assertEquals(null, activation.getDescription() );
}
| public void testSoftMax() throws Throwable
{
ActivationSoftMax activation = new ActivationSoftMax();
Assert.assertTrue(activation.hasDerivative());
ActivationSoftMax clone = (ActivationSoftMax)activation.clone();
Assert.assertNotNull(clone);
double[] input = {1.0,1.0,1.0,1.0 };
activation.activationFunction(input);
Assert.assertEquals(0.25,input[0],0.1);
Assert.assertEquals(0.25,input[1],0.1);
// this will throw an error if it does not work
ActivationSoftMaxPersistor p = (ActivationSoftMaxPersistor)activation.createPersistor();
// test derivative
activation.derivativeFunction(input);
// test name and description
// names and descriptions are not stored for these
activation.setName("name");
activation.setDescription("name");
Assert.assertEquals(null, activation.getName());
Assert.assertEquals(null, activation.getDescription() );
}
|
diff --git a/de.xwic.etlgine/src_test/de/xwic/etlgine/CubeLoaderTest.java b/de.xwic.etlgine/src_test/de/xwic/etlgine/CubeLoaderTest.java
index 8467362..6bc5d53 100644
--- a/de.xwic.etlgine/src_test/de/xwic/etlgine/CubeLoaderTest.java
+++ b/de.xwic.etlgine/src_test/de/xwic/etlgine/CubeLoaderTest.java
@@ -1,63 +1,63 @@
/*
* de.xwic.etlgine.CubeLoaderTest
*/
package de.xwic.etlgine;
import java.io.File;
import junit.framework.TestCase;
import de.xwic.cube.DataPoolManagerFactory;
import de.xwic.cube.IDataPool;
import de.xwic.cube.IDataPoolManager;
import de.xwic.cube.IDataPoolStorageProvider;
import de.xwic.cube.storage.impl.FileDataPoolStorageProvider;
import de.xwic.cube.util.DataDump;
import de.xwic.etlgine.extractor.CSVExtractor;
import de.xwic.etlgine.loader.cube.CubeLoader;
import de.xwic.etlgine.loader.cube.DataPoolInitializer;
import de.xwic.etlgine.loader.cube.IDataPoolProvider;
import de.xwic.etlgine.loader.cube.ScriptedCubeDataMapper;
import de.xwic.etlgine.sources.FileSource;
/**
* @author lippisch
*/
public class CubeLoaderTest extends TestCase {
public void testCubeLoader() throws ETLException {
- IETLProcess process = ETLgine.createETLProcess("cubeLoadeTest");
+ IETLProcess process = ETLgine.createETLProcess("cubeLoaderTest");
FileSource srcFile = new FileSource("test/source_cube.csv");
process.addSource(srcFile);
assertEquals(1, process.getSources().size());
CSVExtractor csvExtractor = new CSVExtractor();
csvExtractor.setSeparator('\t');
process.setExtractor(csvExtractor);
IDataPoolStorageProvider storageProvider = new FileDataPoolStorageProvider(new File("test"));
IDataPoolManager dpm = DataPoolManagerFactory.createDataPoolManager(storageProvider);
final IDataPool pool = dpm.createDataPool("Test");
// add cube loader
IDataPoolProvider dpp = new IDataPoolProvider() {
/* (non-Javadoc)
* @see de.xwic.etlgine.loader.cube.IDataPoolProvider#getDataPool()
*/
public IDataPool getDataPool() {
return pool;
}
};
CubeLoader cubeLoader = new CubeLoader(dpp);
cubeLoader.setTargetCubeKey("Test");
cubeLoader.setDataPoolInitializer(new DataPoolInitializer(new File("scripts/testcube.init.groovy")));
cubeLoader.setDataMapper(new ScriptedCubeDataMapper(new File("scripts/testcube.mapping.groovy")));
process.addLoader(cubeLoader);
process.start();
//DataDump.printStructure(System.out, pool.getDimension("Area"));
DataDump.printValues(System.out, pool.getCube("Test"), pool.getDimension("Area"), pool.getDimension("Name"), pool.getMeasure("Bookings"));
}
}
| true | true | public void testCubeLoader() throws ETLException {
IETLProcess process = ETLgine.createETLProcess("cubeLoadeTest");
FileSource srcFile = new FileSource("test/source_cube.csv");
process.addSource(srcFile);
assertEquals(1, process.getSources().size());
CSVExtractor csvExtractor = new CSVExtractor();
csvExtractor.setSeparator('\t');
process.setExtractor(csvExtractor);
IDataPoolStorageProvider storageProvider = new FileDataPoolStorageProvider(new File("test"));
IDataPoolManager dpm = DataPoolManagerFactory.createDataPoolManager(storageProvider);
final IDataPool pool = dpm.createDataPool("Test");
// add cube loader
IDataPoolProvider dpp = new IDataPoolProvider() {
/* (non-Javadoc)
* @see de.xwic.etlgine.loader.cube.IDataPoolProvider#getDataPool()
*/
public IDataPool getDataPool() {
return pool;
}
};
CubeLoader cubeLoader = new CubeLoader(dpp);
cubeLoader.setTargetCubeKey("Test");
cubeLoader.setDataPoolInitializer(new DataPoolInitializer(new File("scripts/testcube.init.groovy")));
cubeLoader.setDataMapper(new ScriptedCubeDataMapper(new File("scripts/testcube.mapping.groovy")));
process.addLoader(cubeLoader);
process.start();
//DataDump.printStructure(System.out, pool.getDimension("Area"));
DataDump.printValues(System.out, pool.getCube("Test"), pool.getDimension("Area"), pool.getDimension("Name"), pool.getMeasure("Bookings"));
}
| public void testCubeLoader() throws ETLException {
IETLProcess process = ETLgine.createETLProcess("cubeLoaderTest");
FileSource srcFile = new FileSource("test/source_cube.csv");
process.addSource(srcFile);
assertEquals(1, process.getSources().size());
CSVExtractor csvExtractor = new CSVExtractor();
csvExtractor.setSeparator('\t');
process.setExtractor(csvExtractor);
IDataPoolStorageProvider storageProvider = new FileDataPoolStorageProvider(new File("test"));
IDataPoolManager dpm = DataPoolManagerFactory.createDataPoolManager(storageProvider);
final IDataPool pool = dpm.createDataPool("Test");
// add cube loader
IDataPoolProvider dpp = new IDataPoolProvider() {
/* (non-Javadoc)
* @see de.xwic.etlgine.loader.cube.IDataPoolProvider#getDataPool()
*/
public IDataPool getDataPool() {
return pool;
}
};
CubeLoader cubeLoader = new CubeLoader(dpp);
cubeLoader.setTargetCubeKey("Test");
cubeLoader.setDataPoolInitializer(new DataPoolInitializer(new File("scripts/testcube.init.groovy")));
cubeLoader.setDataMapper(new ScriptedCubeDataMapper(new File("scripts/testcube.mapping.groovy")));
process.addLoader(cubeLoader);
process.start();
//DataDump.printStructure(System.out, pool.getDimension("Area"));
DataDump.printValues(System.out, pool.getCube("Test"), pool.getDimension("Area"), pool.getDimension("Name"), pool.getMeasure("Bookings"));
}
|
diff --git a/src/main/java/com/caffeinatedrat/Spectator/ApplicationLayer.java b/src/main/java/com/caffeinatedrat/Spectator/ApplicationLayer.java
index 0eeea69..f3bb132 100644
--- a/src/main/java/com/caffeinatedrat/Spectator/ApplicationLayer.java
+++ b/src/main/java/com/caffeinatedrat/Spectator/ApplicationLayer.java
@@ -1,187 +1,189 @@
/**
* Copyright (c) 2013, Ken Anderson <caffeinatedrat at gmail dot com>
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.caffeinatedrat.Spectator;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import com.caffeinatedrat.SimpleWebSockets.IApplicationLayer;
import com.caffeinatedrat.SimpleWebSockets.ResponseWrapper;
import com.caffeinatedrat.SimpleWebSockets.TextResponse;
public class ApplicationLayer implements IApplicationLayer {
// ----------------------------------------------
// Member Vars (fields)
// ----------------------------------------------
private org.bukkit.Server minecraftServer;
private SpectatorConfiguration config;
// ----------------------------------------------
// Constructors
// ----------------------------------------------
public ApplicationLayer(org.bukkit.Server minecraftServer, SpectatorConfiguration config) {
this.minecraftServer = minecraftServer;
this.config = config;
}
@Override
public void onTextFrame(String text, ResponseWrapper responseWrapper) {
//A text-response is what we'll use during the experimental phase, while we'll eventually move to a binary model.
responseWrapper.response = new TextResponse();
if(text.equalsIgnoreCase("spectator")) {
Hashtable<String, Object> masterCollection = ((TextResponse)responseWrapper.response).getCollection();
List<Hashtable<String, Object>> blocks = new ArrayList<Hashtable<String, Object>>();
masterCollection.put("blocks", blocks);
org.bukkit.util.Vector positionVector = null;
Player[] players = this.minecraftServer.getOnlinePlayers();
if (players.length > 0) {
//For now, have the player send his her location as the camera.
for(Player player : players) {
- if (player.getName().equalsIgnoreCase("caffeinatedrat")) {
+ //if (player.getName().equalsIgnoreCase("caffeinatedrat")) {
+ //Use the first player's position...yeah...this is only for testing, a bad way to handle this.
positionVector = player.getLocation().toVector();
+ break;
- }
+ //}
}
}
else {
positionVector = this.config.getCamera();
}
org.bukkit.util.Vector rangeVector = this.config.getRange();
masterCollection.put("origin", MessageFormat.format("x: {0}, y: {1}, z: {2}", positionVector.getX(), positionVector.getY(), positionVector.getZ()));
masterCollection.put("chunkSizeX", rangeVector.getBlockX());
masterCollection.put("chunkSizeY", rangeVector.getBlockY());
masterCollection.put("chunkSizeZ", rangeVector.getBlockZ());
if (positionVector != null) {
List<World> worlds = this.minecraftServer.getWorlds();
if (worlds.size() > 0) {
World world = worlds.get(0);
int x = positionVector.getBlockX();
int y = positionVector.getBlockY();
int z = positionVector.getBlockZ();
for (int i = (x - rangeVector.getBlockX()); i <= (x + rangeVector.getBlockX()); i++) {
for (int j = (y - rangeVector.getBlockY()); j <= (y + rangeVector.getBlockY()); j++) {
for (int k = (z - rangeVector.getBlockZ()); k <= (z + rangeVector.getBlockZ()); k++) {
Block block = world.getBlockAt(i, j, k);
if (block != null) {
Hashtable<String, Object> collection = new Hashtable<String, Object>();
Material material = block.getType();
//Allocate 2^16 for the id when going binary.
collection.put("type", material.getId());
//Allocate 2^32 for the each axis when going binary.
collection.put("x", i - positionVector.getBlockX());
collection.put("y", j - positionVector.getBlockY());
collection.put("z", k - positionVector.getBlockZ());
//Allocate 2^32 for the environmental data.
collection.put("humidity", block.getHumidity());
collection.put("temperature", block.getTemperature());
//Not sure what this does yet...
collection.put("data", block.getData());
//Convert to a bitstring when going binary...
collection.put("isLiquid", block.isLiquid());
collection.put("isTransparent", material.isTransparent());
collection.put("isOccluding", material.isOccluding());
collection.put("isOccluding", material.isOccluding());
blocks.add(collection);
}
}
//END OF for (int k = -scaleZ; k < ScaleZ; k++) {...
}
//END OF for (int j = -scaleY; j < scaleY; j++) {...
}
//END OF for(int i = -scaleX; i < scaleX; i++) {...
}
}
}
}
@Override
public void onBinaryFrame(byte[] data, ResponseWrapper responseWrapper) {
// TODO Auto-generated method stub
}
@Override
public void onClose() {
// TODO Auto-generated method stub
}
@Override
public void onPing(byte[] data) {
// TODO Auto-generated method stub
}
@Override
public void onPong() {
// TODO Auto-generated method stub
}
}
| false | true | public void onTextFrame(String text, ResponseWrapper responseWrapper) {
//A text-response is what we'll use during the experimental phase, while we'll eventually move to a binary model.
responseWrapper.response = new TextResponse();
if(text.equalsIgnoreCase("spectator")) {
Hashtable<String, Object> masterCollection = ((TextResponse)responseWrapper.response).getCollection();
List<Hashtable<String, Object>> blocks = new ArrayList<Hashtable<String, Object>>();
masterCollection.put("blocks", blocks);
org.bukkit.util.Vector positionVector = null;
Player[] players = this.minecraftServer.getOnlinePlayers();
if (players.length > 0) {
//For now, have the player send his her location as the camera.
for(Player player : players) {
if (player.getName().equalsIgnoreCase("caffeinatedrat")) {
positionVector = player.getLocation().toVector();
}
}
}
else {
positionVector = this.config.getCamera();
}
org.bukkit.util.Vector rangeVector = this.config.getRange();
masterCollection.put("origin", MessageFormat.format("x: {0}, y: {1}, z: {2}", positionVector.getX(), positionVector.getY(), positionVector.getZ()));
masterCollection.put("chunkSizeX", rangeVector.getBlockX());
masterCollection.put("chunkSizeY", rangeVector.getBlockY());
masterCollection.put("chunkSizeZ", rangeVector.getBlockZ());
if (positionVector != null) {
List<World> worlds = this.minecraftServer.getWorlds();
if (worlds.size() > 0) {
World world = worlds.get(0);
int x = positionVector.getBlockX();
int y = positionVector.getBlockY();
int z = positionVector.getBlockZ();
for (int i = (x - rangeVector.getBlockX()); i <= (x + rangeVector.getBlockX()); i++) {
for (int j = (y - rangeVector.getBlockY()); j <= (y + rangeVector.getBlockY()); j++) {
for (int k = (z - rangeVector.getBlockZ()); k <= (z + rangeVector.getBlockZ()); k++) {
Block block = world.getBlockAt(i, j, k);
if (block != null) {
Hashtable<String, Object> collection = new Hashtable<String, Object>();
Material material = block.getType();
//Allocate 2^16 for the id when going binary.
collection.put("type", material.getId());
//Allocate 2^32 for the each axis when going binary.
collection.put("x", i - positionVector.getBlockX());
collection.put("y", j - positionVector.getBlockY());
collection.put("z", k - positionVector.getBlockZ());
//Allocate 2^32 for the environmental data.
collection.put("humidity", block.getHumidity());
collection.put("temperature", block.getTemperature());
//Not sure what this does yet...
collection.put("data", block.getData());
//Convert to a bitstring when going binary...
collection.put("isLiquid", block.isLiquid());
collection.put("isTransparent", material.isTransparent());
collection.put("isOccluding", material.isOccluding());
collection.put("isOccluding", material.isOccluding());
blocks.add(collection);
}
}
//END OF for (int k = -scaleZ; k < ScaleZ; k++) {...
}
//END OF for (int j = -scaleY; j < scaleY; j++) {...
}
//END OF for(int i = -scaleX; i < scaleX; i++) {...
}
}
}
}
| public void onTextFrame(String text, ResponseWrapper responseWrapper) {
//A text-response is what we'll use during the experimental phase, while we'll eventually move to a binary model.
responseWrapper.response = new TextResponse();
if(text.equalsIgnoreCase("spectator")) {
Hashtable<String, Object> masterCollection = ((TextResponse)responseWrapper.response).getCollection();
List<Hashtable<String, Object>> blocks = new ArrayList<Hashtable<String, Object>>();
masterCollection.put("blocks", blocks);
org.bukkit.util.Vector positionVector = null;
Player[] players = this.minecraftServer.getOnlinePlayers();
if (players.length > 0) {
//For now, have the player send his her location as the camera.
for(Player player : players) {
//if (player.getName().equalsIgnoreCase("caffeinatedrat")) {
//Use the first player's position...yeah...this is only for testing, a bad way to handle this.
positionVector = player.getLocation().toVector();
break;
//}
}
}
else {
positionVector = this.config.getCamera();
}
org.bukkit.util.Vector rangeVector = this.config.getRange();
masterCollection.put("origin", MessageFormat.format("x: {0}, y: {1}, z: {2}", positionVector.getX(), positionVector.getY(), positionVector.getZ()));
masterCollection.put("chunkSizeX", rangeVector.getBlockX());
masterCollection.put("chunkSizeY", rangeVector.getBlockY());
masterCollection.put("chunkSizeZ", rangeVector.getBlockZ());
if (positionVector != null) {
List<World> worlds = this.minecraftServer.getWorlds();
if (worlds.size() > 0) {
World world = worlds.get(0);
int x = positionVector.getBlockX();
int y = positionVector.getBlockY();
int z = positionVector.getBlockZ();
for (int i = (x - rangeVector.getBlockX()); i <= (x + rangeVector.getBlockX()); i++) {
for (int j = (y - rangeVector.getBlockY()); j <= (y + rangeVector.getBlockY()); j++) {
for (int k = (z - rangeVector.getBlockZ()); k <= (z + rangeVector.getBlockZ()); k++) {
Block block = world.getBlockAt(i, j, k);
if (block != null) {
Hashtable<String, Object> collection = new Hashtable<String, Object>();
Material material = block.getType();
//Allocate 2^16 for the id when going binary.
collection.put("type", material.getId());
//Allocate 2^32 for the each axis when going binary.
collection.put("x", i - positionVector.getBlockX());
collection.put("y", j - positionVector.getBlockY());
collection.put("z", k - positionVector.getBlockZ());
//Allocate 2^32 for the environmental data.
collection.put("humidity", block.getHumidity());
collection.put("temperature", block.getTemperature());
//Not sure what this does yet...
collection.put("data", block.getData());
//Convert to a bitstring when going binary...
collection.put("isLiquid", block.isLiquid());
collection.put("isTransparent", material.isTransparent());
collection.put("isOccluding", material.isOccluding());
collection.put("isOccluding", material.isOccluding());
blocks.add(collection);
}
}
//END OF for (int k = -scaleZ; k < ScaleZ; k++) {...
}
//END OF for (int j = -scaleY; j < scaleY; j++) {...
}
//END OF for(int i = -scaleX; i < scaleX; i++) {...
}
}
}
}
|
diff --git a/src/ru/spbau/martynov/task3/Decompressor.java b/src/ru/spbau/martynov/task3/Decompressor.java
index f12ea7d..992c348 100644
--- a/src/ru/spbau/martynov/task3/Decompressor.java
+++ b/src/ru/spbau/martynov/task3/Decompressor.java
@@ -1,128 +1,123 @@
package ru.spbau.martynov.task3;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.BufferedOutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/**
* @author Semen A Martynov, 4 Mar 2013
*
* Class for extraction of directories and files from archive.
*/
public class Decompressor {
/**
* Constructor with one parameter
*
* @param archiveName
* Name of archive from which files are derived
* @throws ZipException
* if a ZIP format error has occurred
* @throws SecurityException
* if a security manager exists and its checkRead method doesn't
* allow read access to the file.
* @throws IOException
* if an I/O error has occurred
*/
Decompressor(String archiveName) throws ZipException, SecurityException,
IOException {
zipFile = new ZipFile(archiveName);
}
/**
* Function views archive and finds the archived files.
*
* @throws ZipException
* if a ZIP format error has occurred
* @throws IOException
* if an I/O error has occurred
*/
public void get() throws ZipException, IOException {
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) entries.nextElement();
String zipEntryPath = zipEntry.getName();
write(zipEntryPath, zipFile.getInputStream(zipEntry));
}
}
/**
* Function creates structure of directories and pulls out files from
* archive.
*
* @param filePath
* The file being in archive
* @param inputStream
* Stream for reading the file from archive
* @throws IOException
* if an I/O error has occurred
*/
private static void write(String filePath, InputStream inputStream)
throws IOException {
System.out.print(filePath);
OutputStream outputStream = null;
try {
int index = filePath.lastIndexOf('/');
if (index != -1) {
File file = new File(filePath.substring(0, index + 1));
// creates structure of directories
file.mkdirs();
}
outputStream = new BufferedOutputStream(new FileOutputStream(
filePath));
byte[] buffer = new byte[8000];
int len;
// pulls out files from archive
while ((len = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, len);
} catch (SecurityException | FileNotFoundException e) {
System.out.println(" securityException problem - skipped");
e.printStackTrace(System.err);
} finally {
- if (outputStream != null) {
- try {
+ try {
+ if (outputStream != null) {
outputStream.close();
- } catch (IOException e) {
- e.printStackTrace(System.err);
}
- }
- if (inputStream != null) {
- try {
+ } finally {
+ if (inputStream != null) {
inputStream.close();
- } catch (IOException e) {
- e.printStackTrace(System.err);
}
}
}
System.out.println(" - decopressed");
}
/**
* Closes ZipFile and releases resources
*
* @throws IOException
* if an I/O error has occurred
*/
public void close() throws IOException {
if (zipFile != null) {
zipFile.close();
}
}
/**
* Structure with ZIP archive
*/
private ZipFile zipFile;
}
| false | true | private static void write(String filePath, InputStream inputStream)
throws IOException {
System.out.print(filePath);
OutputStream outputStream = null;
try {
int index = filePath.lastIndexOf('/');
if (index != -1) {
File file = new File(filePath.substring(0, index + 1));
// creates structure of directories
file.mkdirs();
}
outputStream = new BufferedOutputStream(new FileOutputStream(
filePath));
byte[] buffer = new byte[8000];
int len;
// pulls out files from archive
while ((len = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, len);
} catch (SecurityException | FileNotFoundException e) {
System.out.println(" securityException problem - skipped");
e.printStackTrace(System.err);
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
System.out.println(" - decopressed");
}
| private static void write(String filePath, InputStream inputStream)
throws IOException {
System.out.print(filePath);
OutputStream outputStream = null;
try {
int index = filePath.lastIndexOf('/');
if (index != -1) {
File file = new File(filePath.substring(0, index + 1));
// creates structure of directories
file.mkdirs();
}
outputStream = new BufferedOutputStream(new FileOutputStream(
filePath));
byte[] buffer = new byte[8000];
int len;
// pulls out files from archive
while ((len = inputStream.read(buffer)) != -1)
outputStream.write(buffer, 0, len);
} catch (SecurityException | FileNotFoundException e) {
System.out.println(" securityException problem - skipped");
e.printStackTrace(System.err);
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
System.out.println(" - decopressed");
}
|
diff --git a/src/main/java/ar/edu/it/itba/pdc/proxy/implementations/proxy/DecoderImpl.java b/src/main/java/ar/edu/it/itba/pdc/proxy/implementations/proxy/DecoderImpl.java
index 53741f4..d76cada 100755
--- a/src/main/java/ar/edu/it/itba/pdc/proxy/implementations/proxy/DecoderImpl.java
+++ b/src/main/java/ar/edu/it/itba/pdc/proxy/implementations/proxy/DecoderImpl.java
@@ -1,594 +1,589 @@
package ar.edu.it.itba.pdc.proxy.implementations.proxy;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.Map;
import ar.edu.it.itba.pdc.proxy.implementations.configurator.interfaces.Configurator;
import ar.edu.it.itba.pdc.proxy.implementations.utils.HTML;
import ar.edu.it.itba.pdc.proxy.implementations.utils.HTTPPacket;
import ar.edu.it.itba.pdc.proxy.implementations.utils.RebuiltHeader;
import ar.edu.it.itba.pdc.proxy.implementations.utils.Transformations;
import ar.edu.it.itba.pdc.proxy.interfaces.Decoder;
import ar.edu.it.itba.pdc.proxy.interfaces.HTTPHeaders;
public class DecoderImpl implements Decoder {
private boolean read = true;
private HTTPHeaders headers = null;
private String fileName;
private int keepReadingBytes = 0;
private boolean isImage = false;
private boolean isText = false;
private Configurator configurator;
private byte[] aux;
private int auxIndex = 0;
private Charset charset = null;
private boolean BUILDING_NUMBER = true;
private boolean N_EXPECTED = false;
private boolean SECN_EXPECTED = false;
private boolean R_EXPECTED = false;
private boolean SECR_EXPECTED = false;
private boolean READING_CONTENT = false;
private boolean FINISHED = false;
public DecoderImpl(Configurator configurator) {
headers = new HTTPPacket();
aux = new byte[100];
this.configurator = configurator;
}
public byte[] getExtra(byte[] data, int count) {
byte[] bytes = new byte[count - headers.getReadBytes()];
int i = 0;
boolean R_EXPECTED = true;
boolean N_EXPECTED = false;
boolean SECR_EXPECTED = false;
boolean SECN_EXPECTED = false;
for (int j = 0; j < count; j++) {
if (R_EXPECTED && data[j] == '\r') {
R_EXPECTED = false;
N_EXPECTED = true;
} else if (N_EXPECTED && data[j] == '\n') {
N_EXPECTED = false;
SECR_EXPECTED = true;
} else if (N_EXPECTED) {
N_EXPECTED = false;
R_EXPECTED = true;
} else if (SECR_EXPECTED && data[j] == '\r') {
SECR_EXPECTED = false;
SECN_EXPECTED = true;
} else if (SECR_EXPECTED) {
SECR_EXPECTED = false;
R_EXPECTED = true;
} else if (SECN_EXPECTED && data[j] == '\n') {
j++;
for (i = 0; i < count - headers.getReadBytes() && j < count; i++) {
bytes[i] = data[j++];
}
return bytes;
} else {
SECN_EXPECTED = false;
R_EXPECTED = true;
}
}
return bytes;
}
public boolean keepReading() {
return read;
}
public boolean contentExpected() {
return headers.contentExpected();
}
private boolean isChunked() {
return (headers.getHeader("Transfer-Encoding") != null)
&& (headers.getHeader("Transfer-Encoding").contains("chunked"));
}
public String getHeader(String header) {
return headers.getHeader(header);
}
private void analizeMediaType() {
if (headers.getHeader("Content-Type") != null) {
isImage = headers.getHeader("Content-Type").contains("image/");
isText = headers.getHeader("Content-Type").contains("text/plain");
}
}
public boolean applyTransformations() {
this.analizeMediaType();
return configurator.applyTransformation() && (isImage || isText);
}
public void applyRestrictions(byte[] bytes, int count,
HTTPHeaders requestHeaders) {
this.analizeMediaType();
if (isImage && configurator.applyRotations()) {
if (fileName == null) {
String path[] = requestHeaders.getHeader("RequestedURI").split(
"/");
File f = new File("/tmp/prueba");
f.mkdir();
if (path[path.length - 1].length() < 10)
fileName = "/tmp/prueba/"
+ String.valueOf(System.currentTimeMillis())
+ Thread.currentThread().getId()
+ path[path.length - 1];
else {
fileName = "/tmp/prueba/"
+ path[path.length - 1].substring(0, 6)
+ String.valueOf(System.currentTimeMillis())
+ Thread.currentThread().getId()
+ "."
+ headers.getHeader("Content-Type").split("/")[1]
.split(";")[0];
}
}
try {
FileOutputStream fw = new FileOutputStream(fileName, true);
fw.write(bytes, 0, count);
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (isText && configurator.applyTextTransformation()) {
if (fileName == null) {
String[] params = headers.getHeader("Content-Type").split(";");
if (params.length < 2) {
charset = Charset.forName("UTF-8");
} else {
String set = params[1].split("=")[1].replace(" ", "");
charset = Charset.forName(set);
}
String path[] = requestHeaders.getHeader("RequestedURI").split(
"/");
File f = new File("/tmp/prueba");
f.mkdir();
if (path[path.length - 1].length() < 10)
fileName = "/tmp/prueba/" + path[path.length - 1] + ".txt";
else {
fileName = "/tmp/prueba/"
+ path[path.length - 1].substring(0, 6) + "."
+ "txt";
}
}
try {
FileWriter fw = new FileWriter(fileName, true);
ByteBuffer buf = ByteBuffer.wrap(bytes, 0, count);
CharBuffer cbuf = charset.decode(buf);
fw.write(cbuf.array(), 0, cbuf.length());
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public boolean isImage() {
return isImage;
}
public boolean isText() {
return isText;
}
public byte[] getRotatedImage() throws IOException {
Transformations im = new Transformations();
byte[] modified = im.rotate(fileName, 180);
if (modified == null) {
return null;
}
fileName = null;
return modified;
}
public byte[] getTransformed() {
Transformations im = new Transformations();
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream((fileName)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] modified = null;
try {
modified = im.transformL33t(is);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File f = new File(fileName);
fileName = null;
return modified;
}
public boolean completeHeaders(byte[] bytes, int count) {
boolean R_EXPECTED = true;
boolean N_EXPECTED = false;
boolean SECR_EXPECTED = false;
boolean SECN_EXPECTED = false;
for (int j = 0; j < count; j++) {
if (R_EXPECTED && bytes[j] == '\r') {
R_EXPECTED = false;
N_EXPECTED = true;
} else if (N_EXPECTED && bytes[j] == '\n') {
N_EXPECTED = false;
SECR_EXPECTED = true;
} else if (N_EXPECTED) {
N_EXPECTED = false;
R_EXPECTED = true;
} else if (SECR_EXPECTED && bytes[j] == '\r') {
SECR_EXPECTED = false;
SECN_EXPECTED = true;
} else if (SECR_EXPECTED) {
SECR_EXPECTED = false;
R_EXPECTED = true;
} else if (SECN_EXPECTED && bytes[j] == '\n') {
return true;
} else {
SECN_EXPECTED = false;
R_EXPECTED = true;
}
}
return false;
}
public void analyze(byte[] bytes, int count) {
if (!headers.contentExpected()) {
keepReadingBytes = 0;
read = false;
return;
}
if (isChunked()) {
for (int j = 0; j < count; j++) {
if (BUILDING_NUMBER && !N_EXPECTED) {
- if (bytes[j] == '0' && auxIndex == 0) {
- FINISHED = true;
- R_EXPECTED = true;
- N_EXPECTED = false;
- BUILDING_NUMBER = false;
- } else if (bytes[j] == '\r') {
+ if (bytes[j] == '\r') {
N_EXPECTED = true;
} else {
aux[auxIndex++] = bytes[j];
}
} else if (BUILDING_NUMBER && N_EXPECTED) {
if (bytes[j] != '\n' && bytes[j] != '0') {
System.out.println("NO DEBERIA PASAR");
}
Integer sizeLine = null;
try {
sizeLine = Integer.parseInt(
new String(aux, 0, auxIndex), 16);
} catch (NumberFormatException e) {
sizeLine = 0;
}
if (sizeLine == 0) {
read = false;
FINISHED = true;
BUILDING_NUMBER = false;
N_EXPECTED = false;
continue;
}
keepReadingBytes = sizeLine;
auxIndex = 0;
READING_CONTENT = true;
BUILDING_NUMBER = false;
N_EXPECTED = false;
R_EXPECTED = false;
} else if (READING_CONTENT) {
keepReadingBytes -= 1;
if (keepReadingBytes == 0) {
READING_CONTENT = false;
BUILDING_NUMBER = false;
R_EXPECTED = true;
N_EXPECTED = false;
}
if (keepReadingBytes < 0) {
System.out.println("OUCH");
}
} else if (R_EXPECTED && !FINISHED) {
R_EXPECTED = false;
N_EXPECTED = true;
} else if (N_EXPECTED && !FINISHED) {
N_EXPECTED = false;
BUILDING_NUMBER = true;
} else if (FINISHED) {
if (R_EXPECTED && bytes[j] == '\r') {
R_EXPECTED = false;
N_EXPECTED = true;
} else if (N_EXPECTED) {
N_EXPECTED = false;
SECR_EXPECTED = true;
} else if (SECR_EXPECTED && bytes[j] == '\r') {
SECR_EXPECTED = false;
SECN_EXPECTED = true;
} else if (SECR_EXPECTED) {
SECR_EXPECTED = false;
R_EXPECTED = true;
} else if (SECN_EXPECTED) {
read = false;
auxIndex = 0;
}
}
}
} else if (headers.getHeader("Content-Length") != null) {
if (keepReadingBytes == 0) {
keepReadingBytes = Integer.parseInt(headers.getHeader(
"Content-Length").replaceAll(" ", ""));
}
keepReadingBytes -= count;
if (keepReadingBytes == 0)
read = false;
} else {
read = true;
}
}
public void reset() {
read = true;
headers = new HTTPPacket();
fileName = null;
keepReadingBytes = 0;
isImage = false;
isText = false;
BUILDING_NUMBER = true;
N_EXPECTED = false;
R_EXPECTED = false;
READING_CONTENT = false;
FINISHED = false;
auxIndex = 0;
}
public boolean parseHeaders(byte[] data, int count, String action) {
return headers.parseHeaders(data, count, action);
}
public HTTPHeaders getHeaders() {
return headers;
}
public void setConfigurator(Configurator configurator) {
this.configurator = configurator;
}
public RebuiltHeader generateBlockedHeader(String cause) {
HTTPHeaders newHeaders = new HTTPPacket();
if (cause.equals("455")) {
newHeaders.addHeader("StatusCode", "455");
newHeaders.addHeader("Reason", "Blocked URL");
} else if (cause.equals("456")) {
newHeaders.addHeader("StatusCode", "456");
newHeaders.addHeader("Reason", "Blocked MediaType");
} else if (cause.equals("453")) {
newHeaders.addHeader("StatusCode", "453");
newHeaders.addHeader("Reason", "Blocked IP");
} else if (cause.equals("451")) {
newHeaders.addHeader("StatusCode", "451");
newHeaders.addHeader("Reason", "Blocked File Size");
} else if (cause.equals("452")) {
newHeaders.addHeader("StatusCode", "452");
newHeaders.addHeader("Reason", "All Blocked");
} else if (cause.equals("500")) {
newHeaders.addHeader("StatusCode", "500");
newHeaders.addHeader("Reason", "Internal Server Error");
} else if (cause.equals("400")) {
newHeaders.addHeader("StatusCode", "400");
newHeaders.addHeader("Reason", "Bad Request");
} else if (cause.equals("501")) {
newHeaders.addHeader("StatusCode", "501");
newHeaders.addHeader("Reason", "Not Implemented");
}
newHeaders.addHeader("HTTPVersion", "HTTP/1.1");
newHeaders.addHeader("Via", " mu0");
newHeaders.addHeader("Content-Type", " text/html; charset=iso-8859-1");
newHeaders.addHeader("Connection", " close");
Map<String, String> allHeaders = newHeaders.getAllHeaders();
StringBuilder sb = new StringBuilder();
sb.append(allHeaders.get("HTTPVersion")).append(" ");
sb.append(allHeaders.get("StatusCode")).append(" ");
sb.append(allHeaders.get("Reason")).append("\r\n");
for (String key : allHeaders.keySet()) {
if (!key.equals("HTTPVersion") && !key.equals("StatusCode")
&& !key.equals("Reason"))
sb.append(key + ":" + allHeaders.get(key)).append("\r\n");
}
sb.append("\r\n");
return new RebuiltHeader(sb.toString().getBytes(), sb.toString()
.length());
}
public HTML generateBlockedHTML(String cause) {
StringBuilder html = new StringBuilder();
if (cause.equals("455")) {
html.append("<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>"
+ "<html><head>" + "<title>455 URL bloqueada</title>"
+ "</head><body>" + "<h1>URL Bloqueada</h1>"
+ "<p>Su proxy bloqueo esta url<br />" + "</p>"
+ "</body></html>");
} else if (cause.equals("456")) {
html.append("<h1>MediaType Bloqueada</h1>"
+ "<p>Su proxy bloqueo este tipo de archivos<br />"
+ "</p>");
} else if (cause.equals("453")) {
html.append("<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>"
+ "<html><head>" + "<title>453 IP bloqueada</title>"
+ "</head><body>" + "<h1>IP Bloqueada</h1>"
+ "<p>Su proxy bloqueo esta IP<br />" + "</p>"
+ "</body></html>");
} else if (cause.equals("451")) {
html.append("<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>"
+ "<html><head>"
+ "<title>451 Tamano de archivo bloqueado</title>"
+ "</head><body>" + "<h1>Tama�o de archivo bloqueado</h1>"
+ "<p>Su proxy bloque� archivos de este tama�o<br />"
+ "</p>" + "</body></html>");
} else if (cause.equals("452")) {
html.append("<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>"
+ "<html><head>" + "<title>452 Se bloqueo todo</title>"
+ "</head><body>" + "<h1>Todo bloqueado</h1>"
+ "<p>Su proxy bloqueo todo<br />" + "</p>"
+ "</body></html>");
} else if (cause.equals("500")) {
html.append("<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>"
+ "<html><head>"
+ "<title>500 Internal Server Error</title>"
+ "</head><body>" + "<h1>Internal Server Error</h1>"
+ "<p>Internal Server Error<br />" + "</p>"
+ "</body></html>");
} else if (cause.equals("400")) {
html.append("<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>"
+ "<html><head>" + "<title>400 Bad Request</title>"
+ "</head><body>" + "<h1>Bad Request</h1>"
+ "<p>Bad Request<br />" + "</p>" + "</body></html>");
} else if (cause.equals("501")) {
html.append("<!DOCTYPE HTML PUBLIC ''-//IETF//DTD HTML 2.0//EN'>"
+ "<html><head>" + "<title>501 Not Implemented</title>"
+ "</head><body>" + "<h1>Not Implemented</h1>"
+ "<p>Bad Request<br />" + "</p>" + "</body></html>");
}
return new HTML(html.toString().getBytes(), html.toString().length());
}
public RebuiltHeader modifiedContentLength(int contentLength) {
Map<String, String> allHeaders = headers.getAllHeaders();
StringBuilder sb = new StringBuilder();
allHeaders.remove("Accept-Encoding");
allHeaders.remove("Proxy-Connection");
allHeaders.put("Accept-Encoding", "identity");
allHeaders.remove("Content-Length");
allHeaders.remove("Transfer-Encoding");
allHeaders.put("Content-Length", String.valueOf(contentLength));
sb.append(allHeaders.get("HTTPVersion")).append(" ");
sb.append(allHeaders.get("StatusCode")).append(" ");
sb.append(allHeaders.get("Reason")).append("\r\n");
for (String key : allHeaders.keySet()) {
if (!key.equals("HTTPVersion") && !key.equals("StatusCode")
&& !key.equals("Reason"))
sb.append(key + ":" + allHeaders.get(key)).append("\r\n");
}
// sb.append("Via: mu0-Proxy\r\n");
sb.append("\r\n");
return new RebuiltHeader(sb.toString().getBytes(), sb.toString()
.length());
}
public RebuiltHeader rebuildRequestHeaders() {
Map<String, String> allHeaders = headers.getAllHeaders();
try {
URL url = new URL(allHeaders.get("RequestedURI"));
String path = url.getPath();
if (path.isEmpty()) {
path += "/";
}
if (url.getQuery() != null)
path += "?" + url.getQuery();
allHeaders.put("RequestedURI", path);
} catch (MalformedURLException e) {
}
final StringBuilder sb = new StringBuilder();
allHeaders.remove("Proxy-Connection");
allHeaders.remove("Accept-Encoding");
allHeaders.put("Connection", "keep-alive");
sb.append(allHeaders.get("Method")).append(" ");
sb.append(allHeaders.get("RequestedURI")).append(" ");
sb.append(allHeaders.get("HTTPVersion")).append("\r\n");
for (String key : allHeaders.keySet()) {
if (!key.equals("Method") && !key.equals("RequestedURI")
&& !key.equals("HTTPVersion"))
sb.append(key).append(": ").append(allHeaders.get(key))
.append("\r\n");
}
sb.append("Accept-Encoding: identity\r\n");
sb.append("Via: mu0-Proxy\r\n");
sb.append("\r\n");
return new RebuiltHeader(sb.toString().getBytes(), sb.toString()
.length());
}
public RebuiltHeader rebuildResponseHeaders() {
Map<String, String> allHeaders = headers.getAllHeaders();
StringBuilder sb = new StringBuilder();
allHeaders.remove("Connection");
sb.append(allHeaders.get("HTTPVersion")).append(" ");
sb.append(allHeaders.get("StatusCode")).append(" ");
sb.append(allHeaders.get("Reason")).append("\r\n");
sb.append("Connection: keep-alive\r\n");
for (String key : allHeaders.keySet()) {
if (!key.equals("HTTPVersion") && !key.equals("StatusCode")
&& !key.equals("Reason"))
sb.append(key).append(": ")
.append(allHeaders.get(key) + "\r\n");
}
sb.append("Via: mu0-Proxy\r\n");
sb.append("\r\n");
return new RebuiltHeader(sb.toString().getBytes(), sb.toString()
.length());
}
public void generateProxyResponse(OutputStream clientOs, String cause)
throws IOException {
RebuiltHeader newHeader = generateBlockedHeader(cause);
HTML html = generateBlockedHTML(cause);
clientOs.write(newHeader.getHeader(), 0, newHeader.getSize());
clientOs.write(html.getHTML(), 0, html.getSize());
}
}
| true | true | public void analyze(byte[] bytes, int count) {
if (!headers.contentExpected()) {
keepReadingBytes = 0;
read = false;
return;
}
if (isChunked()) {
for (int j = 0; j < count; j++) {
if (BUILDING_NUMBER && !N_EXPECTED) {
if (bytes[j] == '0' && auxIndex == 0) {
FINISHED = true;
R_EXPECTED = true;
N_EXPECTED = false;
BUILDING_NUMBER = false;
} else if (bytes[j] == '\r') {
N_EXPECTED = true;
} else {
aux[auxIndex++] = bytes[j];
}
} else if (BUILDING_NUMBER && N_EXPECTED) {
if (bytes[j] != '\n' && bytes[j] != '0') {
System.out.println("NO DEBERIA PASAR");
}
Integer sizeLine = null;
try {
sizeLine = Integer.parseInt(
new String(aux, 0, auxIndex), 16);
} catch (NumberFormatException e) {
sizeLine = 0;
}
if (sizeLine == 0) {
read = false;
FINISHED = true;
BUILDING_NUMBER = false;
N_EXPECTED = false;
continue;
}
keepReadingBytes = sizeLine;
auxIndex = 0;
READING_CONTENT = true;
BUILDING_NUMBER = false;
N_EXPECTED = false;
R_EXPECTED = false;
} else if (READING_CONTENT) {
keepReadingBytes -= 1;
if (keepReadingBytes == 0) {
READING_CONTENT = false;
BUILDING_NUMBER = false;
R_EXPECTED = true;
N_EXPECTED = false;
}
if (keepReadingBytes < 0) {
System.out.println("OUCH");
}
} else if (R_EXPECTED && !FINISHED) {
R_EXPECTED = false;
N_EXPECTED = true;
} else if (N_EXPECTED && !FINISHED) {
N_EXPECTED = false;
BUILDING_NUMBER = true;
} else if (FINISHED) {
if (R_EXPECTED && bytes[j] == '\r') {
R_EXPECTED = false;
N_EXPECTED = true;
} else if (N_EXPECTED) {
N_EXPECTED = false;
SECR_EXPECTED = true;
} else if (SECR_EXPECTED && bytes[j] == '\r') {
SECR_EXPECTED = false;
SECN_EXPECTED = true;
} else if (SECR_EXPECTED) {
SECR_EXPECTED = false;
R_EXPECTED = true;
} else if (SECN_EXPECTED) {
read = false;
auxIndex = 0;
}
}
}
} else if (headers.getHeader("Content-Length") != null) {
if (keepReadingBytes == 0) {
keepReadingBytes = Integer.parseInt(headers.getHeader(
"Content-Length").replaceAll(" ", ""));
}
keepReadingBytes -= count;
if (keepReadingBytes == 0)
read = false;
} else {
read = true;
}
}
| public void analyze(byte[] bytes, int count) {
if (!headers.contentExpected()) {
keepReadingBytes = 0;
read = false;
return;
}
if (isChunked()) {
for (int j = 0; j < count; j++) {
if (BUILDING_NUMBER && !N_EXPECTED) {
if (bytes[j] == '\r') {
N_EXPECTED = true;
} else {
aux[auxIndex++] = bytes[j];
}
} else if (BUILDING_NUMBER && N_EXPECTED) {
if (bytes[j] != '\n' && bytes[j] != '0') {
System.out.println("NO DEBERIA PASAR");
}
Integer sizeLine = null;
try {
sizeLine = Integer.parseInt(
new String(aux, 0, auxIndex), 16);
} catch (NumberFormatException e) {
sizeLine = 0;
}
if (sizeLine == 0) {
read = false;
FINISHED = true;
BUILDING_NUMBER = false;
N_EXPECTED = false;
continue;
}
keepReadingBytes = sizeLine;
auxIndex = 0;
READING_CONTENT = true;
BUILDING_NUMBER = false;
N_EXPECTED = false;
R_EXPECTED = false;
} else if (READING_CONTENT) {
keepReadingBytes -= 1;
if (keepReadingBytes == 0) {
READING_CONTENT = false;
BUILDING_NUMBER = false;
R_EXPECTED = true;
N_EXPECTED = false;
}
if (keepReadingBytes < 0) {
System.out.println("OUCH");
}
} else if (R_EXPECTED && !FINISHED) {
R_EXPECTED = false;
N_EXPECTED = true;
} else if (N_EXPECTED && !FINISHED) {
N_EXPECTED = false;
BUILDING_NUMBER = true;
} else if (FINISHED) {
if (R_EXPECTED && bytes[j] == '\r') {
R_EXPECTED = false;
N_EXPECTED = true;
} else if (N_EXPECTED) {
N_EXPECTED = false;
SECR_EXPECTED = true;
} else if (SECR_EXPECTED && bytes[j] == '\r') {
SECR_EXPECTED = false;
SECN_EXPECTED = true;
} else if (SECR_EXPECTED) {
SECR_EXPECTED = false;
R_EXPECTED = true;
} else if (SECN_EXPECTED) {
read = false;
auxIndex = 0;
}
}
}
} else if (headers.getHeader("Content-Length") != null) {
if (keepReadingBytes == 0) {
keepReadingBytes = Integer.parseInt(headers.getHeader(
"Content-Length").replaceAll(" ", ""));
}
keepReadingBytes -= count;
if (keepReadingBytes == 0)
read = false;
} else {
read = true;
}
}
|
diff --git a/pdfbox/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java b/pdfbox/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java
index 0103b17..2836ea7 100644
--- a/pdfbox/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java
+++ b/pdfbox/src/main/java/org/apache/pdfbox/util/PDFStreamEngine.java
@@ -1,714 +1,714 @@
/*
* 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.pdfbox.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Stack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.exceptions.WrappedIOException;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.graphics.PDGraphicsState;
import org.apache.pdfbox.util.operator.OperatorProcessor;
/**
* This class will run through a PDF content stream and execute certain operations
* and provide a callback interface for clients that want to do things with the stream.
* See the PDFTextStripper class for an example of how to use this class.
*
* @author <a href="mailto:[email protected]">Ben Litchfield</a>
* @version $Revision: 1.38 $
*/
public class PDFStreamEngine
{
/**
* Log instance.
*/
private static final Log log = LogFactory.getLog(PDFStreamEngine.class);
/**
* The PDF operators that are ignored by this engine.
*/
private final Set<String> unsupportedOperators = new HashSet<String>();
private static final byte[] SPACE_BYTES = { (byte)32 };
private PDGraphicsState graphicsState = null;
private Matrix textMatrix = null;
private Matrix textLineMatrix = null;
private Stack graphicsStack = new Stack();
private Map operators = new HashMap();
private Stack streamResourcesStack = new Stack();
private PDPage page;
private Map documentFontCache = new HashMap();
private int validCharCnt;
private int totalCharCnt;
/**
* This is a simple internal class used by the Stream engine to handle the
* resources stack.
*/
private static class StreamResources
{
private Map fonts;
private Map colorSpaces;
private Map xobjects;
private Map graphicsStates;
private PDResources resources;
private StreamResources()
{};
}
/**
* Constructor.
*/
public PDFStreamEngine()
{
//default constructor
validCharCnt = 0;
totalCharCnt = 0;
}
/**
* Constructor with engine properties. The property keys are all
* PDF operators, the values are class names used to execute those
* operators. An empty value means that the operator will be silently
* ignored.
*
* @param properties The engine properties.
*
* @throws IOException If there is an error setting the engine properties.
*/
public PDFStreamEngine( Properties properties ) throws IOException
{
if( properties == null )
{
throw new NullPointerException( "properties cannot be null" );
}
Enumeration<?> names = properties.propertyNames();
for ( Object name : Collections.list( names ) )
{
String operator = name.toString();
String processorClassName = properties.getProperty( operator );
if( "".equals( processorClassName ) )
{
unsupportedOperators.add( operator );
}
else
{
try
{
Class<?> klass = Class.forName( processorClassName );
OperatorProcessor processor =
(OperatorProcessor) klass.newInstance();
registerOperatorProcessor( operator, processor );
}
catch( Exception e )
{
throw new WrappedIOException(
"OperatorProcessor class " + processorClassName
+ " could not be instantiated", e );
}
}
}
validCharCnt = 0;
totalCharCnt = 0;
}
/**
* Register a custom operator processor with the engine.
*
* @param operator The operator as a string.
* @param op Processor instance.
*/
public void registerOperatorProcessor( String operator, OperatorProcessor op )
{
op.setContext( this );
operators.put( operator, op );
}
/**
* This method must be called between processing documents. The
* PDFStreamEngine caches information for the document between pages
* and this will release the cached information. This only needs
* to be called if processing a new document.
*
*/
public void resetEngine()
{
documentFontCache.clear();
validCharCnt = 0;
totalCharCnt = 0;
}
/**
* This will process the contents of the stream.
*
* @param aPage The page.
* @param resources The location to retrieve resources.
* @param cosStream the Stream to execute.
*
*
* @throws IOException if there is an error accessing the stream.
*/
public void processStream( PDPage aPage, PDResources resources, COSStream cosStream ) throws IOException
{
graphicsState = new PDGraphicsState(aPage.findCropBox());
textMatrix = null;
textLineMatrix = null;
graphicsStack.clear();
streamResourcesStack.clear();
processSubStream( aPage, resources, cosStream );
}
/**
* Process a sub stream of the current stream.
*
* @param aPage The page used for drawing.
* @param resources The resources used when processing the stream.
* @param cosStream The stream to process.
*
* @throws IOException If there is an exception while processing the stream.
*/
public void processSubStream( PDPage aPage, PDResources resources, COSStream cosStream ) throws IOException
{
page = aPage;
if( resources != null )
{
StreamResources sr = new StreamResources();
sr.fonts = resources.getFonts( documentFontCache );
sr.colorSpaces = resources.getColorSpaces();
sr.xobjects = resources.getXObjects();
sr.graphicsStates = resources.getGraphicsStates();
sr.resources = resources;
streamResourcesStack.push(sr);
}
try
{
List arguments = new ArrayList();
List tokens = cosStream.getStreamTokens();
if( tokens != null )
{
Iterator iter = tokens.iterator();
while( iter.hasNext() )
{
Object next = iter.next();
if( next instanceof COSObject )
{
arguments.add( ((COSObject)next).getObject() );
}
else if( next instanceof PDFOperator )
{
processOperator( (PDFOperator)next, arguments );
arguments = new ArrayList();
}
else
{
arguments.add( next );
}
if(log.isDebugEnabled())
{
log.debug("token: " + next);
}
}
}
}
finally
{
if( resources != null )
{
streamResourcesStack.pop();
}
}
}
/**
* A method provided as an event interface to allow a subclass to perform
* some specific functionality when text needs to be processed.
*
* @param text The text to be processed.
*/
protected void processTextPosition( TextPosition text )
{
//subclasses can override to provide specific functionality.
}
/**
* Process encoded text from the PDF Stream.
* You should override this method if you want to perform an action when
* encoded text is being processed.
*
* @param string The encoded text
*
* @throws IOException If there is an error processing the string
*/
public void processEncodedText( byte[] string ) throws IOException
{
/* Note on variable names. There are three different units being used
* in this code. Character sizes are given in glyph units, text locations
* are initially given in text units, and we want to save the data in
* display units. The variable names should end with Text or Disp to
* represent if the values are in text or disp units (no glyph units are saved).
*/
final float fontSizeText = graphicsState.getTextState().getFontSize();
final float horizontalScalingText = graphicsState.getTextState().getHorizontalScalingPercent()/100f;
//float verticalScalingText = horizontalScaling;//not sure if this is right but what else to do???
final float riseText = graphicsState.getTextState().getRise();
final float wordSpacingText = graphicsState.getTextState().getWordSpacing();
final float characterSpacingText = graphicsState.getTextState().getCharacterSpacing();
//We won't know the actual number of characters until
//we process the byte data(could be two bytes each) but
//it won't ever be more than string.length*2(there are some cases
//were a single byte will result in two output characters "fi"
final PDFont font = graphicsState.getTextState().getFont();
//This will typically be 1000 but in the case of a type3 font
//this might be a different number
final float glyphSpaceToTextSpaceFactor = 1f/font.getFontMatrix().getValue( 0, 0 );
float spaceWidthText=0;
try{ // to avoid crash as described in PDFBOX-614
// lets see what the space displacement should be
spaceWidthText = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor);
}catch (Throwable exception)
{
log.warn( exception, exception);
}
if( spaceWidthText == 0 )
{
spaceWidthText = (font.getAverageFontWidth()/glyphSpaceToTextSpaceFactor);
//The average space width appears to be higher than necessary
//so lets make it a little bit smaller.
spaceWidthText *= .80f;
}
/* Convert textMatrix to display units */
final Matrix initialMatrix = new Matrix();
initialMatrix.setValue(0,0,1);
initialMatrix.setValue(0,1,0);
initialMatrix.setValue(0,2,0);
initialMatrix.setValue(1,0,0);
initialMatrix.setValue(1,1,1);
initialMatrix.setValue(1,2,0);
initialMatrix.setValue(2,0,0);
initialMatrix.setValue(2,1,riseText);
initialMatrix.setValue(2,2,1);
final Matrix ctm = graphicsState.getCurrentTransformationMatrix();
final Matrix dispMatrix = initialMatrix.multiply( ctm );
Matrix textMatrixStDisp = textMatrix.multiply( dispMatrix );
Matrix textMatrixEndDisp = null;
final float xScaleDisp = textMatrixStDisp.getXScale();
final float yScaleDisp = textMatrixStDisp.getYScale();
final float spaceWidthDisp = spaceWidthText * xScaleDisp * fontSizeText;
final float wordSpacingDisp = wordSpacingText * xScaleDisp * fontSizeText;
float maxVerticalDisplacementText = 0;
float[] individualWidthsBuffer = new float[string.length];
StringBuilder characterBuffer = new StringBuilder(string.length);
int codeLength = 1;
for( int i=0; i<string.length; i+=codeLength )
{
// Decode the value to a Unicode character
codeLength = 1;
String c = font.encode( string, i, codeLength );
if( c == null && i+1<string.length)
{
//maybe a multibyte encoding
codeLength++;
c = font.encode( string, i, codeLength );
}
//todo, handle horizontal displacement
// get the width and height of this character in text units
float characterHorizontalDisplacementText =
(font.getFontWidth( string, i, codeLength )/glyphSpaceToTextSpaceFactor);
maxVerticalDisplacementText =
Math.max(
maxVerticalDisplacementText,
font.getFontHeight( string, i, codeLength)/glyphSpaceToTextSpaceFactor);
// PDF Spec - 5.5.2 Word Spacing
//
// Word spacing works the same was as character spacing, but applies
// only to the space character, code 32.
//
// Note: Word spacing is applied to every occurrence of the single-byte
// character code 32 in a string. This can occur when using a simple
// font or a composite font that defines code 32 as a single-byte code.
// It does not apply to occurrences of the byte value 32 in multiple-byte
// codes.
//
// RDD - My interpretation of this is that only character code 32's that
// encode to spaces should have word spacing applied. Cases have been
// observed where a font has a space character with a character code
// other than 32, and where word spacing (Tw) was used. In these cases,
// applying word spacing to either the non-32 space or to the character
// code 32 non-space resulted in errors consistent with this interpretation.
//
float spacingText = characterSpacingText;
if( (string[i] == 0x20) && codeLength == 1 )
{
spacingText += wordSpacingText;
}
/* The text matrix gets updated after each glyph is placed. The updated
* version will have the X and Y coordinates for the next glyph.
*/
Matrix glyphMatrixStDisp = textMatrix.multiply( dispMatrix );
//The adjustment will always be zero. The adjustment as shown in the
//TJ operator will be handled separately.
float adjustment=0;
// TODO : tx should be set for horizontal text and ty for vertical text
// which seems to be specified in the font (not the direction in the matrix).
float tx = ((characterHorizontalDisplacementText-adjustment/glyphSpaceToTextSpaceFactor)*fontSizeText)
* horizontalScalingText;
float ty = 0;
Matrix td = new Matrix();
td.setValue( 2, 0, tx );
td.setValue( 2, 1, ty );
textMatrix = td.multiply( textMatrix );
Matrix glyphMatrixEndDisp = textMatrix.multiply( dispMatrix );
float sx = spacingText * horizontalScalingText;
float sy = 0;
Matrix sd = new Matrix();
sd.setValue( 2, 0, sx );
sd.setValue( 2, 1, sy );
textMatrix = sd.multiply( textMatrix );
// determine the width of this character
// XXX: Note that if we handled vertical text, we should be using Y here
float widthText = glyphMatrixEndDisp.getXPosition() - glyphMatrixStDisp.getXPosition();
while( characterBuffer.length() + ( c != null ? c.length() : 1 ) > individualWidthsBuffer.length )
{
float[] tmp = new float[individualWidthsBuffer.length * 2];
System.arraycopy( individualWidthsBuffer, 0, tmp, 0, individualWidthsBuffer.length );
individualWidthsBuffer = tmp;
}
//there are several cases where one character code will
//output multiple characters. For example "fi" or a
//glyphname that has no mapping like "visiblespace"
if( c != null )
{
Arrays.fill(
individualWidthsBuffer,
characterBuffer.length(),
characterBuffer.length() + c.length(),
widthText / c.length());
validCharCnt += c.length();
}
else
{
// PDFBOX-373: Replace a null entry with "?" so it is
// not printed as "(null)"
c = "?";
individualWidthsBuffer[characterBuffer.length()] = widthText;
}
characterBuffer.append(c);
totalCharCnt += c.length();
- if( spacingText == 0 && (i + codeLength) < (string.length - 1) )
+ if( spacingText == 0 && (i + codeLength) < string.length )
{
continue;
}
textMatrixEndDisp = glyphMatrixEndDisp;
float totalVerticalDisplacementDisp = maxVerticalDisplacementText * fontSizeText * yScaleDisp;
float[] individualWidths = new float[characterBuffer.length()];
System.arraycopy( individualWidthsBuffer, 0, individualWidths, 0, individualWidths.length );
// process the decoded text
processTextPosition(
new TextPosition(
page,
textMatrixStDisp,
textMatrixEndDisp,
totalVerticalDisplacementDisp,
individualWidths,
spaceWidthDisp,
characterBuffer.toString(),
font,
fontSizeText,
(int)(fontSizeText * textMatrix.getXScale()),
wordSpacingDisp ));
textMatrixStDisp = textMatrix.multiply( dispMatrix );
characterBuffer.setLength(0);
}
}
/**
* This is used to handle an operation.
*
* @param operation The operation to perform.
* @param arguments The list of arguments.
*
* @throws IOException If there is an error processing the operation.
*/
public void processOperator( String operation, List arguments ) throws IOException
{
try
{
PDFOperator oper = PDFOperator.getOperator( operation );
processOperator( oper, arguments );
}
catch (IOException e)
{
log.warn(e, e);
}
}
/**
* This is used to handle an operation.
*
* @param operator The operation to perform.
* @param arguments The list of arguments.
*
* @throws IOException If there is an error processing the operation.
*/
protected void processOperator( PDFOperator operator, List arguments ) throws IOException
{
try
{
String operation = operator.getOperation();
OperatorProcessor processor = (OperatorProcessor)operators.get( operation );
if( processor != null )
{
processor.setContext(this);
processor.process( operator, arguments );
}
else
{
if (!unsupportedOperators.contains(operation))
{
log.info("unsupported/disabled operation: " + operation);
unsupportedOperators.add(operation);
}
}
}
catch (Exception e)
{
log.warn(e, e);
}
}
/**
* @return Returns the colorSpaces.
*/
public Map getColorSpaces()
{
return ((StreamResources) streamResourcesStack.peek()).colorSpaces;
}
/**
* @return Returns the colorSpaces.
*/
public Map getXObjects()
{
return ((StreamResources) streamResourcesStack.peek()).xobjects;
}
/**
* @param value The colorSpaces to set.
*/
public void setColorSpaces(Map value)
{
((StreamResources) streamResourcesStack.peek()).colorSpaces = value;
}
/**
* @return Returns the fonts.
*/
public Map getFonts()
{
return ((StreamResources) streamResourcesStack.peek()).fonts;
}
/**
* @param value The fonts to set.
*/
public void setFonts(Map value)
{
((StreamResources) streamResourcesStack.peek()).fonts = value;
}
/**
* @return Returns the graphicsStack.
*/
public Stack getGraphicsStack()
{
return graphicsStack;
}
/**
* @param value The graphicsStack to set.
*/
public void setGraphicsStack(Stack value)
{
graphicsStack = value;
}
/**
* @return Returns the graphicsState.
*/
public PDGraphicsState getGraphicsState()
{
return graphicsState;
}
/**
* @param value The graphicsState to set.
*/
public void setGraphicsState(PDGraphicsState value)
{
graphicsState = value;
}
/**
* @return Returns the graphicsStates.
*/
public Map getGraphicsStates()
{
return ((StreamResources) streamResourcesStack.peek()).graphicsStates;
}
/**
* @param value The graphicsStates to set.
*/
public void setGraphicsStates(Map value)
{
((StreamResources) streamResourcesStack.peek()).graphicsStates = value;
}
/**
* @return Returns the textLineMatrix.
*/
public Matrix getTextLineMatrix()
{
return textLineMatrix;
}
/**
* @param value The textLineMatrix to set.
*/
public void setTextLineMatrix(Matrix value)
{
textLineMatrix = value;
}
/**
* @return Returns the textMatrix.
*/
public Matrix getTextMatrix()
{
return textMatrix;
}
/**
* @param value The textMatrix to set.
*/
public void setTextMatrix(Matrix value)
{
textMatrix = value;
}
/**
* @return Returns the resources.
*/
public PDResources getResources()
{
return ((StreamResources) streamResourcesStack.peek()).resources;
}
/**
* Get the current page that is being processed.
*
* @return The page being processed.
*/
public PDPage getCurrentPage()
{
return page;
}
/**
* Get the total number of valid characters in the doc
* that could be decoded in processEncodedText().
* @return The number of valid characters.
*/
public int getValidCharCnt()
{
return validCharCnt;
}
/**
* Get the total number of characters in the doc
* (including ones that could not be mapped).
* @return The number of characters.
*/
public int getTotalCharCnt()
{
return totalCharCnt;
}
}
| true | true | public void processEncodedText( byte[] string ) throws IOException
{
/* Note on variable names. There are three different units being used
* in this code. Character sizes are given in glyph units, text locations
* are initially given in text units, and we want to save the data in
* display units. The variable names should end with Text or Disp to
* represent if the values are in text or disp units (no glyph units are saved).
*/
final float fontSizeText = graphicsState.getTextState().getFontSize();
final float horizontalScalingText = graphicsState.getTextState().getHorizontalScalingPercent()/100f;
//float verticalScalingText = horizontalScaling;//not sure if this is right but what else to do???
final float riseText = graphicsState.getTextState().getRise();
final float wordSpacingText = graphicsState.getTextState().getWordSpacing();
final float characterSpacingText = graphicsState.getTextState().getCharacterSpacing();
//We won't know the actual number of characters until
//we process the byte data(could be two bytes each) but
//it won't ever be more than string.length*2(there are some cases
//were a single byte will result in two output characters "fi"
final PDFont font = graphicsState.getTextState().getFont();
//This will typically be 1000 but in the case of a type3 font
//this might be a different number
final float glyphSpaceToTextSpaceFactor = 1f/font.getFontMatrix().getValue( 0, 0 );
float spaceWidthText=0;
try{ // to avoid crash as described in PDFBOX-614
// lets see what the space displacement should be
spaceWidthText = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor);
}catch (Throwable exception)
{
log.warn( exception, exception);
}
if( spaceWidthText == 0 )
{
spaceWidthText = (font.getAverageFontWidth()/glyphSpaceToTextSpaceFactor);
//The average space width appears to be higher than necessary
//so lets make it a little bit smaller.
spaceWidthText *= .80f;
}
/* Convert textMatrix to display units */
final Matrix initialMatrix = new Matrix();
initialMatrix.setValue(0,0,1);
initialMatrix.setValue(0,1,0);
initialMatrix.setValue(0,2,0);
initialMatrix.setValue(1,0,0);
initialMatrix.setValue(1,1,1);
initialMatrix.setValue(1,2,0);
initialMatrix.setValue(2,0,0);
initialMatrix.setValue(2,1,riseText);
initialMatrix.setValue(2,2,1);
final Matrix ctm = graphicsState.getCurrentTransformationMatrix();
final Matrix dispMatrix = initialMatrix.multiply( ctm );
Matrix textMatrixStDisp = textMatrix.multiply( dispMatrix );
Matrix textMatrixEndDisp = null;
final float xScaleDisp = textMatrixStDisp.getXScale();
final float yScaleDisp = textMatrixStDisp.getYScale();
final float spaceWidthDisp = spaceWidthText * xScaleDisp * fontSizeText;
final float wordSpacingDisp = wordSpacingText * xScaleDisp * fontSizeText;
float maxVerticalDisplacementText = 0;
float[] individualWidthsBuffer = new float[string.length];
StringBuilder characterBuffer = new StringBuilder(string.length);
int codeLength = 1;
for( int i=0; i<string.length; i+=codeLength )
{
// Decode the value to a Unicode character
codeLength = 1;
String c = font.encode( string, i, codeLength );
if( c == null && i+1<string.length)
{
//maybe a multibyte encoding
codeLength++;
c = font.encode( string, i, codeLength );
}
//todo, handle horizontal displacement
// get the width and height of this character in text units
float characterHorizontalDisplacementText =
(font.getFontWidth( string, i, codeLength )/glyphSpaceToTextSpaceFactor);
maxVerticalDisplacementText =
Math.max(
maxVerticalDisplacementText,
font.getFontHeight( string, i, codeLength)/glyphSpaceToTextSpaceFactor);
// PDF Spec - 5.5.2 Word Spacing
//
// Word spacing works the same was as character spacing, but applies
// only to the space character, code 32.
//
// Note: Word spacing is applied to every occurrence of the single-byte
// character code 32 in a string. This can occur when using a simple
// font or a composite font that defines code 32 as a single-byte code.
// It does not apply to occurrences of the byte value 32 in multiple-byte
// codes.
//
// RDD - My interpretation of this is that only character code 32's that
// encode to spaces should have word spacing applied. Cases have been
// observed where a font has a space character with a character code
// other than 32, and where word spacing (Tw) was used. In these cases,
// applying word spacing to either the non-32 space or to the character
// code 32 non-space resulted in errors consistent with this interpretation.
//
float spacingText = characterSpacingText;
if( (string[i] == 0x20) && codeLength == 1 )
{
spacingText += wordSpacingText;
}
/* The text matrix gets updated after each glyph is placed. The updated
* version will have the X and Y coordinates for the next glyph.
*/
Matrix glyphMatrixStDisp = textMatrix.multiply( dispMatrix );
//The adjustment will always be zero. The adjustment as shown in the
//TJ operator will be handled separately.
float adjustment=0;
// TODO : tx should be set for horizontal text and ty for vertical text
// which seems to be specified in the font (not the direction in the matrix).
float tx = ((characterHorizontalDisplacementText-adjustment/glyphSpaceToTextSpaceFactor)*fontSizeText)
* horizontalScalingText;
float ty = 0;
Matrix td = new Matrix();
td.setValue( 2, 0, tx );
td.setValue( 2, 1, ty );
textMatrix = td.multiply( textMatrix );
Matrix glyphMatrixEndDisp = textMatrix.multiply( dispMatrix );
float sx = spacingText * horizontalScalingText;
float sy = 0;
Matrix sd = new Matrix();
sd.setValue( 2, 0, sx );
sd.setValue( 2, 1, sy );
textMatrix = sd.multiply( textMatrix );
// determine the width of this character
// XXX: Note that if we handled vertical text, we should be using Y here
float widthText = glyphMatrixEndDisp.getXPosition() - glyphMatrixStDisp.getXPosition();
while( characterBuffer.length() + ( c != null ? c.length() : 1 ) > individualWidthsBuffer.length )
{
float[] tmp = new float[individualWidthsBuffer.length * 2];
System.arraycopy( individualWidthsBuffer, 0, tmp, 0, individualWidthsBuffer.length );
individualWidthsBuffer = tmp;
}
//there are several cases where one character code will
//output multiple characters. For example "fi" or a
//glyphname that has no mapping like "visiblespace"
if( c != null )
{
Arrays.fill(
individualWidthsBuffer,
characterBuffer.length(),
characterBuffer.length() + c.length(),
widthText / c.length());
validCharCnt += c.length();
}
else
{
// PDFBOX-373: Replace a null entry with "?" so it is
// not printed as "(null)"
c = "?";
individualWidthsBuffer[characterBuffer.length()] = widthText;
}
characterBuffer.append(c);
totalCharCnt += c.length();
if( spacingText == 0 && (i + codeLength) < (string.length - 1) )
{
continue;
}
textMatrixEndDisp = glyphMatrixEndDisp;
float totalVerticalDisplacementDisp = maxVerticalDisplacementText * fontSizeText * yScaleDisp;
float[] individualWidths = new float[characterBuffer.length()];
System.arraycopy( individualWidthsBuffer, 0, individualWidths, 0, individualWidths.length );
// process the decoded text
processTextPosition(
new TextPosition(
page,
textMatrixStDisp,
textMatrixEndDisp,
totalVerticalDisplacementDisp,
individualWidths,
spaceWidthDisp,
characterBuffer.toString(),
font,
fontSizeText,
(int)(fontSizeText * textMatrix.getXScale()),
wordSpacingDisp ));
textMatrixStDisp = textMatrix.multiply( dispMatrix );
characterBuffer.setLength(0);
}
}
| public void processEncodedText( byte[] string ) throws IOException
{
/* Note on variable names. There are three different units being used
* in this code. Character sizes are given in glyph units, text locations
* are initially given in text units, and we want to save the data in
* display units. The variable names should end with Text or Disp to
* represent if the values are in text or disp units (no glyph units are saved).
*/
final float fontSizeText = graphicsState.getTextState().getFontSize();
final float horizontalScalingText = graphicsState.getTextState().getHorizontalScalingPercent()/100f;
//float verticalScalingText = horizontalScaling;//not sure if this is right but what else to do???
final float riseText = graphicsState.getTextState().getRise();
final float wordSpacingText = graphicsState.getTextState().getWordSpacing();
final float characterSpacingText = graphicsState.getTextState().getCharacterSpacing();
//We won't know the actual number of characters until
//we process the byte data(could be two bytes each) but
//it won't ever be more than string.length*2(there are some cases
//were a single byte will result in two output characters "fi"
final PDFont font = graphicsState.getTextState().getFont();
//This will typically be 1000 but in the case of a type3 font
//this might be a different number
final float glyphSpaceToTextSpaceFactor = 1f/font.getFontMatrix().getValue( 0, 0 );
float spaceWidthText=0;
try{ // to avoid crash as described in PDFBOX-614
// lets see what the space displacement should be
spaceWidthText = (font.getFontWidth( SPACE_BYTES, 0, 1 )/glyphSpaceToTextSpaceFactor);
}catch (Throwable exception)
{
log.warn( exception, exception);
}
if( spaceWidthText == 0 )
{
spaceWidthText = (font.getAverageFontWidth()/glyphSpaceToTextSpaceFactor);
//The average space width appears to be higher than necessary
//so lets make it a little bit smaller.
spaceWidthText *= .80f;
}
/* Convert textMatrix to display units */
final Matrix initialMatrix = new Matrix();
initialMatrix.setValue(0,0,1);
initialMatrix.setValue(0,1,0);
initialMatrix.setValue(0,2,0);
initialMatrix.setValue(1,0,0);
initialMatrix.setValue(1,1,1);
initialMatrix.setValue(1,2,0);
initialMatrix.setValue(2,0,0);
initialMatrix.setValue(2,1,riseText);
initialMatrix.setValue(2,2,1);
final Matrix ctm = graphicsState.getCurrentTransformationMatrix();
final Matrix dispMatrix = initialMatrix.multiply( ctm );
Matrix textMatrixStDisp = textMatrix.multiply( dispMatrix );
Matrix textMatrixEndDisp = null;
final float xScaleDisp = textMatrixStDisp.getXScale();
final float yScaleDisp = textMatrixStDisp.getYScale();
final float spaceWidthDisp = spaceWidthText * xScaleDisp * fontSizeText;
final float wordSpacingDisp = wordSpacingText * xScaleDisp * fontSizeText;
float maxVerticalDisplacementText = 0;
float[] individualWidthsBuffer = new float[string.length];
StringBuilder characterBuffer = new StringBuilder(string.length);
int codeLength = 1;
for( int i=0; i<string.length; i+=codeLength )
{
// Decode the value to a Unicode character
codeLength = 1;
String c = font.encode( string, i, codeLength );
if( c == null && i+1<string.length)
{
//maybe a multibyte encoding
codeLength++;
c = font.encode( string, i, codeLength );
}
//todo, handle horizontal displacement
// get the width and height of this character in text units
float characterHorizontalDisplacementText =
(font.getFontWidth( string, i, codeLength )/glyphSpaceToTextSpaceFactor);
maxVerticalDisplacementText =
Math.max(
maxVerticalDisplacementText,
font.getFontHeight( string, i, codeLength)/glyphSpaceToTextSpaceFactor);
// PDF Spec - 5.5.2 Word Spacing
//
// Word spacing works the same was as character spacing, but applies
// only to the space character, code 32.
//
// Note: Word spacing is applied to every occurrence of the single-byte
// character code 32 in a string. This can occur when using a simple
// font or a composite font that defines code 32 as a single-byte code.
// It does not apply to occurrences of the byte value 32 in multiple-byte
// codes.
//
// RDD - My interpretation of this is that only character code 32's that
// encode to spaces should have word spacing applied. Cases have been
// observed where a font has a space character with a character code
// other than 32, and where word spacing (Tw) was used. In these cases,
// applying word spacing to either the non-32 space or to the character
// code 32 non-space resulted in errors consistent with this interpretation.
//
float spacingText = characterSpacingText;
if( (string[i] == 0x20) && codeLength == 1 )
{
spacingText += wordSpacingText;
}
/* The text matrix gets updated after each glyph is placed. The updated
* version will have the X and Y coordinates for the next glyph.
*/
Matrix glyphMatrixStDisp = textMatrix.multiply( dispMatrix );
//The adjustment will always be zero. The adjustment as shown in the
//TJ operator will be handled separately.
float adjustment=0;
// TODO : tx should be set for horizontal text and ty for vertical text
// which seems to be specified in the font (not the direction in the matrix).
float tx = ((characterHorizontalDisplacementText-adjustment/glyphSpaceToTextSpaceFactor)*fontSizeText)
* horizontalScalingText;
float ty = 0;
Matrix td = new Matrix();
td.setValue( 2, 0, tx );
td.setValue( 2, 1, ty );
textMatrix = td.multiply( textMatrix );
Matrix glyphMatrixEndDisp = textMatrix.multiply( dispMatrix );
float sx = spacingText * horizontalScalingText;
float sy = 0;
Matrix sd = new Matrix();
sd.setValue( 2, 0, sx );
sd.setValue( 2, 1, sy );
textMatrix = sd.multiply( textMatrix );
// determine the width of this character
// XXX: Note that if we handled vertical text, we should be using Y here
float widthText = glyphMatrixEndDisp.getXPosition() - glyphMatrixStDisp.getXPosition();
while( characterBuffer.length() + ( c != null ? c.length() : 1 ) > individualWidthsBuffer.length )
{
float[] tmp = new float[individualWidthsBuffer.length * 2];
System.arraycopy( individualWidthsBuffer, 0, tmp, 0, individualWidthsBuffer.length );
individualWidthsBuffer = tmp;
}
//there are several cases where one character code will
//output multiple characters. For example "fi" or a
//glyphname that has no mapping like "visiblespace"
if( c != null )
{
Arrays.fill(
individualWidthsBuffer,
characterBuffer.length(),
characterBuffer.length() + c.length(),
widthText / c.length());
validCharCnt += c.length();
}
else
{
// PDFBOX-373: Replace a null entry with "?" so it is
// not printed as "(null)"
c = "?";
individualWidthsBuffer[characterBuffer.length()] = widthText;
}
characterBuffer.append(c);
totalCharCnt += c.length();
if( spacingText == 0 && (i + codeLength) < string.length )
{
continue;
}
textMatrixEndDisp = glyphMatrixEndDisp;
float totalVerticalDisplacementDisp = maxVerticalDisplacementText * fontSizeText * yScaleDisp;
float[] individualWidths = new float[characterBuffer.length()];
System.arraycopy( individualWidthsBuffer, 0, individualWidths, 0, individualWidths.length );
// process the decoded text
processTextPosition(
new TextPosition(
page,
textMatrixStDisp,
textMatrixEndDisp,
totalVerticalDisplacementDisp,
individualWidths,
spaceWidthDisp,
characterBuffer.toString(),
font,
fontSizeText,
(int)(fontSizeText * textMatrix.getXScale()),
wordSpacingDisp ));
textMatrixStDisp = textMatrix.multiply( dispMatrix );
characterBuffer.setLength(0);
}
}
|
diff --git a/src/net/sf/freecol/server/ai/mission/UnitSeekAndDestroyMission.java b/src/net/sf/freecol/server/ai/mission/UnitSeekAndDestroyMission.java
index f53f4205e..55802a40b 100644
--- a/src/net/sf/freecol/server/ai/mission/UnitSeekAndDestroyMission.java
+++ b/src/net/sf/freecol/server/ai/mission/UnitSeekAndDestroyMission.java
@@ -1,471 +1,471 @@
/**
* Copyright (C) 2002-2012 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.server.ai.mission;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.CombatModel;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Map.Direction;
import net.sf.freecol.common.model.Ownable;
import net.sf.freecol.common.model.PathNode;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Player.Stance;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Tension;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.pathfinding.CostDeciders;
import net.sf.freecol.common.model.pathfinding.GoalDecider;
import net.sf.freecol.common.networking.Connection;
import net.sf.freecol.server.ai.AIMain;
import net.sf.freecol.server.ai.AIMessage;
import net.sf.freecol.server.ai.AIPlayer;
import net.sf.freecol.server.ai.AIUnit;
import org.w3c.dom.Element;
/**
* Mission for attacking a specific target, be it a Unit or a Settlement.
*/
public class UnitSeekAndDestroyMission extends Mission {
private static final Logger logger = Logger.getLogger(UnitSeekAndDestroyMission.class.getName());
private static final String tag = "AI seek+destroyer";
/**
* The object we are trying to destroy. This can be a
* either <code>Settlement</code> or a <code>Unit</code>.
*/
private Location target;
/**
* Creates a mission for the given <code>AIUnit</code>.
*
* @param aiMain The main AI-object.
* @param aiUnit The <code>AIUnit</code> this mission
* is created for.
* @param target The object we are trying to destroy. This can be either a
* <code>Settlement</code> or a <code>Unit</code>.
*/
public UnitSeekAndDestroyMission(AIMain aiMain, AIUnit aiUnit,
Location target) {
super(aiMain, aiUnit);
if (!(target instanceof Unit || target instanceof Settlement)) {
throw new IllegalArgumentException("Invalid seek+destroy target: "
+ target);
}
this.target = target;
logger.finest(tag + " begins with target " + target
+ ": " + aiUnit.getUnit());
}
/**
* Loads a mission from the given element.
*
* @param aiMain The main AI-object.
* @param element An <code>Element</code> containing an
* XML-representation of this object.
*/
public UnitSeekAndDestroyMission(AIMain aiMain, Element element) {
super(aiMain);
readFromXMLElement(element);
}
/**
* Creates a new <code>UnitSeekAndDestroyMission</code> and reads
* the given element.
*
* @param aiMain The main AI-object.
* @param in The input stream containing the XML.
* @throws XMLStreamException if a problem was encountered
* during parsing.
* @see net.sf.freecol.server.ai.AIObject#readFromXML
*/
public UnitSeekAndDestroyMission(AIMain aiMain, XMLStreamReader in)
throws XMLStreamException {
super(aiMain);
readFromXML(in);
}
/**
* Gets the object we are trying to destroy.
*
* @return The object which should be destroyed.
*/
public Location getTarget() {
return target;
}
/**
* Is a location a suitable seek-and-destroy target for an AI unit?
*
* @param aiUnit The <code>AIUnit</code> to seek-and-destroy with.
* @param target The candidate <code>Settlement</code> or <code>Unit</code>.
* @return True if the target is suitable.
*/
public static boolean isTarget(AIUnit aiUnit, Location target) {
final Unit unit = aiUnit.getUnit();
final Player owner = unit.getOwner();
Player targetPlayer;
return target != null
&& !((FreeColGameObject)target).isDisposed()
&& target.getTile() != null
&& !(target instanceof Settlement && unit.isNaval())
&& !(target instanceof Unit
&& (target.getTile().getSettlement() != null
|| ((((Unit)target).isNaval() && !target.getTile().isLand())
!= unit.isNaval())))
&& (targetPlayer = ((Ownable)target).getOwner()) != null
&& targetPlayer != owner
&& (owner.getStance(targetPlayer) == Stance.WAR
|| (owner.isIndian()
&& owner.getTension(targetPlayer).getLevel()
.compareTo(Tension.Level.CONTENT) > 0));
}
/**
* Extract a valid target for this mission from a path.
*
* @param aiUnit The <code>AIUnit</code> to perform the mission.
* @param path A <code>PathNode</code> to extract a target from.
* @return A target for this mission, or null if none found.
*/
public static Location extractTarget(AIUnit aiUnit, PathNode path) {
Unit unit;
Tile tile;
Location target = (aiUnit == null
|| (unit = aiUnit.getUnit()) == null
|| path == null
|| (tile = path.getLastNode().getTile()) == null) ? null
: (tile.getSettlement() != null) ? tile.getSettlement()
: tile.getDefendingUnit(unit);
return (isTarget(aiUnit, target)) ? target : null;
}
/**
* Scores a potential attack on a settlement.
*
* Do not cheat and look inside the settlement.
* Just use visible facts about it.
*
* TODO: if we are the REF and there is a significant Tory
* population inside, assume traitors have briefed us.
*
* @param aiUnit The <code>AIUnit</code> to do the mission.
* @param path The <code>PathNode</code> to take to the settlement.
* @param settlement The <code>Settlement</code> to attack.
* @return A score of the desirability of the mission.
*/
static private int scoreSettlementTarget(AIUnit aiUnit, PathNode path,
Settlement settlement) {
final Unit unit = aiUnit.getUnit();
final CombatModel combatModel = unit.getGame().getCombatModel();
int value = 1020;
value -= path.getTotalTurns() * 100;
final float off = combatModel.getOffencePower(unit, settlement);
value += off * 50;
if (settlement instanceof Colony) {
// Favour high population (more loot:-).
Colony colony = (Colony) settlement;
value += 50 * colony.getUnitCount();
if (colony.hasStockade()) { // Avoid fortifications.
value -= 200 * colony.getStockade().getLevel();
}
} else if (settlement instanceof IndianSettlement) {
// Favour the most hostile settlements
IndianSettlement is = (IndianSettlement) settlement;
Tension tension = is.getAlarm(unit.getOwner());
if (tension != null) value += tension.getValue() / 2;
}
if (unit.getOwner().isIndian()) {
// Natives prefer to attack when DISPLEASED.
IndianSettlement is = unit.getIndianSettlement();
if (is != null && is.getAlarm(settlement.getOwner()) != null) {
value += is.getAlarm(settlement.getOwner()).getValue()
- Tension.Level.DISPLEASED.getLimit();
}
}
logger.finest("UnitSeekAndDestroyMission settlement score(" + unit
+ " v " + settlement + ") = " + value);
return value;
}
/**
* Scores a potential attack on a unit.
*
* @param aiUnit The <code>AIUnit</code> to do the mission.
* @param path The <code>PathNode</code> to take to the settlement.
* @param defender The <code>Unit</code> to attack.
* @return A score of the desirability of the mission.
*/
static private int scoreUnitTarget(AIUnit aiUnit, PathNode path,
Unit defender) {
final Unit unit = aiUnit.getUnit();
final Tile tile = path.getLastNode().getTile();
final int turns = path.getTotalTurns();
final CombatModel combatModel = unit.getGame().getCombatModel();
final float off = combatModel.getOffencePower(unit, defender);
final float def = combatModel.getDefencePower(unit, defender);
if (off <= 0) return Integer.MIN_VALUE;
int value = 1020 - turns * 100;
value += 100 * (off - def);
// Add a big bonus for treasure trains on the tile.
// Do not cheat and look at the value.
for (Unit u : tile.getUnitList()) {
if (u.canCarryTreasure() && u.getTreasureAmount() > 0) {
value += 1000;
break;
}
}
if (defender.isNaval()) {
if (tile.isLand()) value += 500; // Easy win
} else {
if (defender.hasAbility(Ability.EXPERT_SOLDIER)
&& !defender.isArmed()) value += 100;
}
logger.finest("UnitSeekAndDestroyMission score(" + unit
+ " v " + defender + ") = " + value);
return value;
}
/**
* Evaluate a potential seek and destroy mission for a given unit
* to a given tile.
*
* TODO: revisit and rebalance the mass of magic numbers.
*
* @param aiUnit The <code>AIUnit</code> to do the mission.
* @param path A <code>PathNode</code> to take to the target.
* @return A score for the proposed mission.
*/
public static int scoreTarget(AIUnit aiUnit, PathNode path) {
Location target = extractTarget(aiUnit, path);
return (target instanceof Settlement)
? scoreSettlementTarget(aiUnit, path, (Settlement)target)
: (target instanceof Unit)
? scoreUnitTarget(aiUnit, path, (Unit)target)
: Integer.MIN_VALUE;
}
/**
* Finds a suitable seek-and-destroy target for an AI unit.
*
* @param aiUnit The <code>AIUnit</code> to find a target for.
* @param range An upper bound on the number of moves.
* @return A path to the target, or null if none found.
*/
public static PathNode findTarget(AIUnit aiUnit, int range) {
Unit unit;
Tile startTile;
if (aiUnit == null
|| (unit = aiUnit.getUnit()) == null || unit.isDisposed()
|| (startTile = unit.getPathStartTile()) == null) return null;
return unit.search(startTile,
getMissionGoalDecider(aiUnit, UnitSeekAndDestroyMission.class),
CostDeciders.avoidIllegal(), range,
((unit.isOnCarrier()) ? ((Unit)unit.getLocation()) : null));
}
// Fake Transportable interface
/**
* Gets the transport destination for units with this mission.
*
* @return The destination for this <code>Transportable</code>.
*/
@Override
public Tile getTransportDestination() {
Tile tile = (target == null) ? null : target.getTile();
return (shouldTakeTransportToTile(tile)) ? tile : null;
}
// Mission interface
/**
* Check to see if this mission is still valid.
*
* @return True if this mission is valid.
*/
public boolean isValid() {
return super.isValid()
&& getUnit().isOffensiveUnit()
&& isTarget(getAIUnit(), target);
}
/**
* Performs the mission. Check for a target-of-opportunity within one
* turn and hit that if possible. Otherwise, just continue on towards
* the real target.
*
* @param connection The <code>Connection</code> to the server.
*/
@Override
public void doMission(Connection connection) {
final Unit unit = getUnit();
if (unit == null || unit.isDisposed()) {
logger.warning(tag + " broken: " + unit);
return;
} else if (!unit.isOffensiveUnit()) {
logger.finest(tag + " disarmed: " + unit);
return;
}
final Player player = unit.getOwner();
// Is there a target-of-opportunity?
final AIUnit aiUnit = getAIUnit();
PathNode path = findTarget(aiUnit, 1);
Location nearbyTarget = (path == null) ? null
: extractTarget(aiUnit, path);
if (nearbyTarget == target) nearbyTarget = null;
if (isValid()) {
if (nearbyTarget != null) {
logger.finest(tag + " found target-of-opportunity "
+ nearbyTarget + ": " + unit);
}
} else {
if (nearbyTarget == null) {
logger.finest(tag + " can not find a target: " + unit);
return;
}
logger.finest(tag + " abandoning " + target
+ " retargeting " + nearbyTarget + ": " + unit);
target = nearbyTarget;
nearbyTarget = null;
}
Location currentTarget = (nearbyTarget != null) ? nearbyTarget : target;
Unit.MoveType mt = travelToTarget(tag, currentTarget.getTile());
Tile unitTile = unit.getTile();
Settlement settlement = unitTile.getSettlement();
switch (mt) {
case MOVE_NO_MOVES:
logger.finest(tag + " en route to " + currentTarget + ": " + unit);
break;
case ATTACK_UNIT: case ATTACK_SETTLEMENT:
if (settlement != null && settlement.getUnitCount() < 2) {
// Do not risk attacking out of a settlement that
// might collapse. Defend instead.
aiUnit.setMission(new DefendSettlementMission(getAIMain(),
aiUnit, settlement));
return;
}
logger.finest(tag + " attacking " + currentTarget + ": " + unit);
- AIMessage.askAttack(aiUnit, unitTile.getDirection(target.getTile()));
+ AIMessage.askAttack(aiUnit, unitTile.getDirection(currentTarget.getTile()));
break;
default:
logger.finest(tag + " unexpected move type: " + mt + ": " + unit);
break;
}
}
/**
* Gets debugging information about this mission.
* This string is a short representation of this
* object's state.
*
* @return The <code>String</code>.
*/
@Override
public String getDebuggingInfo() {
if (target == null) {
return "No target";
} else {
final String name;
if (target instanceof Unit) {
name = ((Unit) target).toString();
} else if (target instanceof Colony) {
name = ((Colony) target).getName();
} else {
name = "";
}
return target.getTile().getPosition() + " " + name;
}
}
// Serialization
/**
* Writes all of the <code>AIObject</code>s and other AI-related
* information to an XML-stream.
*
* @param out The target stream.
* @throws XMLStreamException if there are any problems writing to the
* stream.
*/
protected void toXMLImpl(XMLStreamWriter out) throws XMLStreamException {
toXML(out, getXMLElementTagName());
}
/**
* {@inherit-doc}
*/
@Override
protected void writeAttributes(XMLStreamWriter out)
throws XMLStreamException {
super.writeAttributes(out);
if (getTarget() != null) {
out.writeAttribute("target", getTarget().getId());
}
}
/**
* {@inherit-doc}
*/
@Override
protected void readAttributes(XMLStreamReader in)
throws XMLStreamException {
super.readAttributes(in);
target = (Location)getGame()
.getFreeColGameObjectSafely(in.getAttributeValue(null, "target"));
}
/**
* Returns the tag name of the root element representing this object.
*
* @return "unitSeekAndDestroyMission".
*/
public static String getXMLElementTagName() {
return "unitSeekAndDestroyMission";
}
}
| true | true | public void doMission(Connection connection) {
final Unit unit = getUnit();
if (unit == null || unit.isDisposed()) {
logger.warning(tag + " broken: " + unit);
return;
} else if (!unit.isOffensiveUnit()) {
logger.finest(tag + " disarmed: " + unit);
return;
}
final Player player = unit.getOwner();
// Is there a target-of-opportunity?
final AIUnit aiUnit = getAIUnit();
PathNode path = findTarget(aiUnit, 1);
Location nearbyTarget = (path == null) ? null
: extractTarget(aiUnit, path);
if (nearbyTarget == target) nearbyTarget = null;
if (isValid()) {
if (nearbyTarget != null) {
logger.finest(tag + " found target-of-opportunity "
+ nearbyTarget + ": " + unit);
}
} else {
if (nearbyTarget == null) {
logger.finest(tag + " can not find a target: " + unit);
return;
}
logger.finest(tag + " abandoning " + target
+ " retargeting " + nearbyTarget + ": " + unit);
target = nearbyTarget;
nearbyTarget = null;
}
Location currentTarget = (nearbyTarget != null) ? nearbyTarget : target;
Unit.MoveType mt = travelToTarget(tag, currentTarget.getTile());
Tile unitTile = unit.getTile();
Settlement settlement = unitTile.getSettlement();
switch (mt) {
case MOVE_NO_MOVES:
logger.finest(tag + " en route to " + currentTarget + ": " + unit);
break;
case ATTACK_UNIT: case ATTACK_SETTLEMENT:
if (settlement != null && settlement.getUnitCount() < 2) {
// Do not risk attacking out of a settlement that
// might collapse. Defend instead.
aiUnit.setMission(new DefendSettlementMission(getAIMain(),
aiUnit, settlement));
return;
}
logger.finest(tag + " attacking " + currentTarget + ": " + unit);
AIMessage.askAttack(aiUnit, unitTile.getDirection(target.getTile()));
break;
default:
logger.finest(tag + " unexpected move type: " + mt + ": " + unit);
break;
}
}
| public void doMission(Connection connection) {
final Unit unit = getUnit();
if (unit == null || unit.isDisposed()) {
logger.warning(tag + " broken: " + unit);
return;
} else if (!unit.isOffensiveUnit()) {
logger.finest(tag + " disarmed: " + unit);
return;
}
final Player player = unit.getOwner();
// Is there a target-of-opportunity?
final AIUnit aiUnit = getAIUnit();
PathNode path = findTarget(aiUnit, 1);
Location nearbyTarget = (path == null) ? null
: extractTarget(aiUnit, path);
if (nearbyTarget == target) nearbyTarget = null;
if (isValid()) {
if (nearbyTarget != null) {
logger.finest(tag + " found target-of-opportunity "
+ nearbyTarget + ": " + unit);
}
} else {
if (nearbyTarget == null) {
logger.finest(tag + " can not find a target: " + unit);
return;
}
logger.finest(tag + " abandoning " + target
+ " retargeting " + nearbyTarget + ": " + unit);
target = nearbyTarget;
nearbyTarget = null;
}
Location currentTarget = (nearbyTarget != null) ? nearbyTarget : target;
Unit.MoveType mt = travelToTarget(tag, currentTarget.getTile());
Tile unitTile = unit.getTile();
Settlement settlement = unitTile.getSettlement();
switch (mt) {
case MOVE_NO_MOVES:
logger.finest(tag + " en route to " + currentTarget + ": " + unit);
break;
case ATTACK_UNIT: case ATTACK_SETTLEMENT:
if (settlement != null && settlement.getUnitCount() < 2) {
// Do not risk attacking out of a settlement that
// might collapse. Defend instead.
aiUnit.setMission(new DefendSettlementMission(getAIMain(),
aiUnit, settlement));
return;
}
logger.finest(tag + " attacking " + currentTarget + ": " + unit);
AIMessage.askAttack(aiUnit, unitTile.getDirection(currentTarget.getTile()));
break;
default:
logger.finest(tag + " unexpected move type: " + mt + ": " + unit);
break;
}
}
|
diff --git a/src/RegisterFile.java b/src/RegisterFile.java
index 2fddf1e..6b24909 100644
--- a/src/RegisterFile.java
+++ b/src/RegisterFile.java
@@ -1,46 +1,46 @@
public class RegisterFile implements Clockable{
public Register[] regFile;
public Pin writeReg = new Pin();
public Pin readReg1 = new Pin();
public Pin readReg2 = new Pin();
public Pin writeData = new Pin();
public Pin regWrite = new Pin();
public Pin readData1 = new Pin();
public Pin readData2 = new Pin();
public RegisterFile(){
// initializes with 32 words of memory set to 0
regFile = new Register[32];
for(int x=0; x<32; x++){
regFile[x] = new Register(0);
}
}
// gets the value stored at register $'index'
public long getVal(int index){
return regFile[index].getValue();
}
// updates value at register $'index' with 'val'
public void setRegister(int index, long val){
if(index >=1 && index < 32){
regFile[index].setValue(val);
}
else throw new Error("Cannot access $r" + index);
}
public void clockEdge(){
// if regWrite is 1, then we write to the register
// which is stored in writeReg. Data is stored in writeData;
if(regWrite.getValue() != null && regWrite.getValue() == (long)1){
setRegister(writeReg.getValue().intValue(), writeData.getValue());
}
- readData1.setValue(readReg1.getValue());
- readData2.setValue(readReg2.getValue());
+ readData1.setValue(getVal(readReg1.getValue().intValue()));
+ readData2.setValue(getVal(readReg2.getValue().intValue()));
}
}
| true | true | public void clockEdge(){
// if regWrite is 1, then we write to the register
// which is stored in writeReg. Data is stored in writeData;
if(regWrite.getValue() != null && regWrite.getValue() == (long)1){
setRegister(writeReg.getValue().intValue(), writeData.getValue());
}
readData1.setValue(readReg1.getValue());
readData2.setValue(readReg2.getValue());
}
| public void clockEdge(){
// if regWrite is 1, then we write to the register
// which is stored in writeReg. Data is stored in writeData;
if(regWrite.getValue() != null && regWrite.getValue() == (long)1){
setRegister(writeReg.getValue().intValue(), writeData.getValue());
}
readData1.setValue(getVal(readReg1.getValue().intValue()));
readData2.setValue(getVal(readReg2.getValue().intValue()));
}
|
diff --git a/se/sics/mspsim/core/MSP430Core.java b/se/sics/mspsim/core/MSP430Core.java
index 7f56f5a..0eb1d35 100644
--- a/se/sics/mspsim/core/MSP430Core.java
+++ b/se/sics/mspsim/core/MSP430Core.java
@@ -1,2190 +1,2184 @@
/**
* Copyright (c) 2007, 2008, 2009, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of MSPSim.
*
* -----------------------------------------------------------------
*
* MSP430Core
*
* Author : Joakim Eriksson
* Created : Sun Oct 21 22:00:00 2007
*/
package se.sics.mspsim.core;
import java.io.PrintStream;
import java.util.ArrayList;
import se.sics.mspsim.core.EmulationLogger.WarningType;
import se.sics.mspsim.core.Memory.AccessMode;
import se.sics.mspsim.core.Memory.AccessType;
import se.sics.mspsim.util.ComponentRegistry;
import se.sics.mspsim.util.DefaultEmulationLogger;
import se.sics.mspsim.util.MapEntry;
import se.sics.mspsim.util.MapTable;
import se.sics.mspsim.util.Utils;
/**
* The CPU of the MSP430
*/
public class MSP430Core extends Chip implements MSP430Constants {
public static final int RETURN = 0x4130;
public static final boolean debugInterrupts = false;
public static final boolean EXCEPTION_ON_BAD_OPERATION = true;
// Try it out with 64 k memory
public final int MAX_MEM;
public final int MAX_MEM_IO;
// 16 registers of which some are "special" - PC, SP, etc.
public final int[] reg = new int[16];
private final RegisterMonitor[] regWriteMonitors = new RegisterMonitor[16];
private final RegisterMonitor[] regReadMonitors = new RegisterMonitor[16];
// true => breakpoints can occur!
boolean breakpointActive = true;
public final int memory[];
private final Flash flash;
boolean isFlashBusy;
boolean isStopping = false;
private final Memory memorySegments[];
Memory currentSegment;
public long cycles = 0;
public long cpuCycles = 0;
MapTable map;
public final boolean MSP430XArch;
public final MSP430Config config;
private final ArrayList<IOUnit> ioUnits;
private final SFR sfr;
private final Watchdog watchdog;
private final ClockSystem bcs;
// From the possible interrupt sources - to be able to indicate is serviced.
// NOTE: 64 since more modern MSP430's have more than 16 vectors (5xxx has 64).
private InterruptHandler interruptSource[] = new InterruptHandler[64];
private final int MAX_INTERRUPT;
protected int interruptMax = -1;
// Op/instruction represents the last executed OP / instruction
private int op;
public int instruction;
private int extWord;
int servicedInterrupt = -1;
InterruptHandler servicedInterruptUnit = null;
protected boolean interruptsEnabled = false;
protected boolean cpuOff = false;
// Not private since they are needed (for fast access...)
public int dcoFrq = 2500000;
int aclkFrq = 32768;
public int smclkFrq = dcoFrq;
long lastCyclesTime = 0;
long lastVTime = 0;
long currentTime = 0;
long lastMicrosDelta;
double currentDCOFactor = 1.0;
// Clk A can be "captured" by timers - needs to be handled close to CPU...?
// private int clkACaptureMode = CLKCAPTURE_NONE;
// Other clocks too...
long nextEventCycles;
private EventQueue vTimeEventQueue = new EventQueue();
private long nextVTimeEventCycles;
private EventQueue cycleEventQueue = new EventQueue();
private long nextCycleEventCycles;
private ArrayList<Chip> chips = new ArrayList<Chip>();
final ComponentRegistry registry;
Profiler profiler;
public MSP430Core(int type, ComponentRegistry registry, MSP430Config config) {
super("MSP430", "MSP430 Core", null);
logger = registry.getComponent(EmulationLogger.class);
if (logger == null) {
logger = new DefaultEmulationLogger(this, System.out);
registry.registerComponent("logger", logger);
}
MAX_INTERRUPT = config.maxInterruptVector;
MAX_MEM_IO = config.maxMemIO;
MAX_MEM = config.maxMem;
MSP430XArch = config.MSP430XArch;
memory = new int[MAX_MEM];
memorySegments = new Memory[MAX_MEM >> 8];
flash = new Flash(this, memory,
new FlashRange(config.mainFlashStart, config.mainFlashStart + config.mainFlashSize, 512, 64),
new FlashRange(config.infoMemStart, config.infoMemStart + config.infoMemSize, 128, 64),
config.flashControllerOffset);
currentSegment = new Memory() {
@Override
public int read(int address, AccessMode mode, AccessType type) throws EmulationException {
if (address >= MAX_MEM) {
throw new EmulationException("Reading outside memory: 0x" + Utils.hex(address, 4));
}
return memorySegments[address >> 8].read(address, mode, type);
}
@Override
public void write(int address, int data, AccessMode mode) throws EmulationException {
if (address >= MAX_MEM) {
throw new EmulationException("Writing outside memory: 0x" + Utils.hex(address, 4));
}
memorySegments[address >> 8].write(address, data, mode);
}
@Override
public int get(int address, AccessMode mode) {
if (address >= MAX_MEM) {
throw new EmulationException("Reading outside memory: 0x" + Utils.hex(address, 4));
}
return memorySegments[address >> 8].get(address, mode);
}
@Override
public void set(int address, int data, AccessMode mode) {
if (address >= MAX_MEM) {
throw new EmulationException("Writing outside memory: 0x" + Utils.hex(address, 4));
}
memorySegments[address >> 8].set(address, data, mode);
}
};
// System.out.println("Set up MSP430 Core with " + MAX_MEM + " bytes memory");
/* this is for detecting writes/read to/from non-existing IO */
IOUnit voidIO = new IOUnit("void", this, memory, 0) {
public void interruptServiced(int vector) {
}
public void write(int address, int value, boolean word, long cycles) {
cpu.logw(WarningType.VOID_IO_WRITE, "*** IOUnit write to non-existent IO at $" + Utils.hex(address, 4));
}
public int read(int address, boolean word, long cycles) {
cpu.logw(WarningType.VOID_IO_READ, "*** IOUnit read from non-existent IO at $" + Utils.hex(address, 4));
return 0;
}
};
/* setup memory segments */
int maxSeg = MAX_MEM >> 8;
Memory ramSegment = new RAMSegment(this);
RAMOffsetSegment ramMirrorSegment = null;
Memory flashSegment = new FlashSegment(this, flash);
IOSegment ioSegment = new IOSegment(this, MAX_MEM_IO, voidIO);
Memory noMemorySegment = new NoMemSegment(this);
for (int i = 0; i < maxSeg; i++) {
if (config.isRAM(i << 8)) {
// System.out.println("Setting RAM segment at: " + Utils.hex16(i << 8));
memorySegments[i] = ramSegment;
} else if (config.isRAMMirror(i << 8)) {
if (ramMirrorSegment == null) {
ramMirrorSegment = new RAMOffsetSegment(this, config.ramMirrorAddress - config.ramMirrorStart);
}
// System.out.println("Setting RAM mirror segment at: " + Utils.hex(i << 8, 4)
// + " => " + Utils.hex((i << 8) + ramMirrorSegment.getOffset()));
memorySegments[i] = ramMirrorSegment;
} else if (config.isFlash(i << 8) || config.isInfoMem(i << 8)) {
// System.out.println("Setting Flash segment at: " + Utils.hex16(i << 8));
memorySegments[i] = flashSegment;
} else if (config.isIO(i << 8)) {
// System.out.println("Setting IO segment at: " + Utils.hex16(i << 8));
memorySegments[i] = ioSegment;
} else {
// System.out.println("Setting NoMem segment at: " + Utils.hex16(i << 8));
memorySegments[i] = noMemorySegment;
}
}
this.registry = registry;
this.config = config;
// The CPU need to register itself as chip
addChip(this);
// Ignore type for now...
setModeNames(MODE_NAMES);
// IOUnits should likely be placed in a hashtable?
// Maybe for debugging purposes...
ioUnits = new ArrayList<IOUnit>();
ioSegment.setIORange(config.flashControllerOffset, 6, flash);
/* Setup special function registers */
sfr = new SFR(this, memory);
ioSegment.setIORange(config.sfrOffset, 0x10, sfr);
// first step towards making core configurable
Timer[] timers = new Timer[config.timerConfig.length];
for (int i = 0; i < config.timerConfig.length; i++) {
Timer t = new Timer(this, memory, config.timerConfig[i]);
ioSegment.setIORange(config.timerConfig[i].offset, 0x20, t);
ioSegment.setIORange(config.timerConfig[i].timerIVAddr, 1, t);
timers[i] = t;
}
bcs = config.createClockSystem(this, memory, timers);
ioSegment.setIORange(bcs.getAddressRangeMin(), bcs.getAddressRangeMax() - bcs.getAddressRangeMin() + 1, bcs);
// SFR and Basic clock system.
ioUnits.add(sfr);
ioUnits.add(bcs);
config.setup(this, ioUnits);
/* timers after ports ? */
for (int i = 0; i < timers.length; i++) {
ioUnits.add(timers[i]);
}
watchdog = new Watchdog(this);
ioSegment.setIORange(config.watchdogOffset, 1, watchdog);
ioUnits.add(watchdog);
bcs.reset(0);
}
public void setIORange(int address, int range, IOUnit io) {
if (address + range > MAX_MEM_IO) {
throw new IllegalStateException("Outside IO memory: 0x" + Utils.hex(address, 4));
}
IOSegment ioSegment = (IOSegment) memorySegments[address >> 8];
ioSegment.setIORange(address, range, io);
}
public Profiler getProfiler() {
return profiler;
}
public void setProfiler(Profiler prof) {
registry.registerComponent("profiler", prof);
profiler = prof;
profiler.setCPU(this);
}
public synchronized void addGlobalMonitor(MemoryMonitor mon) {
GlobalWatchedMemory gwm;
if (currentSegment instanceof GlobalWatchedMemory) {
gwm = (GlobalWatchedMemory)currentSegment;
} else {
currentSegment = gwm = new GlobalWatchedMemory(currentSegment);
}
gwm.addGlobalMonitor(mon);
}
public synchronized void removeGlobalMonitor(MemoryMonitor mon) {
if (currentSegment instanceof GlobalWatchedMemory) {
GlobalWatchedMemory gwm = (GlobalWatchedMemory)currentSegment;
gwm.removeGlobalMonitor(mon);
if (!gwm.hasGlobalMonitor()) {
// No more monitors - switch back to normal memory
currentSegment = gwm.getWatchedMemory();
}
}
}
public ComponentRegistry getRegistry() {
return registry;
}
public SFR getSFR() {
return sfr;
}
public void addChip(Chip chip) {
chips.add(chip);
}
public Chip getChip(String name) {
for(Chip chip : chips) {
if (name.equalsIgnoreCase(chip.getID()) || name.equalsIgnoreCase(chip.getName())) {
return chip;
}
}
return null;
}
public <T extends Chip> T getChip(Class<T> type) {
for(Chip chip : chips) {
if (type.isInstance(chip)) {
return type.cast(chip);
}
}
return null;
}
public <T extends Chip> T getChip(Class<T> type, String name) {
for(Chip chip : chips) {
if (type.isInstance(chip) &&
(name.equalsIgnoreCase(chip.getID()) || name.equalsIgnoreCase(chip.getName()))) {
return type.cast(chip);
}
}
return null;
}
public Chip[] getChips() {
return chips.toArray(new Chip[chips.size()]);
}
public <T extends Chip> T[] getChips(Class<T> type) {
ArrayList<T> list = new ArrayList<T>();
for(Chip chip : chips) {
if (type.isInstance(chip)) {
list.add(type.cast(chip));
}
}
@SuppressWarnings("unchecked")
T[] tmp = (T[]) java.lang.reflect.Array.newInstance(type, list.size());
return list.toArray(tmp);
}
public Loggable[] getLoggables() {
Loggable[] ls = new Loggable[ioUnits.size() + chips.size()];
for (int i = 0; i < ioUnits.size(); i++) {
ls[i] = ioUnits.get(i);
}
for (int i = 0; i < chips.size(); i++) {
ls[i + ioUnits.size()] = chips.get(i);
}
return ls;
}
public Loggable getLoggable(String name) {
Loggable l = getChip(name);
if (l == null) {
l = getIOUnit(name);
}
return l;
}
public boolean hasWatchPoint(int address) {
Memory mem = memorySegments[address >> 8];
if (mem instanceof WatchedMemory) {
return ((WatchedMemory)mem).hasWatchPoint(address);
}
return false;
}
public synchronized void addWatchPoint(int address, MemoryMonitor mon) {
int seg = address >> 8;
WatchedMemory wm;
if (memorySegments[seg] instanceof WatchedMemory) {
wm = (WatchedMemory) memorySegments[seg];
} else {
wm = new WatchedMemory(address & 0xfff00, memorySegments[seg]);
memorySegments[seg] = wm;
}
wm.addWatchPoint(address, mon);
}
public synchronized void removeWatchPoint(int address, MemoryMonitor mon) {
if (memorySegments[address >> 8] instanceof WatchedMemory) {
WatchedMemory wm = (WatchedMemory) memorySegments[address >> 8];
wm.removeWatchPoint(address, mon);
}
}
public synchronized void addRegisterMonitor(int r, RegisterMonitor mon) {
addRegisterWriteMonitor(r, mon);
addRegisterReadMonitor(r, mon);
}
public synchronized void removeRegisterMonitor(int r, RegisterMonitor mon) {
removeRegisterWriteMonitor(r, mon);
removeRegisterReadMonitor(r, mon);
}
public synchronized void addRegisterWriteMonitor(int r, RegisterMonitor mon) {
regWriteMonitors[r] = RegisterMonitor.Proxy.INSTANCE.add(regWriteMonitors[r], mon);
}
public synchronized void removeRegisterWriteMonitor(int r, RegisterMonitor mon) {
regWriteMonitors[r] = RegisterMonitor.Proxy.INSTANCE.remove(regWriteMonitors[r], mon);
}
public synchronized void addRegisterReadMonitor(int r, RegisterMonitor mon) {
regReadMonitors[r] = RegisterMonitor.Proxy.INSTANCE.add(regReadMonitors[r], mon);
}
public synchronized void removeRegisterReadMonitor(int r, RegisterMonitor mon) {
regReadMonitors[r] = RegisterMonitor.Proxy.INSTANCE.remove(regReadMonitors[r], mon);
}
public void writeRegister(int r, int value) {
// Before the write!
// if (value >= MAX_MEM) {
// System.out.println("Writing larger than MAX_MEM to " + r + " value:" + value);
// new Throwable().printStackTrace();
// }
RegisterMonitor rwm = regWriteMonitors[r];
if (rwm != null) {
// TODO Add register access mode
rwm.notifyWriteBefore(r, value, AccessMode.WORD);
reg[r] = value;
rwm.notifyWriteAfter(r, value, AccessMode.WORD);
} else {
reg[r] = value;
}
if (r == SR) {
boolean oldCpuOff = cpuOff;
if (debugInterrupts) {
if (((value & GIE) == GIE) != interruptsEnabled) {
System.out.println("InterruptEnabled changed: " + !interruptsEnabled);
}
}
boolean oldIE = interruptsEnabled;
interruptsEnabled = ((value & GIE) == GIE);
// if (debugInterrupts) System.out.println("Wrote to InterruptEnabled: " + interruptsEnabled + " was: " + oldIE);
if (oldIE == false && interruptsEnabled && servicedInterrupt >= 0) {
// System.out.println("*** Interrupts enabled while in interrupt : " +
// servicedInterrupt + " PC: $" + getAddressAsString(reg[PC]));
/* must handle pending immediately */
handlePendingInterrupts();
}
cpuOff = ((value & CPUOFF) == CPUOFF);
if (cpuOff != oldCpuOff) {
// System.out.println("LPM CPUOff: " + cpuOff + " cycles: " + cycles);
}
if (cpuOff) {
boolean scg0 = (value & SCG0) == SCG0;
boolean scg1 = (value & SCG1) == SCG1;
boolean oscoff = (value & OSCOFF) == OSCOFF;
if (oscoff && scg1 && scg0) {
setMode(MODE_LPM4);
} else if (scg1 && scg0){
setMode(MODE_LPM3);
} else if (scg1) {
setMode(MODE_LPM2);
} else if (scg0) {
setMode(MODE_LPM1);
} else {
setMode(MODE_LPM0);
}
} else {
setMode(MODE_ACTIVE);
}
}
}
public int readRegister(int r) {
int value;
RegisterMonitor rrm = regReadMonitors[r];
if (rrm != null) {
// TODO Register access mode
rrm.notifyReadBefore(r, AccessMode.WORD);
value = reg[r];
rrm.notifyReadAfter(r, AccessMode.WORD);
} else {
value = reg[r];
}
return value;
}
public int readRegisterCG(int r, int m) {
// CG1 + m == 0 => SR!
if ((r == CG1 && m != 0) || r == CG2) {
// No monitoring here... just return the CG values
return CREG_VALUES[r - 2][m];
}
int value;
RegisterMonitor rrm = regReadMonitors[r];
if (rrm != null) {
// TODO Register access mode
rrm.notifyReadBefore(r, AccessMode.WORD);
value = reg[r];
rrm.notifyReadAfter(r, AccessMode.WORD);
} else {
value = reg[r];
}
return value;
}
public int incRegister(int r, int value) {
int registerValue;
RegisterMonitor rm = regReadMonitors[r];
if (rm != null) {
rm.notifyReadBefore(r, AccessMode.WORD);
registerValue = reg[r];
rm.notifyReadAfter(r, AccessMode.WORD);
} else {
registerValue = reg[r];
}
rm = regWriteMonitors[r];
registerValue += value;
if (rm != null) {
rm.notifyWriteBefore(r, registerValue, AccessMode.WORD);
reg[r] = registerValue;
rm.notifyWriteAfter(r, registerValue, AccessMode.WORD);
} else {
reg[r] = registerValue;
}
return reg[r];
}
public void setACLKFrq(int frequency) {
aclkFrq = frequency;
}
public void setDCOFrq(int frequency, int smclkFrq) {
dcoFrq = frequency;
this.smclkFrq = smclkFrq;
// update last virtual time before updating DCOfactor
lastVTime = getTime();
lastCyclesTime = cycles;
lastMicrosDelta = 0;
currentDCOFactor = 1.0 * bcs.getMaxDCOFrequency() / frequency;
/* System.out.println("*** DCO: MAX:" + bcs.getMaxDCOFrequency() +
" current: " + frequency + " DCO_FAC = " + currentDCOFactor);*/
if (DEBUG)
log("Set smclkFrq: " + smclkFrq);
dcoReset();
}
/* called after dcoReset */
protected void dcoReset() {
}
// returns global time counted in max speed of DCOs (~5Mhz)
public long getTime() {
long diff = cycles - lastCyclesTime;
return lastVTime + (long) (diff * currentDCOFactor);
}
// Converts a virtual time to a cycles time according to the current
// cycle speed
private long convertVTime(long vTime) {
long tmpTime = lastCyclesTime + (long) ((vTime - lastVTime) / currentDCOFactor);
// System.out.println("ConvertVTime: vTime=" + vTime + " => " + tmpTime);
return tmpTime;
}
// get elapsed time in seconds
public double getTimeMillis() {
return 1000.0 * getTime() / bcs.getMaxDCOFrequency();
}
private void executeEvents() {
if (cycles >= nextVTimeEventCycles) {
if (vTimeEventQueue.eventCount == 0) {
nextVTimeEventCycles = cycles + 10000;
} else {
TimeEvent te = vTimeEventQueue.popFirst();
long now = getTime();
// if (now > te.time) {
// System.out.println("VTimeEvent got delayed by: " + (now - te.time) + " at " +
// cycles + " target Time: " + te.time + " class: " + te.getClass().getName());
// }
te.execute(now);
if (vTimeEventQueue.eventCount > 0) {
nextVTimeEventCycles = convertVTime(vTimeEventQueue.nextTime);
} else {
nextVTimeEventCycles = cycles + 10000;
}
}
}
if (cycles >= nextCycleEventCycles) {
if (cycleEventQueue.eventCount == 0) {
nextCycleEventCycles = cycles + 10000;
} else {
TimeEvent te = cycleEventQueue.popFirst();
te.execute(cycles);
if (cycleEventQueue.eventCount > 0) {
nextCycleEventCycles = cycleEventQueue.nextTime;
} else {
nextCycleEventCycles = cycles + 10000;
}
}
}
// Pick the one with shortest time in the future.
nextEventCycles = nextCycleEventCycles < nextVTimeEventCycles ?
nextCycleEventCycles : nextVTimeEventCycles;
}
/**
* Schedules a new Time event using the cycles counter
* @param event
* @param time
*/
public void scheduleCycleEvent(TimeEvent event, long cycles) {
long currentNext = cycleEventQueue.nextTime;
cycleEventQueue.addEvent(event, cycles);
if (currentNext != cycleEventQueue.nextTime) {
nextCycleEventCycles = cycleEventQueue.nextTime;
if (nextEventCycles > nextCycleEventCycles) {
nextEventCycles = nextCycleEventCycles;
}
}
}
/**
* Schedules a new Time event using the virtual time clock
* @param event
* @param time
*/
public void scheduleTimeEvent(TimeEvent event, long time) {
long currentNext = vTimeEventQueue.nextTime;
vTimeEventQueue.addEvent(event, time);
if (currentNext != vTimeEventQueue.nextTime) {
// This is only valid when not having a cycle event queue also...
// if we have it needs to be checked also!
nextVTimeEventCycles = convertVTime(vTimeEventQueue.nextTime);
if (nextEventCycles > nextVTimeEventCycles) {
nextEventCycles = nextVTimeEventCycles;
}
/* Warn if someone schedules a time backwards in time... */
if (cycles > nextVTimeEventCycles) {
logger.logw(this, WarningType.EMULATION_ERROR, "Scheduling time event backwards in time!!!");
throw new IllegalStateException("Cycles are passed desired future time...");
}
}
}
/**
* Schedules a new Time event msec milliseconds in the future
* @param event
* @param time
*/
public long scheduleTimeEventMillis(TimeEvent event, double msec) {
/* System.out.println("MAX_DCO " + bcs.getMaxDCOFrequency());*/
long time = (long) (getTime() + msec / 1000 * bcs.getMaxDCOFrequency());
// System.out.println("Scheduling at: " + time + " (" + msec + ") getTime: " + getTime());
scheduleTimeEvent(event, time);
return time;
}
public void printEventQueues(PrintStream out) {
out.println("Current cycles: " + cycles + " virtual time:" + getTime());
out.println("Cycle event queue: (next time: " + nextCycleEventCycles + ")");
cycleEventQueue.print(out);
out.println("Virtual time event queue: (next time: " + nextVTimeEventCycles + ")");
vTimeEventQueue.print(out);
}
// Should also return active units...
public IOUnit getIOUnit(String name) {
for (IOUnit ioUnit : ioUnits) {
if (name.equalsIgnoreCase(ioUnit.getID()) ||
name.equalsIgnoreCase(ioUnit.getName())) {
return ioUnit;
}
}
return null;
}
public <T> T getIOUnit(Class<T> type) {
for (IOUnit ioUnit : ioUnits) {
if (type.isInstance(ioUnit)) {
return type.cast(ioUnit);
}
}
return null;
}
public <T> T getIOUnit(Class<T> type, String name) {
for (IOUnit ioUnit : ioUnits) {
if (type.isInstance(ioUnit)
&& (name.equalsIgnoreCase(ioUnit.getID())
|| name.equalsIgnoreCase(ioUnit.getName()))) {
return type.cast(ioUnit);
}
}
return null;
}
private void resetIOUnits() {
for (IOUnit ioUnit : ioUnits) {
ioUnit.reset(RESET_POR);
}
}
private void internalReset() {
for (int i = 0, n = interruptSource.length; i < n; i++) {
interruptSource[i] = null;
}
servicedInterruptUnit = null;
servicedInterrupt = -1;
interruptMax = -1;
writeRegister(SR, 0);
cycleEventQueue.removeAll();
vTimeEventQueue.removeAll();
for (Chip chip : chips) {
chip.notifyReset();
}
// Needs to be last since these can add events...
resetIOUnits();
if (profiler != null) {
profiler.resetProfile();
}
}
public EmulationLogger getLogger() {
return logger;
}
public void reset() {
flagInterrupt(MAX_INTERRUPT, null, true);
}
// Indicate that we have an interrupt now!
// We should only get same IOUnit for same interrupt level
public void flagInterrupt(int interrupt, InterruptHandler source,
boolean triggerIR) {
if (triggerIR) {
interruptSource[interrupt] = source;
if (debugInterrupts) {
if (source != null) {
System.out.println("### Interrupt " + interrupt + " flagged ON by " + source.getName() + " prio: " + interrupt);
} else {
System.out.println("### Interrupt " + interrupt + " flagged ON by <null>");
}
}
// MAX priority is executed first - update max if this is higher!
if (interrupt > interruptMax) {
interruptMax = interrupt;
}
if (interruptMax == MAX_INTERRUPT) {
// This can not be masked at all!
interruptsEnabled = true;
}
} else {
if (interruptSource[interrupt] == source) {
if (debugInterrupts) {
System.out.println("### Interrupt flagged OFF by " + source.getName() + " prio: " + interrupt);
}
interruptSource[interrupt] = null;
reevaluateInterrupts();
}
}
}
private void reevaluateInterrupts() {
interruptMax = -1;
for (int i = 0; i < interruptSource.length; i++) {
if (interruptSource[i] != null)
interruptMax = i;
}
}
// returns the currently serviced interrupt (vector ID)
public int getServicedInterrupt() {
return servicedInterrupt;
}
// This will be called after an interrupt have been handled
// In the main-CPU loop
public void handlePendingInterrupts() {
// By default no int. left to process...
reevaluateInterrupts();
servicedInterrupt = -1;
servicedInterruptUnit = null;
}
void profileCall(int dst, int pc) {
MapEntry function = map.getEntry(dst);
if (function == null) {
function = getFunction(map, dst);
}
profiler.profileCall(function, cpuCycles, pc);
}
void printWarning(EmulationLogger.WarningType type, int address) throws EmulationException {
String message;
switch(type) {
case MISALIGNED_READ:
message = "**** Illegal read - misaligned word from $" +
getAddressAsString(address) + " at $" + getAddressAsString(reg[PC]);
break;
case MISALIGNED_WRITE:
message = "**** Illegal write - misaligned word to $" +
getAddressAsString(address) + " at $" + getAddressAsString(reg[PC]);
break;
case ADDRESS_OUT_OF_BOUNDS_READ:
message = "**** Illegal read - out of bounds from $" +
getAddressAsString(address) + " at $" + getAddressAsString(reg[PC]);
break;
case ADDRESS_OUT_OF_BOUNDS_WRITE:
message = "**** Illegal write - out of bounds from $" +
getAddressAsString(address) + " at $" + getAddressAsString(reg[PC]);
break;
default:
message = "**** " + type + " address $" + getAddressAsString(address) +
" at $" + getAddressAsString(reg[PC]);
break;
}
logger.logw(this, type, message);
}
public void generateTrace(PrintStream out) {
/* Override if a stack trace or other additional warning info should
* be printed */
}
private int serviceInterrupt(int pc) {
int pcBefore = pc;
int spBefore = readRegister(SP);
int sp = spBefore;
int sr = readRegister(SR);
if (profiler != null) {
profiler.profileInterrupt(interruptMax, cycles);
}
if (flash.blocksCPU()) {
/* TODO: how should this error/warning be handled ?? */
throw new IllegalStateException(
"Got interrupt while flash controller blocks CPU. CPU CRASHED.");
}
// Only store stuff on irq except reset... - not sure if this is correct...
// TODO: Check what to do if reset is called!
if (interruptMax < MAX_INTERRUPT) {
// Push PC and SR to stack
// store on stack - always move 2 steps (W) even if B.
writeRegister(SP, sp = spBefore - 2);
currentSegment.write(sp, pc, AccessMode.WORD);
writeRegister(SP, sp = sp - 2);
currentSegment.write(sp, (sr & 0x0fff) | ((pc & 0xf0000) >> 4), AccessMode.WORD);
}
// Clear SR
writeRegister(SR, 0); // sr & ~CPUOFF & ~SCG1 & ~OSCOFF);
// Jump to the address specified in the interrupt vector
pc = currentSegment.read(0xfffe - (MAX_INTERRUPT - interruptMax) * 2, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc);
servicedInterrupt = interruptMax;
servicedInterruptUnit = interruptSource[servicedInterrupt];
// Flag off this interrupt - for now - as soon as RETI is
// executed things might change!
reevaluateInterrupts();
if (servicedInterrupt == MAX_INTERRUPT) {
if (debugInterrupts) System.out.println("**** Servicing RESET! => $" + getAddressAsString(pc));
internalReset();
}
// Interrupts take 6 cycles!
cycles += 6;
if (debugInterrupts) {
System.out.println("### Executing interrupt: " +
servicedInterrupt + " at "
+ pcBefore + " to " + pc +
" SP before: " + spBefore +
" Vector: " + Utils.hex16(0xfffe - (MAX_INTERRUPT - servicedInterrupt) * 2));
}
// And call the serviced routine (which can cause another interrupt)
if (servicedInterruptUnit != null) {
if (debugInterrupts) {
System.out.println("### Calling serviced interrupt on: " +
servicedInterruptUnit.getName());
}
servicedInterruptUnit.interruptServiced(servicedInterrupt);
}
return pc;
}
/* returns true if any instruction was emulated - false if CpuOff */
public int emulateOP(long maxCycles) throws EmulationException {
//System.out.println("CYCLES BEFORE: " + cycles);
int pc = readRegister(PC);
long startCycles = cycles;
// -------------------------------------------------------------------
// Interrupt processing [after the last instruction was executed]
// -------------------------------------------------------------------
if (interruptsEnabled && servicedInterrupt == -1 && interruptMax >= 0) {
pc = serviceInterrupt(pc);
}
/* Did not execute any instructions */
if (cpuOff || flash.blocksCPU()) {
// System.out.println("Jumping: " + (nextIOTickCycles - cycles));
// nextEventCycles must exist, otherwise CPU can not wake up!?
// If CPU is not active we must run the events here!!!
// this can trigger interrupts that wake the CPU
// -------------------------------------------------------------------
// Event processing - note: This can trigger IRQs!
// -------------------------------------------------------------------
/* This can flag an interrupt! */
while (cycles >= nextEventCycles) {
executeEvents();
}
if (interruptsEnabled && interruptMax > 0) {
/* can not allow for jumping to nextEventCycles since that would jump too far */
return -1;
}
if (maxCycles >= 0 && maxCycles < nextEventCycles) {
// Should it just freeze or take on extra cycle step if cycles > max?
cycles = cycles < maxCycles ? maxCycles : cycles;
} else {
cycles = nextEventCycles;
}
return -1;
}
int pcBefore = pc;
instruction = currentSegment.read(pc, AccessMode.WORD, AccessType.EXECUTE);
if (isStopping) {
// Signaled to stop the execution before performing the instruction
return -2;
}
int ext3_0 = 0;
int ext10_7 = 0;
int extSrc = 0;
int extDst = 0;
boolean repeatsInDstReg = false;
boolean wordx20 = false;
/* check for extension words */
if ((instruction & 0xf800) == 0x1800) {
extWord = instruction;
ext3_0 = instruction & 0xf; /* bit 3 - 0 - either repeat count or dest 19-16 */
ext10_7 = (instruction >> 7) & 0xf; /* bit 10 - 7 - src 19-16 */
extSrc = ext10_7 << 16;
extDst = ext3_0 << 16;
pc += 2;
// Bit 7 in the extension word indicates that the number of
// repeats is found in the register pointed to by ext3_0. If
// the bit is 0, ext3_0 contains the number of repeats. If the
// bit is 1, ext3_0 contains the register number that holds
// the number of repeats.
if ((instruction & 0x80) == 0x80) {
repeatsInDstReg = true;
}
// Bit 6 indicates whether or not the data length mode should
// be 20 bits. A one means traditional MSP430 mode; a zero
// indicates 20 bit mode. (XXX: there is a reserved data
// length mode if this bit is zero and the MSP430 instruction
// that follows the extension word also has a zero bit data
// length mode.)
wordx20 = (instruction & 0x40) == 0;
instruction = currentSegment.read(pc, AccessMode.WORD, AccessType.EXECUTE);
// System.out.println("*** Extension word!!! " + Utils.hex16(extWord) +
// " read the instruction too: " + Utils.hex16(instruction) + " at " + Utils.hex16(pc - 2));
} else {
extWord = 0;
}
op = instruction >> 12;
int sp = 0;
int sr = 0;
int rval = 0; /* register value */
int repeats = 1; /* msp430X can repeat some instructions in some cases */
boolean zeroCarry = false; /* msp430X can zero carry in repeats */
boolean word = (instruction & 0x40) == 0;
/* NOTE: there is a mode when wordx20 = true & word = true that is resereved */
AccessMode mode = wordx20 ? AccessMode.WORD20 : (word ? AccessMode.WORD : AccessMode.BYTE);
if (mode == AccessMode.WORD20) System.out.println("WORD20 not really supported...");
// Destination vars
int dstRegister = 0;
int dstAddress = -1;
boolean dstRegMode = false;
int dst = -1;
boolean write = false;
boolean updateStatus = true;
// When is PC increased probably immediately (e.g. here)?
pc += 2;
writeRegister(PC, pc);
switch (op) {
case 0:
// MSP430X - additional instructions
op = instruction & 0xf0f0;
if (!MSP430XArch)
throw new EmulationException("Executing MSP430X instruction but MCU is not a MSP430X");
// System.out.println("Executing MSP430X instruction op:" + Utils.hex16(op) +
// " ins:" + Utils.hex16(instruction) + " PC = $" + getAddressAsString(pc - 2));
int src = 0;
/* data is either bit 19-16 or src register */
int srcData = (instruction & 0x0f00) >> 8;
int dstData = (instruction & 0x000f);
boolean rrword = true;
mode = AccessMode.WORD20;
switch(op) {
// 20 bit register write
case MOVA_IND:
/* Read from address in src register (20-bit?), move to destination register (=20 bit). */
writeRegister(dstData, currentSegment.read(readRegister(srcData), AccessMode.WORD20, AccessType.READ));
updateStatus = false;
cycles += 3;
break;
case MOVA_IND_AUTOINC:
if (profiler != null && instruction == 0x0110) {
profiler.profileReturn(cpuCycles);
}
writeRegister(PC, pc);
/* read from address in register */
src = readRegister(srcData);
// System.out.println("Reading $" + getAddressAsString(src) +
// " from register: " + srcData);
dst = currentSegment.read(src, AccessMode.WORD20, AccessType.READ);
// System.out.println("Reading from mem: $" + getAddressAsString(dst));
writeRegister(srcData, src + 4);
// System.out.println("*** Writing $" + getAddressAsString(dst) + " to reg: " + dstData);
writeRegister(dstData, dst);
updateStatus = false;
cycles += 3;
break;
case MOVA_ABS2REG:
src = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc += 2);
dst = src + (srcData << 16);
//System.out.println(Utils.hex20(pc) + " MOVA &ABS Reading from $" + getAddressAsString(dst) + " to reg: " + dstData);
dst = currentSegment.read(dst, AccessMode.WORD20, AccessType.READ);
//System.out.println(" => $" + getAddressAsString(dst));
writeRegister(dstData, dst);
updateStatus = false;
cycles += 4;
break;
case MOVA_INDX2REG:
/* Read data from address in memory, indexed by source
* register, and place into destination register. */
int index = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
int indexModifier = readRegister(srcData);
if(index > 0x8000) {
index = -(0x10000 - index);
}
- if(indexModifier > 0x8000) {
- indexModifier = -(0x10000 - indexModifier);
- }
writeRegister(dstData, currentSegment.read(indexModifier + index, AccessMode.WORD20, AccessType.READ));
writeRegister(PC, pc += 2);
updateStatus = false;
cycles += 4;
break;
case MOVA_REG2ABS:
dst = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc += 2);
currentSegment.write(dst + (dstData << 16), readRegister(srcData), AccessMode.WORD20);
updateStatus = false;
cycles += 4;
break;
case MOVA_REG2INDX:
/* Read data from register, write to address in memory,
* indexed by source register. */
index = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
indexModifier = readRegister(dstData);
if(index > 0x8000) {
index = -(0x10000 - index);
}
- if(indexModifier > 0x8000) {
- indexModifier = -(0x10000 - indexModifier);
- }
currentSegment.write(indexModifier + index, readRegister(srcData), AccessMode.WORD20);
writeRegister(PC, pc += 2);
updateStatus = false;
cycles += 4;
break;
case MOVA_IMM2REG:
src = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc += 2);
dst = src + (srcData << 16);
// System.out.println("*** Writing $" + getAddressAsString(dst) + " to reg: " + dstData);
dst &= 0xfffff;
writeRegister(dstData, dst);
updateStatus = false;
cycles += 2;
break;
case ADDA_IMM:
// For all immediate instructions, the data low 16 bits of
// the data is stored in the following word (PC + 2) and
// the high 4 bits in the instruction word, which we have
// masked out as srcData.
int immData = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + (srcData << 16);
writeRegister(PC, pc += 2);
dst = readRegister(dstData) + immData;
// System.out.println("ADDA #" + Utils.hex20(immData) + " => " + Utils.hex20(dst));
dst &= 0xfffff;
writeRegister(dstData, dst);
cycles += 3;
break;
case CMPA_IMM: {
/* Status Bits N: Set if result is negative (src > dst), reset if positive (src ≤ dst)
Z: Set if result is zero (src = dst), reset otherwise (src ≠ dst)
C: Set if there is a carry from the MSB, reset otherwise
V: Set if the subtraction of a negative source operand from a positive destination
operand delivers a negative result, or if the subtraction of a positive source
operand from a negative destination operand delivers a positive result, reset
otherwise (no overflow) */
immData = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + (srcData << 16);
writeRegister(PC, pc += 2);
sr = readRegister(SR);
int destRegValue = readRegister(dstData);
sr &= ~(NEGATIVE | ZERO | CARRY | OVERFLOW);
if (destRegValue >= immData) {
sr |= CARRY;
}
if (destRegValue < immData) {
sr |= NEGATIVE;
}
if (destRegValue == immData) {
sr |= ZERO;
}
int cmpTmp = destRegValue - immData;
int b = 0x80000; // CMPA always use 20 bit data length
if (((destRegValue ^ cmpTmp) & b) == 0 &&
(((destRegValue ^ immData) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
updateStatus = false;
cycles += 3;
break;
}
case SUBA_IMM:
immData = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + (srcData << 16);
writeRegister(PC, pc += 2);
dst = readRegister(dstData) - immData;
writeRegister(dstData, dst);
cycles += 3;
break;
case MOVA_REG:
cycles += 1;
/* as = 0 since register mode */
writeRegister(dstData, readRegisterCG(srcData, 0));
break;
case CMPA_REG: {
sr = readRegister(SR);
sr &= ~(NEGATIVE | ZERO | CARRY | OVERFLOW);
int destRegValue = readRegister(dstData);
int srcRegValue = readRegisterCG(srcData, 0);
if (destRegValue >= srcRegValue) {
sr |= CARRY;
}
if (destRegValue < srcRegValue) {
sr |= NEGATIVE;
}
if (destRegValue == srcRegValue) {
sr |= ZERO;
}
int cmpTmp = destRegValue - srcRegValue;
int b = 0x80000; // CMPA always use 20 bit data length
if (((destRegValue ^ cmpTmp) & b) == 0 &&
(((destRegValue ^ srcRegValue) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
updateStatus = false;
cycles += 1;
break;
}
case ADDA_REG:
// Assume AS = 2
dst = readRegister(dstData) + readRegisterCG(srcData, 2);
writeRegister(dstData, dst);
cycles += 1;
break;
case SUBA_REG:
// Assume AS = 2
dst = readRegister(dstData) - readRegisterCG(srcData, 2);
writeRegister(dstData, dst);
cycles += 1;
break;
case RRXX_ADDR:
rrword = false;
case RRXX_WORD:
int count = ((instruction >> 10) & 0x03) + 1;
dst = readRegister(dstData);
sr = readRegister(SR);
int nxtCarry = 0;
int carry = (sr & CARRY) > 0? 1: 0;
if (rrword) {
mode = AccessMode.WORD;
dst = dst & 0xffff;
}
cycles += 1 + count;
switch(instruction & RRMASK) {
/* if word zero anything above */
case RRCM:
/* if (rrword): Rotate right through carry the 16-bit CPU register content
if (!rrword): Rotate right through carry the 20-bit CPU register content */
/* Pull the (count) lowest bits from dst - those will
* be placed in the (count) high bits of dst after the
* instruction is complete. */
int dst_low = dst & ((1 << count) - 1);
/* Grab the bit that will be in the carry flag when instruction completes. */
nxtCarry = (dst & (1 << (count + 1))) > 0? CARRY: 0;
/* Rotate dst. */
dst = dst >> (count);
/* Rotate the high bits, insert into dst. */
if (rrword) {
dst |= (dst_low << (17 - count)) | (carry << (16 - count));
} else {
dst |= (dst_low << (21 - count)) | (carry << (20 - count));
}
break;
case RRAM:
// System.out.println("RRAM executing");
/* roll in MSB from above */
/* 1 11 111 1111 needs to get in if MSB is 1 */
if ((dst & (rrword ? 0x8000 : 0x80000)) > 0) {
/* add some 1 bits above MSB if MSB is 1 */
dst = dst | (rrword ? 0xf8000 : 0xf80000);
}
dst = dst >> (count - 1);
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
break;
case RLAM:
// System.out.println("RLAM executing at " + pc);
/* just roll in "zeroes" from left */
dst = dst << (count - 1);
nxtCarry = (dst & (rrword ? 0x8000 : 0x80000)) > 0 ? CARRY : 0;
dst = dst << 1;
break;
case RRUM:
//System.out.println("RRUM executing");
/* just roll in "zeroes" from right */
dst = dst >> (count - 1);
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
break;
}
/* clear overflow - set carry according to above OP */
writeRegister(SR, (sr & ~(CARRY | OVERFLOW)) | nxtCarry);
dst = dst & (rrword ? 0xffff : 0xfffff);
writeRegister(dstData, dst);
break;
default:
System.out.println("MSP430X instruction not yet supported: " +
Utils.hex16(instruction) +
" op " + Utils.hex16(op));
throw new EmulationException("Found unsupported MSP430X instruction " +
Utils.hex16(instruction) +
" op " + Utils.hex16(op));
}
break;
case 1:
{
// -------------------------------------------------------------------
// Single operand instructions
// -------------------------------------------------------------------
// Register
dstRegister = instruction & 0xf;
/* check if this is a MSP430X CALLA instruction */
if ((op = instruction & CALLA_MASK) > RETI) {
pc = readRegister(PC);
dst = -1; /* will be -1 if not a call! */
/* do not update status after these instructions!!! */
updateStatus = false;
switch(op) {
case CALLA_REG:
// The CALLA operations increase the SP before
// address resolution!
// store on stack - always move 2 steps before resolution
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
dst = readRegister(dstRegister);
System.out.println("CALLA REG => " + Utils.hex20(dst));
cycles += 5;
break;
case CALLA_INDEX:
/* CALLA X(REG) => REG + X is the address*/
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
System.out.println("CALLA INDX: R" + dstRegister);
dst = readRegister(dstRegister);
/* what happens if wrapping here??? */
/* read the index which is from -15 bit - +15 bit. - so extend sign to 20-bit */
int v = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((v & 0x8000) != 0) {
v |= 0xf0000;
}
System.out.println("CALLA INDX: Reg = " + Utils.hex20(dst) + " INDX: " + v);
dst += v;
dst &= 0xfffff;
System.out.println("CALLA INDX => " + Utils.hex20(dst));
dst = currentSegment.read(dst, AccessMode.WORD20, AccessType.READ);
System.out.println("CALLA Read from INDX => " + Utils.hex20(dst));
cycles += 5;
pc += 2;
// System.exit(0);
break;
case CALLA_IMM:
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
dst = (dstRegister << 16) | currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
pc += 2;
cycles += 5;
break;
case CALLA_IND:
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
dstAddress = readRegister(dstRegister);
dst = currentSegment.read(dstAddress, AccessMode.WORD20, AccessType.READ);
pc += 2;
cycles += 5;
break;
case CALLA_ABS:
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
/* read the address of where the address to call is */
dst = (dstRegister << 16) | currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
dst = currentSegment.read(dst, AccessMode.WORD20, AccessType.READ);
pc += 2;
cycles += 7;
break;
default:
AccessMode type = AccessMode.WORD;
int size = 2;
sp = readRegister(SP);
/* check for PUSHM... POPM... */
switch(op & 0x1f00) {
case PUSHM_A:
type = AccessMode.WORD20;
size = 4;
cycles += 2;
case PUSHM_W:
int n = 1 + ((instruction >> 4) & 0x0f);
int regNo = instruction & 0x0f;
// System.out.println("PUSHM " + (type == AccessMode.WORD20 ? "A" : "W") +
// " n: " + n + " " + regNo + " at " + Utils.hex16(pcBefore));
/* decrease stack pointer and write n times */
for(int i = 0; i < n; i++) {
sp -= size;
cycles += 2;
currentSegment.write(sp, this.reg[regNo--], type);
// System.out.println("Saved reg: " + (regNo + 1) + " was " + reg[regNo + 1]);
/* what happens if regNo is wrapped ??? */
if (regNo < 0) regNo = 15;
}
writeRegister(SP, sp);
break;
case POPM_A:
type = AccessMode.WORD20;
size = 4;
cycles += 2;
case POPM_W:
n = 1 + ((instruction >> 4) & 0x0f);
regNo = instruction & 0x0f;
// System.out.println("POPM W " + (type == AccessMode.WORD20 ? "A" : "W") + " n: " +
// n + " " + regNo + " at " + Utils.hex16(pcBefore));
/* read and increase stack pointer n times */
for(int i = 0; i < n; i++) {
cycles += 2;
this.reg[regNo++] = currentSegment.read(sp, type, AccessType.READ);
// System.out.println("Restored reg: " + (regNo - 1) + " to " + reg[regNo - 1]);
sp += size;
/* what happens if regNo is wrapped ??? */
if (regNo > 15) regNo = 0;
}
writeRegister(SP, sp);
break;
default:
System.out.println("CALLA/PUSH/POP: mode not implemented");
throw new EmulationException("CALLA: mode not implemented "
+ Utils.hex16(instruction) + " => " + Utils.hex16(op));
}
}
// store current PC on stack. (current PC points to next instr.)
/* store 20 bits on stack (costs two words) */
if (dst != -1) {
currentSegment.write(sp, (pc >> 16) & 0xf, AccessMode.WORD);
sp = sp - 2;
currentSegment.write(sp, pc & 0xffff, AccessMode.WORD);
writeRegister(SP, sp);
writeRegister(PC, dst);
if (profiler != null) {
profileCall(dst, pc);
}
}
} else {
// Address mode of destination...
int ad = (instruction >> 4) & 3;
int nxtCarry = 0;
op = instruction & 0xff80;
if (op == PUSH || op == CALL) {
// The PUSH and CALL operations increase the SP before
// address resolution!
// store on stack - always move 2 steps (W) even if B./
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
}
if ((dstRegister == CG1 && ad > AM_INDEX) || dstRegister == CG2) {
dstRegMode = true;
cycles++;
} else {
switch(ad) {
// Operand in register!
case AM_REG:
dstRegMode = true;
cycles++;
break;
case AM_INDEX:
// TODO: needs to handle if SR is used!
rval = readRegisterCG(dstRegister, ad);
/* Support for MSP430X and below / above 64 KB */
/* if register is pointing to <64KB then it needs to be truncated to below 64 */
if (extWord != 0) {
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + extDst;
dstAddress += rval;
dstAddress &= 0xfffff;
} else if (rval <= 0xffff) {
dstAddress = (rval + currentSegment.read(pc, AccessMode.WORD, AccessType.READ)) & 0xffff;
} else {
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((dstAddress & 0x8000) > 0) {
dstAddress |= 0xf0000;
}
dstAddress += rval;
dstAddress &= 0xfffff;
}
// When is PC incremented - assuming immediately after "read"?
pc += 2;
writeRegister(PC, pc);
cycles += 4;
break;
// Indirect register
case AM_IND_REG:
dstAddress = readRegister(dstRegister);
cycles += 3;
break;
// Bugfix suggested by Matt Thompson
case AM_IND_AUTOINC:
if (dstRegister == PC) {
dstAddress = pc;
dst = currentSegment.read(dstAddress, mode != AccessMode.BYTE ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
dst += extDst;
pc += 2;
writeRegister(PC, pc);
} else {
dstAddress = readRegister(dstRegister);
writeRegister(dstRegister, dstAddress + mode.bytes); // XXX (word ? 2 : 1));
}
cycles += 3;
break;
}
}
// Perform the read
if (dstRegMode) {
dst = readRegisterCG(dstRegister, ad);
dst &= mode.mask;
/* set the repeat here! */
if (repeatsInDstReg) {
repeats = 1 + readRegister(ext3_0);
} else {
repeats = 1 + ext3_0;
}
zeroCarry = (extWord & EXTWORD_ZC) > 0;
// if (repeats > 1) {
// System.out.println("*** Repeat " + repeats + " ZeroCarry: " + zeroCarry);
// }
} else if (dst == -1) {
dst = currentSegment.read(dstAddress, mode, AccessType.READ);
}
/* TODO: test add the loop here! */
while(repeats-- > 0) {
sr = readRegister(SR);
/* always clear carry before repeat */
if (repeats >= 0) {
if (zeroCarry) {
sr = sr & ~CARRY;
//System.out.println("ZC => Cleared carry...");
}
//System.out.println("*** Repeat: " + repeats);
}
switch(op) {
case RRC:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
dst |= (sr & CARRY) > 0 ? mode.msb : 0;
//XXX if (word) {
// dst |= (sr & CARRY) > 0 ? 0x8000 : 0;
// } else if (wordx20) {
// dst |= (sr & CARRY) > 0 ? 0x80000 : 0;
// } else {
// dst |= (sr & CARRY) > 0 ? 0x80 : 0;
// }
// Indicate write to memory!!
write = true;
// Set the next carry!
writeRegister(SR, (sr & ~(CARRY | OVERFLOW)) | nxtCarry);
break;
case SWPB:
int tmp = dst;
dst = ((tmp >> 8) & 0xff) + ((tmp << 8) & 0xff00);
write = true;
break;
case RRA:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = (dst & mode.msb) | dst >> 1;
//XXX if (word) {
// dst = (dst & 0x8000) | (dst >> 1);
// } else if (wordx20) {
// dst = (dst & 0x80000) | (dst >> 1);
// } else {
// dst = (dst & 0x80) | (dst >> 1);
// }
write = true;
writeRegister(SR, (sr & ~(CARRY | OVERFLOW)) | nxtCarry);
break;
case SXT:
// Extend Sign (bit 8-15 => same as bit 7)
dst = (dst & 0x80) > 0 ? dst | 0xfff00 : dst & 0x7f;
write = true;
sr = sr & ~(CARRY | OVERFLOW);
if (dst != 0) {
sr |= CARRY;
}
writeRegister(SR, sr);
break;
case PUSH:
if (mode == AccessMode.WORD20) {
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
}
currentSegment.write(sp, dst, mode);
/* if REG or INDIRECT AUTOINC then add 2 cycles, otherwise 1 */
cycles += (ad == AM_REG || ad == AM_IND_AUTOINC) ? 2 : 1;
write = false;
updateStatus = false;
break;
case CALL:
// store current PC on stack. (current PC points to next instr.)
pc = readRegister(PC);
// memory[sp] = pc & 0xff;
// memory[sp + 1] = pc >> 8;
currentSegment.write(sp, pc, AccessMode.WORD);
writeRegister(PC, dst);
/* Additional cycles: REG => 3, AM_IND_AUTO => 2, other => 1 */
cycles += (ad == AM_REG) ? 3 : (ad == AM_IND_AUTOINC) ? 2 : 1;
/* profiler will be called during calls */
if (profiler != null) {
profileCall(dst, pc);
}
write = false;
updateStatus = false;
break;
case RETI:
// Put Top of stack to Status DstRegister (TOS -> SR)
servicedInterrupt = -1; /* needed before write to SR!!! */
sp = readRegister(SP);
sr = currentSegment.read(sp, AccessMode.WORD, AccessType.READ);
writeRegister(SR, sr & 0x0fff);
sp = sp + 2;
// writeRegister(SR, memory[sp++] + (memory[sp++] << 8));
// TOS -> PC
// writeRegister(PC, memory[sp++] + (memory[sp++] << 8));
writeRegister(PC, currentSegment.read(sp, AccessMode.WORD, AccessType.READ) | (sr & 0xf000) << 4);
sp = sp + 2;
writeRegister(SP, sp);
write = false;
updateStatus = false;
cycles += 4;
if (debugInterrupts) {
System.out.println("### RETI at " + pc + " => " + reg[PC] +
" SP after: " + reg[SP]);
}
if (profiler != null) {
profiler.profileRETI(cycles);
}
// This assumes that all interrupts will get back using RETI!
handlePendingInterrupts();
break;
default:
System.out.println("Error: Not implemented instruction:" +
Utils.hex16(instruction));
}
if (repeats > 0) {
//XXX if (word) {
// dst &= 0xffff;
// } else if (wordx20) {
// dst &= 0xfffff;
// } else {
// dst &= 0xff;
// }
dst &= mode.mask;
}
}
}
}
break;
// Jump instructions
case 2:
case 3:
// 10 bits for address for these => 0x00fc => remove 2 bits
int jmpOffset = instruction & 0x3ff;
jmpOffset = (jmpOffset & 0x200) == 0 ?
2 * jmpOffset : -(2 * (0x200 - (jmpOffset & 0x1ff)));
boolean jump = false;
// All jump takes two cycles
cycles += 2;
sr = readRegister(SR);
switch(instruction & 0xfc00) {
case JNE:
jump = (sr & ZERO) == 0;
break;
case JEQ:
jump = (sr & ZERO) > 0;
break;
case JNC:
jump = (sr & CARRY) == 0;
break;
case JC:
jump = (sr & CARRY) > 0;
break;
case JN:
jump = (sr & NEGATIVE) > 0;
break;
case JGE:
jump = (sr & NEGATIVE) > 0 == (sr & OVERFLOW) > 0;
break;
case JL:
jump = (sr & NEGATIVE) > 0 != (sr & OVERFLOW) > 0;
break;
case JMP:
jump = true;
break;
default:
logw(WarningType.EMULATION_ERROR, "Not implemented instruction: #" + Utils.binary16(instruction));
}
// Perform the Jump
if (jump) {
writeRegister(PC, pc + jmpOffset);
}
updateStatus = false;
break;
default:
// ---------------------------------------------------------------
// Double operand instructions!
// ---------------------------------------------------------------
dstRegister = instruction & 0xf;
int srcRegister = (instruction >> 8) & 0xf;
int as = (instruction >> 4) & 3;
// AD: 0 => register direct, 1 => register index, e.g. X(Rn)
dstRegMode = ((instruction >> 7) & 1) == 0;
dstAddress = -1;
int srcAddress = -1;
src = 0;
// Some CGs should be handled as registry reads only...
if ((srcRegister == CG1 && as > AM_INDEX) || srcRegister == CG2) {
src = CREG_VALUES[srcRegister - 2][as];
src &= mode.mask;
//XXX if (word) {
// src &= 0xffff;
// } else if (wordx20) {
// src &= 0xfffff;
// } else {
// src &= 0xff;
// }
cycles += dstRegMode ? 1 : 4;
} else {
switch(as) {
// Operand in register!
case AM_REG:
// CG handled above!
src = readRegister(srcRegister);
src &= mode.mask;
//XXX if (word) {
// src &= 0xffff;
// } else if (wordx20) {
// src &= 0xfffff;
// } else {
// src &= 0xff;
// }
cycles += dstRegMode ? 1 : 4;
/* add cycle if destination register = PC */
if (dstRegister == PC) cycles++;
if (dstRegMode) {
/* possible to have repeat, etc... */
/* TODO: decode the # also */
if (repeatsInDstReg) {
repeats = 1 + readRegister(ext3_0);
} else {
repeats = 1 + ext3_0;
}
zeroCarry = (extWord & EXTWORD_ZC) > 0;
}
break;
case AM_INDEX: {
// Indexed if reg != PC & CG1/CG2 - will PC be incremented?
int sval = readRegisterCG(srcRegister, as);
/* Support for MSP430X and below / above 64 KB */
/* if register is pointing to <64KB then it needs to be truncated to below 64 */
if (extWord != 0) {
srcAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + extSrc;
srcAddress += sval;
srcAddress &= 0xfffff;
} else if (sval <= 0xffff) {
srcAddress = (sval + currentSegment.read(pc, AccessMode.WORD, AccessType.READ)) & 0xffff;
} else {
srcAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((srcAddress & 0x8000) > 0) {
// Negative index
srcAddress |= 0xf0000;
}
srcAddress += sval;
srcAddress &= 0xfffff;
}
// When is PC incremented - assuming immediately after "read"?
pc += 2;
writeRegister(PC, pc);
cycles += dstRegMode ? 3 : 6;
break;
}
// Indirect register
case AM_IND_REG:
srcAddress = readRegister(srcRegister);
cycles += dstRegMode ? 2 : 5;
break;
case AM_IND_AUTOINC:
if (srcRegister == PC) {
/* PC is always handled as word */
src = currentSegment.read(pc, mode != AccessMode.BYTE ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
src += extSrc;
pc += 2;
writeRegister(PC, pc);
cycles += dstRegMode ? 2 : 5;
} else {
srcAddress = readRegister(srcRegister);
incRegister(srcRegister, mode.bytes);//XXX word ? 2 : 1);
cycles += dstRegMode ? 2 : 5;
}
/* If destination register is PC another cycle is consumed */
if (dstRegister == PC) {
cycles++;
}
break;
}
}
// Perform the read of destination!
if (dstRegMode) {
if (op != MOV) {
dst = readRegister(dstRegister);
dst &= mode.mask;
}
} else {
// PC Could have changed above!
pc = readRegister(PC);
if (dstRegister == 2) {
/* absolute mode */
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ); //memory[pc] + (memory[pc + 1] << 8);
} else {
// CG here - probably not!???
rval = readRegister(dstRegister);
/* Support for MSP430X and below / above 64 KB */
/* if register is pointing to <64KB then it needs to be truncated to below 64 */
if (rval <= 0xffff) {
dstAddress = (rval + currentSegment.read(pc, AccessMode.WORD, AccessType.READ)) & 0xffff;
} else {
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((dstAddress & 0x8000) > 0) {
dstAddress |= 0xf0000;
}
dstAddress += rval;
dstAddress &= 0xfffff;
}
}
if (op != MOV) {
dst = currentSegment.read(dstAddress, word ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
}
pc += 2;
incRegister(PC, 2);
}
// **** Perform the read...
if (srcAddress != -1) {
// if (srcAddress > 0xffff) {
// System.out.println("SrcAddress is: " + Utils.hex20(srcAddress));
// }
// srcAddress = srcAddress & 0xffff;
src = currentSegment.read(srcAddress, mode, AccessType.READ);
// src = currentSegment.read(srcAddress, word ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
// if (debug) {
// System.out.println("Reading from " + getAddressAsString(srcAddress) +
// " => " + src);
// }
}
/* TODO: test add the loop here! */
while(repeats-- > 0) {
sr = readRegister(SR);
if (repeats >= 0) {
if (zeroCarry) {
sr = sr & ~CARRY;
//System.out.println("ZC => Cleared carry...");
}
//System.out.println("*** Repeat: " + repeats);
}
int tmp = 0;
int tmpAdd = 0;
switch (op) {
case MOV: // MOV
dst = src;
write = true;
updateStatus = false;
if (instruction == RETURN && profiler != null) {
profiler.profileReturn(cpuCycles);
}
break;
// FIX THIS!!! - make SUB a separate operation so that
// it is clear that overflow flag is correct...
case SUB:
// Carry always 1 with SUB
tmpAdd = 1;
case SUBC:
// Both sub and subc does one complement (not) + 1 (or carry)
src = (src ^ 0xffff) & 0xffff;
case ADDC: // ADDC
if (op == ADDC || op == SUBC)
tmpAdd = ((sr & CARRY) > 0) ? 1 : 0;
case ADD: // ADD
// Tmp gives zero if same sign! if sign is different after -> overf.
sr &= ~(OVERFLOW | CARRY);
int b = word ? 0x8000 : (wordx20 ? 0x80000 : 0x80);
tmp = (src ^ dst) & b;
// Includes carry if carry should be added...
dst = dst + src + tmpAdd;
int b2 = word ? 0xffff : (wordx20 ? 0xfffff : 0xff);
if (dst > b2) {
sr |= CARRY;
}
// If tmp == 0 and currenly not the same sign for src & dst
if (tmp == 0 && ((src ^ dst) & b) != 0) {
sr |= OVERFLOW;
// System.out.println("OVERFLOW - ADD/SUB " + Utils.hex16(src)
// + " + " + Utils.hex16(tmpDst));
}
// System.out.println(Utils.hex16(dst) + " [SR=" +
// Utils.hex16(reg[SR]) + "]");
writeRegister(SR, sr);
write = true;
break;
case CMP: // CMP
// Set CARRY if A >= B, and it's clear if A < B
b = mode.msb;
sr = (sr & ~(CARRY | OVERFLOW)) | (dst >= src ? CARRY : 0);
tmp = (dst - src);
if (((src ^ tmp) & b) == 0 && (((src ^ dst) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
// Must set dst to the result to set the rest of the status register
dst = tmp;
break;
case DADD: // DADD
if (DEBUG)
log("DADD: Decimal add executed - result error!!!");
// Decimal add... this is wrong... each nibble is 0-9...
// So this has to be reimplemented...
dst = dst + src + ((sr & CARRY) > 0 ? 1 : 0);
write = true;
break;
case BIT: // BIT
dst = src & dst;
// Clear overflow and carry!
sr = sr & ~(CARRY | OVERFLOW);
// Set carry if result is non-zero!
if (dst != 0) {
sr |= CARRY;
}
writeRegister(SR, sr);
break;
case BIC: // BIC
// No status reg change
// System.out.println("BIC: =>" + Utils.hex16(dstAddress) + " => "
// + Utils.hex16(dst) + " AS: " + as +
// " sReg: " + srcRegister + " => " + src +
// " dReg: " + dstRegister + " => " + dst);
dst = (~src) & dst;
write = true;
updateStatus = false;
break;
case BIS: // BIS
dst = src | dst;
write = true;
updateStatus = false;
break;
case XOR: // XOR
sr = sr & ~(CARRY | OVERFLOW);
b = mode.msb; //word ? 0x8000 : (wordx20 ? 0x80000 : 0x80);
if ((src & b) != 0 && (dst & b) != 0) {
sr |= OVERFLOW;
}
dst = src ^ dst;
if (dst != 0) {
sr |= CARRY;
}
write = true;
writeRegister(SR, sr);
break;
case AND: // AND
sr = sr & ~(CARRY | OVERFLOW);
dst = src & dst;
if (dst != 0) {
sr |= CARRY;
}
write = true;
writeRegister(SR, sr);
break;
default:
String address = getAddressAsString(pc);
logw(WarningType.EMULATION_ERROR,
"DoubleOperand not implemented: op = " + Integer.toHexString(op) + " at " + address);
if (EXCEPTION_ON_BAD_OPERATION) {
EmulationException ex = new EmulationException("Bad operation: $" + Integer.toHexString(op) + " at $" + address);
ex.initCause(new Throwable("" + pc));
throw ex;
}
} /* after switch(op) */
/* If we have the same register as dst and src then copy here to get input
* in next loop
*/
if (repeats > 0 && srcRegister == dstRegister) {
src = dst;
src &= mode.mask;
//XXX if (word) {
// src &= 0xffff;
// } else if (wordx20) {
// src &= 0xfffff;
// } else {
// src &= 0xff;
// }
}
}
}
/* Processing after each instruction */
dst &= mode.mask;
//XXX if (word) {
// dst &= 0xffff;
// } else if (wordx20) {
// dst &= 0xfffff;
// } else {
// dst &= 0xff;
// }
if (write) {
if (dstRegMode) {
writeRegister(dstRegister, dst);
} else {
dstAddress &= 0xffff;
currentSegment.write(dstAddress, dst, mode);
}
}
if (updateStatus) {
// Update the Zero and Negative status!
// Carry and overflow must be set separately!
sr = readRegister(SR);
sr = (sr & ~(ZERO | NEGATIVE)) |
((dst == 0) ? ZERO : 0) | ((dst & mode.msb) > 0 ? NEGATIVE : 0);
//XXX (word ? ((dst & 0x8000) > 0 ? NEGATIVE : 0) :
// (wordx20 ? ((dst & 0x80000) > 0 ? NEGATIVE : 0) :
// ((dst & 0x80) > 0 ? NEGATIVE : 0)));
writeRegister(SR, sr);
}
//System.out.println("CYCLES AFTER: " + cycles);
// -------------------------------------------------------------------
// Event processing (when CPU is awake)
// -------------------------------------------------------------------
while (cycles >= nextEventCycles) {
executeEvents();
}
cpuCycles += cycles - startCycles;
/* return the address that was executed */
return pcBefore;
}
public int getModeMax() {
return MODE_MAX;
}
MapEntry getFunction(MapTable map, int address) {
MapEntry function = new MapEntry(MapEntry.TYPE.function, address, 0,
"fkn at $" + getAddressAsString(address), null, true);
map.setEntry(function);
return function;
}
public Memory getMemory() {
return currentSegment;
}
public int getPC() {
return reg[PC];
}
public int getSR() {
return reg[SR];
}
public int getSP() {
return reg[SP];
}
public int getRegister(int register) {
return reg[register];
}
public String getAddressAsString(int addr) {
return config.getAddressAsString(addr);
}
public int getConfiguration(int parameter) {
return 0;
}
public String info() {
StringBuilder buf = new StringBuilder();
buf.append(" Mode: " + getModeName(getMode())
+ " ACLK: " + aclkFrq + " Hz SMCLK: " + smclkFrq + " Hz\n"
+ " Cycles: " + cycles + " CPU Cycles: " + cpuCycles
+ " Time: " + (long)getTimeMillis() + " msec\n");
buf.append(" Interrupt enabled: " + interruptsEnabled + " HighestInterrupt: " + interruptMax);
for (int i = 0; i < MAX_INTERRUPT; i++) {
int value = currentSegment.get(0xfffe - i * 2, AccessMode.WORD);
if (value != 0xffff) {
buf.append(" Vector " + (MAX_INTERRUPT - i) + " at $"
+ Utils.hex16(0xfffe - i * 2) + " -> $"
+ Utils.hex16(value) + "\n");
}
}
return buf.toString();
}
}
| false | true | public int emulateOP(long maxCycles) throws EmulationException {
//System.out.println("CYCLES BEFORE: " + cycles);
int pc = readRegister(PC);
long startCycles = cycles;
// -------------------------------------------------------------------
// Interrupt processing [after the last instruction was executed]
// -------------------------------------------------------------------
if (interruptsEnabled && servicedInterrupt == -1 && interruptMax >= 0) {
pc = serviceInterrupt(pc);
}
/* Did not execute any instructions */
if (cpuOff || flash.blocksCPU()) {
// System.out.println("Jumping: " + (nextIOTickCycles - cycles));
// nextEventCycles must exist, otherwise CPU can not wake up!?
// If CPU is not active we must run the events here!!!
// this can trigger interrupts that wake the CPU
// -------------------------------------------------------------------
// Event processing - note: This can trigger IRQs!
// -------------------------------------------------------------------
/* This can flag an interrupt! */
while (cycles >= nextEventCycles) {
executeEvents();
}
if (interruptsEnabled && interruptMax > 0) {
/* can not allow for jumping to nextEventCycles since that would jump too far */
return -1;
}
if (maxCycles >= 0 && maxCycles < nextEventCycles) {
// Should it just freeze or take on extra cycle step if cycles > max?
cycles = cycles < maxCycles ? maxCycles : cycles;
} else {
cycles = nextEventCycles;
}
return -1;
}
int pcBefore = pc;
instruction = currentSegment.read(pc, AccessMode.WORD, AccessType.EXECUTE);
if (isStopping) {
// Signaled to stop the execution before performing the instruction
return -2;
}
int ext3_0 = 0;
int ext10_7 = 0;
int extSrc = 0;
int extDst = 0;
boolean repeatsInDstReg = false;
boolean wordx20 = false;
/* check for extension words */
if ((instruction & 0xf800) == 0x1800) {
extWord = instruction;
ext3_0 = instruction & 0xf; /* bit 3 - 0 - either repeat count or dest 19-16 */
ext10_7 = (instruction >> 7) & 0xf; /* bit 10 - 7 - src 19-16 */
extSrc = ext10_7 << 16;
extDst = ext3_0 << 16;
pc += 2;
// Bit 7 in the extension word indicates that the number of
// repeats is found in the register pointed to by ext3_0. If
// the bit is 0, ext3_0 contains the number of repeats. If the
// bit is 1, ext3_0 contains the register number that holds
// the number of repeats.
if ((instruction & 0x80) == 0x80) {
repeatsInDstReg = true;
}
// Bit 6 indicates whether or not the data length mode should
// be 20 bits. A one means traditional MSP430 mode; a zero
// indicates 20 bit mode. (XXX: there is a reserved data
// length mode if this bit is zero and the MSP430 instruction
// that follows the extension word also has a zero bit data
// length mode.)
wordx20 = (instruction & 0x40) == 0;
instruction = currentSegment.read(pc, AccessMode.WORD, AccessType.EXECUTE);
// System.out.println("*** Extension word!!! " + Utils.hex16(extWord) +
// " read the instruction too: " + Utils.hex16(instruction) + " at " + Utils.hex16(pc - 2));
} else {
extWord = 0;
}
op = instruction >> 12;
int sp = 0;
int sr = 0;
int rval = 0; /* register value */
int repeats = 1; /* msp430X can repeat some instructions in some cases */
boolean zeroCarry = false; /* msp430X can zero carry in repeats */
boolean word = (instruction & 0x40) == 0;
/* NOTE: there is a mode when wordx20 = true & word = true that is resereved */
AccessMode mode = wordx20 ? AccessMode.WORD20 : (word ? AccessMode.WORD : AccessMode.BYTE);
if (mode == AccessMode.WORD20) System.out.println("WORD20 not really supported...");
// Destination vars
int dstRegister = 0;
int dstAddress = -1;
boolean dstRegMode = false;
int dst = -1;
boolean write = false;
boolean updateStatus = true;
// When is PC increased probably immediately (e.g. here)?
pc += 2;
writeRegister(PC, pc);
switch (op) {
case 0:
// MSP430X - additional instructions
op = instruction & 0xf0f0;
if (!MSP430XArch)
throw new EmulationException("Executing MSP430X instruction but MCU is not a MSP430X");
// System.out.println("Executing MSP430X instruction op:" + Utils.hex16(op) +
// " ins:" + Utils.hex16(instruction) + " PC = $" + getAddressAsString(pc - 2));
int src = 0;
/* data is either bit 19-16 or src register */
int srcData = (instruction & 0x0f00) >> 8;
int dstData = (instruction & 0x000f);
boolean rrword = true;
mode = AccessMode.WORD20;
switch(op) {
// 20 bit register write
case MOVA_IND:
/* Read from address in src register (20-bit?), move to destination register (=20 bit). */
writeRegister(dstData, currentSegment.read(readRegister(srcData), AccessMode.WORD20, AccessType.READ));
updateStatus = false;
cycles += 3;
break;
case MOVA_IND_AUTOINC:
if (profiler != null && instruction == 0x0110) {
profiler.profileReturn(cpuCycles);
}
writeRegister(PC, pc);
/* read from address in register */
src = readRegister(srcData);
// System.out.println("Reading $" + getAddressAsString(src) +
// " from register: " + srcData);
dst = currentSegment.read(src, AccessMode.WORD20, AccessType.READ);
// System.out.println("Reading from mem: $" + getAddressAsString(dst));
writeRegister(srcData, src + 4);
// System.out.println("*** Writing $" + getAddressAsString(dst) + " to reg: " + dstData);
writeRegister(dstData, dst);
updateStatus = false;
cycles += 3;
break;
case MOVA_ABS2REG:
src = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc += 2);
dst = src + (srcData << 16);
//System.out.println(Utils.hex20(pc) + " MOVA &ABS Reading from $" + getAddressAsString(dst) + " to reg: " + dstData);
dst = currentSegment.read(dst, AccessMode.WORD20, AccessType.READ);
//System.out.println(" => $" + getAddressAsString(dst));
writeRegister(dstData, dst);
updateStatus = false;
cycles += 4;
break;
case MOVA_INDX2REG:
/* Read data from address in memory, indexed by source
* register, and place into destination register. */
int index = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
int indexModifier = readRegister(srcData);
if(index > 0x8000) {
index = -(0x10000 - index);
}
if(indexModifier > 0x8000) {
indexModifier = -(0x10000 - indexModifier);
}
writeRegister(dstData, currentSegment.read(indexModifier + index, AccessMode.WORD20, AccessType.READ));
writeRegister(PC, pc += 2);
updateStatus = false;
cycles += 4;
break;
case MOVA_REG2ABS:
dst = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc += 2);
currentSegment.write(dst + (dstData << 16), readRegister(srcData), AccessMode.WORD20);
updateStatus = false;
cycles += 4;
break;
case MOVA_REG2INDX:
/* Read data from register, write to address in memory,
* indexed by source register. */
index = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
indexModifier = readRegister(dstData);
if(index > 0x8000) {
index = -(0x10000 - index);
}
if(indexModifier > 0x8000) {
indexModifier = -(0x10000 - indexModifier);
}
currentSegment.write(indexModifier + index, readRegister(srcData), AccessMode.WORD20);
writeRegister(PC, pc += 2);
updateStatus = false;
cycles += 4;
break;
case MOVA_IMM2REG:
src = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc += 2);
dst = src + (srcData << 16);
// System.out.println("*** Writing $" + getAddressAsString(dst) + " to reg: " + dstData);
dst &= 0xfffff;
writeRegister(dstData, dst);
updateStatus = false;
cycles += 2;
break;
case ADDA_IMM:
// For all immediate instructions, the data low 16 bits of
// the data is stored in the following word (PC + 2) and
// the high 4 bits in the instruction word, which we have
// masked out as srcData.
int immData = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + (srcData << 16);
writeRegister(PC, pc += 2);
dst = readRegister(dstData) + immData;
// System.out.println("ADDA #" + Utils.hex20(immData) + " => " + Utils.hex20(dst));
dst &= 0xfffff;
writeRegister(dstData, dst);
cycles += 3;
break;
case CMPA_IMM: {
/* Status Bits N: Set if result is negative (src > dst), reset if positive (src ≤ dst)
Z: Set if result is zero (src = dst), reset otherwise (src ≠ dst)
C: Set if there is a carry from the MSB, reset otherwise
V: Set if the subtraction of a negative source operand from a positive destination
operand delivers a negative result, or if the subtraction of a positive source
operand from a negative destination operand delivers a positive result, reset
otherwise (no overflow) */
immData = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + (srcData << 16);
writeRegister(PC, pc += 2);
sr = readRegister(SR);
int destRegValue = readRegister(dstData);
sr &= ~(NEGATIVE | ZERO | CARRY | OVERFLOW);
if (destRegValue >= immData) {
sr |= CARRY;
}
if (destRegValue < immData) {
sr |= NEGATIVE;
}
if (destRegValue == immData) {
sr |= ZERO;
}
int cmpTmp = destRegValue - immData;
int b = 0x80000; // CMPA always use 20 bit data length
if (((destRegValue ^ cmpTmp) & b) == 0 &&
(((destRegValue ^ immData) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
updateStatus = false;
cycles += 3;
break;
}
case SUBA_IMM:
immData = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + (srcData << 16);
writeRegister(PC, pc += 2);
dst = readRegister(dstData) - immData;
writeRegister(dstData, dst);
cycles += 3;
break;
case MOVA_REG:
cycles += 1;
/* as = 0 since register mode */
writeRegister(dstData, readRegisterCG(srcData, 0));
break;
case CMPA_REG: {
sr = readRegister(SR);
sr &= ~(NEGATIVE | ZERO | CARRY | OVERFLOW);
int destRegValue = readRegister(dstData);
int srcRegValue = readRegisterCG(srcData, 0);
if (destRegValue >= srcRegValue) {
sr |= CARRY;
}
if (destRegValue < srcRegValue) {
sr |= NEGATIVE;
}
if (destRegValue == srcRegValue) {
sr |= ZERO;
}
int cmpTmp = destRegValue - srcRegValue;
int b = 0x80000; // CMPA always use 20 bit data length
if (((destRegValue ^ cmpTmp) & b) == 0 &&
(((destRegValue ^ srcRegValue) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
updateStatus = false;
cycles += 1;
break;
}
case ADDA_REG:
// Assume AS = 2
dst = readRegister(dstData) + readRegisterCG(srcData, 2);
writeRegister(dstData, dst);
cycles += 1;
break;
case SUBA_REG:
// Assume AS = 2
dst = readRegister(dstData) - readRegisterCG(srcData, 2);
writeRegister(dstData, dst);
cycles += 1;
break;
case RRXX_ADDR:
rrword = false;
case RRXX_WORD:
int count = ((instruction >> 10) & 0x03) + 1;
dst = readRegister(dstData);
sr = readRegister(SR);
int nxtCarry = 0;
int carry = (sr & CARRY) > 0? 1: 0;
if (rrword) {
mode = AccessMode.WORD;
dst = dst & 0xffff;
}
cycles += 1 + count;
switch(instruction & RRMASK) {
/* if word zero anything above */
case RRCM:
/* if (rrword): Rotate right through carry the 16-bit CPU register content
if (!rrword): Rotate right through carry the 20-bit CPU register content */
/* Pull the (count) lowest bits from dst - those will
* be placed in the (count) high bits of dst after the
* instruction is complete. */
int dst_low = dst & ((1 << count) - 1);
/* Grab the bit that will be in the carry flag when instruction completes. */
nxtCarry = (dst & (1 << (count + 1))) > 0? CARRY: 0;
/* Rotate dst. */
dst = dst >> (count);
/* Rotate the high bits, insert into dst. */
if (rrword) {
dst |= (dst_low << (17 - count)) | (carry << (16 - count));
} else {
dst |= (dst_low << (21 - count)) | (carry << (20 - count));
}
break;
case RRAM:
// System.out.println("RRAM executing");
/* roll in MSB from above */
/* 1 11 111 1111 needs to get in if MSB is 1 */
if ((dst & (rrword ? 0x8000 : 0x80000)) > 0) {
/* add some 1 bits above MSB if MSB is 1 */
dst = dst | (rrword ? 0xf8000 : 0xf80000);
}
dst = dst >> (count - 1);
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
break;
case RLAM:
// System.out.println("RLAM executing at " + pc);
/* just roll in "zeroes" from left */
dst = dst << (count - 1);
nxtCarry = (dst & (rrword ? 0x8000 : 0x80000)) > 0 ? CARRY : 0;
dst = dst << 1;
break;
case RRUM:
//System.out.println("RRUM executing");
/* just roll in "zeroes" from right */
dst = dst >> (count - 1);
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
break;
}
/* clear overflow - set carry according to above OP */
writeRegister(SR, (sr & ~(CARRY | OVERFLOW)) | nxtCarry);
dst = dst & (rrword ? 0xffff : 0xfffff);
writeRegister(dstData, dst);
break;
default:
System.out.println("MSP430X instruction not yet supported: " +
Utils.hex16(instruction) +
" op " + Utils.hex16(op));
throw new EmulationException("Found unsupported MSP430X instruction " +
Utils.hex16(instruction) +
" op " + Utils.hex16(op));
}
break;
case 1:
{
// -------------------------------------------------------------------
// Single operand instructions
// -------------------------------------------------------------------
// Register
dstRegister = instruction & 0xf;
/* check if this is a MSP430X CALLA instruction */
if ((op = instruction & CALLA_MASK) > RETI) {
pc = readRegister(PC);
dst = -1; /* will be -1 if not a call! */
/* do not update status after these instructions!!! */
updateStatus = false;
switch(op) {
case CALLA_REG:
// The CALLA operations increase the SP before
// address resolution!
// store on stack - always move 2 steps before resolution
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
dst = readRegister(dstRegister);
System.out.println("CALLA REG => " + Utils.hex20(dst));
cycles += 5;
break;
case CALLA_INDEX:
/* CALLA X(REG) => REG + X is the address*/
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
System.out.println("CALLA INDX: R" + dstRegister);
dst = readRegister(dstRegister);
/* what happens if wrapping here??? */
/* read the index which is from -15 bit - +15 bit. - so extend sign to 20-bit */
int v = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((v & 0x8000) != 0) {
v |= 0xf0000;
}
System.out.println("CALLA INDX: Reg = " + Utils.hex20(dst) + " INDX: " + v);
dst += v;
dst &= 0xfffff;
System.out.println("CALLA INDX => " + Utils.hex20(dst));
dst = currentSegment.read(dst, AccessMode.WORD20, AccessType.READ);
System.out.println("CALLA Read from INDX => " + Utils.hex20(dst));
cycles += 5;
pc += 2;
// System.exit(0);
break;
case CALLA_IMM:
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
dst = (dstRegister << 16) | currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
pc += 2;
cycles += 5;
break;
case CALLA_IND:
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
dstAddress = readRegister(dstRegister);
dst = currentSegment.read(dstAddress, AccessMode.WORD20, AccessType.READ);
pc += 2;
cycles += 5;
break;
case CALLA_ABS:
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
/* read the address of where the address to call is */
dst = (dstRegister << 16) | currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
dst = currentSegment.read(dst, AccessMode.WORD20, AccessType.READ);
pc += 2;
cycles += 7;
break;
default:
AccessMode type = AccessMode.WORD;
int size = 2;
sp = readRegister(SP);
/* check for PUSHM... POPM... */
switch(op & 0x1f00) {
case PUSHM_A:
type = AccessMode.WORD20;
size = 4;
cycles += 2;
case PUSHM_W:
int n = 1 + ((instruction >> 4) & 0x0f);
int regNo = instruction & 0x0f;
// System.out.println("PUSHM " + (type == AccessMode.WORD20 ? "A" : "W") +
// " n: " + n + " " + regNo + " at " + Utils.hex16(pcBefore));
/* decrease stack pointer and write n times */
for(int i = 0; i < n; i++) {
sp -= size;
cycles += 2;
currentSegment.write(sp, this.reg[regNo--], type);
// System.out.println("Saved reg: " + (regNo + 1) + " was " + reg[regNo + 1]);
/* what happens if regNo is wrapped ??? */
if (regNo < 0) regNo = 15;
}
writeRegister(SP, sp);
break;
case POPM_A:
type = AccessMode.WORD20;
size = 4;
cycles += 2;
case POPM_W:
n = 1 + ((instruction >> 4) & 0x0f);
regNo = instruction & 0x0f;
// System.out.println("POPM W " + (type == AccessMode.WORD20 ? "A" : "W") + " n: " +
// n + " " + regNo + " at " + Utils.hex16(pcBefore));
/* read and increase stack pointer n times */
for(int i = 0; i < n; i++) {
cycles += 2;
this.reg[regNo++] = currentSegment.read(sp, type, AccessType.READ);
// System.out.println("Restored reg: " + (regNo - 1) + " to " + reg[regNo - 1]);
sp += size;
/* what happens if regNo is wrapped ??? */
if (regNo > 15) regNo = 0;
}
writeRegister(SP, sp);
break;
default:
System.out.println("CALLA/PUSH/POP: mode not implemented");
throw new EmulationException("CALLA: mode not implemented "
+ Utils.hex16(instruction) + " => " + Utils.hex16(op));
}
}
// store current PC on stack. (current PC points to next instr.)
/* store 20 bits on stack (costs two words) */
if (dst != -1) {
currentSegment.write(sp, (pc >> 16) & 0xf, AccessMode.WORD);
sp = sp - 2;
currentSegment.write(sp, pc & 0xffff, AccessMode.WORD);
writeRegister(SP, sp);
writeRegister(PC, dst);
if (profiler != null) {
profileCall(dst, pc);
}
}
} else {
// Address mode of destination...
int ad = (instruction >> 4) & 3;
int nxtCarry = 0;
op = instruction & 0xff80;
if (op == PUSH || op == CALL) {
// The PUSH and CALL operations increase the SP before
// address resolution!
// store on stack - always move 2 steps (W) even if B./
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
}
if ((dstRegister == CG1 && ad > AM_INDEX) || dstRegister == CG2) {
dstRegMode = true;
cycles++;
} else {
switch(ad) {
// Operand in register!
case AM_REG:
dstRegMode = true;
cycles++;
break;
case AM_INDEX:
// TODO: needs to handle if SR is used!
rval = readRegisterCG(dstRegister, ad);
/* Support for MSP430X and below / above 64 KB */
/* if register is pointing to <64KB then it needs to be truncated to below 64 */
if (extWord != 0) {
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + extDst;
dstAddress += rval;
dstAddress &= 0xfffff;
} else if (rval <= 0xffff) {
dstAddress = (rval + currentSegment.read(pc, AccessMode.WORD, AccessType.READ)) & 0xffff;
} else {
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((dstAddress & 0x8000) > 0) {
dstAddress |= 0xf0000;
}
dstAddress += rval;
dstAddress &= 0xfffff;
}
// When is PC incremented - assuming immediately after "read"?
pc += 2;
writeRegister(PC, pc);
cycles += 4;
break;
// Indirect register
case AM_IND_REG:
dstAddress = readRegister(dstRegister);
cycles += 3;
break;
// Bugfix suggested by Matt Thompson
case AM_IND_AUTOINC:
if (dstRegister == PC) {
dstAddress = pc;
dst = currentSegment.read(dstAddress, mode != AccessMode.BYTE ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
dst += extDst;
pc += 2;
writeRegister(PC, pc);
} else {
dstAddress = readRegister(dstRegister);
writeRegister(dstRegister, dstAddress + mode.bytes); // XXX (word ? 2 : 1));
}
cycles += 3;
break;
}
}
// Perform the read
if (dstRegMode) {
dst = readRegisterCG(dstRegister, ad);
dst &= mode.mask;
/* set the repeat here! */
if (repeatsInDstReg) {
repeats = 1 + readRegister(ext3_0);
} else {
repeats = 1 + ext3_0;
}
zeroCarry = (extWord & EXTWORD_ZC) > 0;
// if (repeats > 1) {
// System.out.println("*** Repeat " + repeats + " ZeroCarry: " + zeroCarry);
// }
} else if (dst == -1) {
dst = currentSegment.read(dstAddress, mode, AccessType.READ);
}
/* TODO: test add the loop here! */
while(repeats-- > 0) {
sr = readRegister(SR);
/* always clear carry before repeat */
if (repeats >= 0) {
if (zeroCarry) {
sr = sr & ~CARRY;
//System.out.println("ZC => Cleared carry...");
}
//System.out.println("*** Repeat: " + repeats);
}
switch(op) {
case RRC:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
dst |= (sr & CARRY) > 0 ? mode.msb : 0;
//XXX if (word) {
// dst |= (sr & CARRY) > 0 ? 0x8000 : 0;
// } else if (wordx20) {
// dst |= (sr & CARRY) > 0 ? 0x80000 : 0;
// } else {
// dst |= (sr & CARRY) > 0 ? 0x80 : 0;
// }
// Indicate write to memory!!
write = true;
// Set the next carry!
writeRegister(SR, (sr & ~(CARRY | OVERFLOW)) | nxtCarry);
break;
case SWPB:
int tmp = dst;
dst = ((tmp >> 8) & 0xff) + ((tmp << 8) & 0xff00);
write = true;
break;
case RRA:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = (dst & mode.msb) | dst >> 1;
//XXX if (word) {
// dst = (dst & 0x8000) | (dst >> 1);
// } else if (wordx20) {
// dst = (dst & 0x80000) | (dst >> 1);
// } else {
// dst = (dst & 0x80) | (dst >> 1);
// }
write = true;
writeRegister(SR, (sr & ~(CARRY | OVERFLOW)) | nxtCarry);
break;
case SXT:
// Extend Sign (bit 8-15 => same as bit 7)
dst = (dst & 0x80) > 0 ? dst | 0xfff00 : dst & 0x7f;
write = true;
sr = sr & ~(CARRY | OVERFLOW);
if (dst != 0) {
sr |= CARRY;
}
writeRegister(SR, sr);
break;
case PUSH:
if (mode == AccessMode.WORD20) {
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
}
currentSegment.write(sp, dst, mode);
/* if REG or INDIRECT AUTOINC then add 2 cycles, otherwise 1 */
cycles += (ad == AM_REG || ad == AM_IND_AUTOINC) ? 2 : 1;
write = false;
updateStatus = false;
break;
case CALL:
// store current PC on stack. (current PC points to next instr.)
pc = readRegister(PC);
// memory[sp] = pc & 0xff;
// memory[sp + 1] = pc >> 8;
currentSegment.write(sp, pc, AccessMode.WORD);
writeRegister(PC, dst);
/* Additional cycles: REG => 3, AM_IND_AUTO => 2, other => 1 */
cycles += (ad == AM_REG) ? 3 : (ad == AM_IND_AUTOINC) ? 2 : 1;
/* profiler will be called during calls */
if (profiler != null) {
profileCall(dst, pc);
}
write = false;
updateStatus = false;
break;
case RETI:
// Put Top of stack to Status DstRegister (TOS -> SR)
servicedInterrupt = -1; /* needed before write to SR!!! */
sp = readRegister(SP);
sr = currentSegment.read(sp, AccessMode.WORD, AccessType.READ);
writeRegister(SR, sr & 0x0fff);
sp = sp + 2;
// writeRegister(SR, memory[sp++] + (memory[sp++] << 8));
// TOS -> PC
// writeRegister(PC, memory[sp++] + (memory[sp++] << 8));
writeRegister(PC, currentSegment.read(sp, AccessMode.WORD, AccessType.READ) | (sr & 0xf000) << 4);
sp = sp + 2;
writeRegister(SP, sp);
write = false;
updateStatus = false;
cycles += 4;
if (debugInterrupts) {
System.out.println("### RETI at " + pc + " => " + reg[PC] +
" SP after: " + reg[SP]);
}
if (profiler != null) {
profiler.profileRETI(cycles);
}
// This assumes that all interrupts will get back using RETI!
handlePendingInterrupts();
break;
default:
System.out.println("Error: Not implemented instruction:" +
Utils.hex16(instruction));
}
if (repeats > 0) {
//XXX if (word) {
// dst &= 0xffff;
// } else if (wordx20) {
// dst &= 0xfffff;
// } else {
// dst &= 0xff;
// }
dst &= mode.mask;
}
}
}
}
break;
// Jump instructions
case 2:
case 3:
// 10 bits for address for these => 0x00fc => remove 2 bits
int jmpOffset = instruction & 0x3ff;
jmpOffset = (jmpOffset & 0x200) == 0 ?
2 * jmpOffset : -(2 * (0x200 - (jmpOffset & 0x1ff)));
boolean jump = false;
// All jump takes two cycles
cycles += 2;
sr = readRegister(SR);
switch(instruction & 0xfc00) {
case JNE:
jump = (sr & ZERO) == 0;
break;
case JEQ:
jump = (sr & ZERO) > 0;
break;
case JNC:
jump = (sr & CARRY) == 0;
break;
case JC:
jump = (sr & CARRY) > 0;
break;
case JN:
jump = (sr & NEGATIVE) > 0;
break;
case JGE:
jump = (sr & NEGATIVE) > 0 == (sr & OVERFLOW) > 0;
break;
case JL:
jump = (sr & NEGATIVE) > 0 != (sr & OVERFLOW) > 0;
break;
case JMP:
jump = true;
break;
default:
logw(WarningType.EMULATION_ERROR, "Not implemented instruction: #" + Utils.binary16(instruction));
}
// Perform the Jump
if (jump) {
writeRegister(PC, pc + jmpOffset);
}
updateStatus = false;
break;
default:
// ---------------------------------------------------------------
// Double operand instructions!
// ---------------------------------------------------------------
dstRegister = instruction & 0xf;
int srcRegister = (instruction >> 8) & 0xf;
int as = (instruction >> 4) & 3;
// AD: 0 => register direct, 1 => register index, e.g. X(Rn)
dstRegMode = ((instruction >> 7) & 1) == 0;
dstAddress = -1;
int srcAddress = -1;
src = 0;
// Some CGs should be handled as registry reads only...
if ((srcRegister == CG1 && as > AM_INDEX) || srcRegister == CG2) {
src = CREG_VALUES[srcRegister - 2][as];
src &= mode.mask;
//XXX if (word) {
// src &= 0xffff;
// } else if (wordx20) {
// src &= 0xfffff;
// } else {
// src &= 0xff;
// }
cycles += dstRegMode ? 1 : 4;
} else {
switch(as) {
// Operand in register!
case AM_REG:
// CG handled above!
src = readRegister(srcRegister);
src &= mode.mask;
//XXX if (word) {
// src &= 0xffff;
// } else if (wordx20) {
// src &= 0xfffff;
// } else {
// src &= 0xff;
// }
cycles += dstRegMode ? 1 : 4;
/* add cycle if destination register = PC */
if (dstRegister == PC) cycles++;
if (dstRegMode) {
/* possible to have repeat, etc... */
/* TODO: decode the # also */
if (repeatsInDstReg) {
repeats = 1 + readRegister(ext3_0);
} else {
repeats = 1 + ext3_0;
}
zeroCarry = (extWord & EXTWORD_ZC) > 0;
}
break;
case AM_INDEX: {
// Indexed if reg != PC & CG1/CG2 - will PC be incremented?
int sval = readRegisterCG(srcRegister, as);
/* Support for MSP430X and below / above 64 KB */
/* if register is pointing to <64KB then it needs to be truncated to below 64 */
if (extWord != 0) {
srcAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + extSrc;
srcAddress += sval;
srcAddress &= 0xfffff;
} else if (sval <= 0xffff) {
srcAddress = (sval + currentSegment.read(pc, AccessMode.WORD, AccessType.READ)) & 0xffff;
} else {
srcAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((srcAddress & 0x8000) > 0) {
// Negative index
srcAddress |= 0xf0000;
}
srcAddress += sval;
srcAddress &= 0xfffff;
}
// When is PC incremented - assuming immediately after "read"?
pc += 2;
writeRegister(PC, pc);
cycles += dstRegMode ? 3 : 6;
break;
}
// Indirect register
case AM_IND_REG:
srcAddress = readRegister(srcRegister);
cycles += dstRegMode ? 2 : 5;
break;
case AM_IND_AUTOINC:
if (srcRegister == PC) {
/* PC is always handled as word */
src = currentSegment.read(pc, mode != AccessMode.BYTE ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
src += extSrc;
pc += 2;
writeRegister(PC, pc);
cycles += dstRegMode ? 2 : 5;
} else {
srcAddress = readRegister(srcRegister);
incRegister(srcRegister, mode.bytes);//XXX word ? 2 : 1);
cycles += dstRegMode ? 2 : 5;
}
/* If destination register is PC another cycle is consumed */
if (dstRegister == PC) {
cycles++;
}
break;
}
}
// Perform the read of destination!
if (dstRegMode) {
if (op != MOV) {
dst = readRegister(dstRegister);
dst &= mode.mask;
}
} else {
// PC Could have changed above!
pc = readRegister(PC);
if (dstRegister == 2) {
/* absolute mode */
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ); //memory[pc] + (memory[pc + 1] << 8);
} else {
// CG here - probably not!???
rval = readRegister(dstRegister);
/* Support for MSP430X and below / above 64 KB */
/* if register is pointing to <64KB then it needs to be truncated to below 64 */
if (rval <= 0xffff) {
dstAddress = (rval + currentSegment.read(pc, AccessMode.WORD, AccessType.READ)) & 0xffff;
} else {
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((dstAddress & 0x8000) > 0) {
dstAddress |= 0xf0000;
}
dstAddress += rval;
dstAddress &= 0xfffff;
}
}
if (op != MOV) {
dst = currentSegment.read(dstAddress, word ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
}
pc += 2;
incRegister(PC, 2);
}
// **** Perform the read...
if (srcAddress != -1) {
// if (srcAddress > 0xffff) {
// System.out.println("SrcAddress is: " + Utils.hex20(srcAddress));
// }
// srcAddress = srcAddress & 0xffff;
src = currentSegment.read(srcAddress, mode, AccessType.READ);
// src = currentSegment.read(srcAddress, word ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
// if (debug) {
// System.out.println("Reading from " + getAddressAsString(srcAddress) +
// " => " + src);
// }
}
/* TODO: test add the loop here! */
while(repeats-- > 0) {
sr = readRegister(SR);
if (repeats >= 0) {
if (zeroCarry) {
sr = sr & ~CARRY;
//System.out.println("ZC => Cleared carry...");
}
//System.out.println("*** Repeat: " + repeats);
}
int tmp = 0;
int tmpAdd = 0;
switch (op) {
case MOV: // MOV
dst = src;
write = true;
updateStatus = false;
if (instruction == RETURN && profiler != null) {
profiler.profileReturn(cpuCycles);
}
break;
// FIX THIS!!! - make SUB a separate operation so that
// it is clear that overflow flag is correct...
case SUB:
// Carry always 1 with SUB
tmpAdd = 1;
case SUBC:
// Both sub and subc does one complement (not) + 1 (or carry)
src = (src ^ 0xffff) & 0xffff;
case ADDC: // ADDC
if (op == ADDC || op == SUBC)
tmpAdd = ((sr & CARRY) > 0) ? 1 : 0;
case ADD: // ADD
// Tmp gives zero if same sign! if sign is different after -> overf.
sr &= ~(OVERFLOW | CARRY);
int b = word ? 0x8000 : (wordx20 ? 0x80000 : 0x80);
tmp = (src ^ dst) & b;
// Includes carry if carry should be added...
dst = dst + src + tmpAdd;
int b2 = word ? 0xffff : (wordx20 ? 0xfffff : 0xff);
if (dst > b2) {
sr |= CARRY;
}
// If tmp == 0 and currenly not the same sign for src & dst
if (tmp == 0 && ((src ^ dst) & b) != 0) {
sr |= OVERFLOW;
// System.out.println("OVERFLOW - ADD/SUB " + Utils.hex16(src)
// + " + " + Utils.hex16(tmpDst));
}
// System.out.println(Utils.hex16(dst) + " [SR=" +
// Utils.hex16(reg[SR]) + "]");
writeRegister(SR, sr);
write = true;
break;
case CMP: // CMP
// Set CARRY if A >= B, and it's clear if A < B
b = mode.msb;
sr = (sr & ~(CARRY | OVERFLOW)) | (dst >= src ? CARRY : 0);
tmp = (dst - src);
if (((src ^ tmp) & b) == 0 && (((src ^ dst) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
// Must set dst to the result to set the rest of the status register
dst = tmp;
break;
case DADD: // DADD
if (DEBUG)
log("DADD: Decimal add executed - result error!!!");
// Decimal add... this is wrong... each nibble is 0-9...
// So this has to be reimplemented...
dst = dst + src + ((sr & CARRY) > 0 ? 1 : 0);
write = true;
break;
case BIT: // BIT
dst = src & dst;
// Clear overflow and carry!
sr = sr & ~(CARRY | OVERFLOW);
// Set carry if result is non-zero!
if (dst != 0) {
sr |= CARRY;
}
writeRegister(SR, sr);
break;
case BIC: // BIC
// No status reg change
// System.out.println("BIC: =>" + Utils.hex16(dstAddress) + " => "
// + Utils.hex16(dst) + " AS: " + as +
// " sReg: " + srcRegister + " => " + src +
// " dReg: " + dstRegister + " => " + dst);
dst = (~src) & dst;
write = true;
updateStatus = false;
break;
case BIS: // BIS
dst = src | dst;
write = true;
updateStatus = false;
break;
case XOR: // XOR
sr = sr & ~(CARRY | OVERFLOW);
b = mode.msb; //word ? 0x8000 : (wordx20 ? 0x80000 : 0x80);
if ((src & b) != 0 && (dst & b) != 0) {
sr |= OVERFLOW;
}
dst = src ^ dst;
if (dst != 0) {
sr |= CARRY;
}
write = true;
writeRegister(SR, sr);
break;
case AND: // AND
sr = sr & ~(CARRY | OVERFLOW);
dst = src & dst;
if (dst != 0) {
sr |= CARRY;
}
write = true;
writeRegister(SR, sr);
break;
default:
String address = getAddressAsString(pc);
logw(WarningType.EMULATION_ERROR,
"DoubleOperand not implemented: op = " + Integer.toHexString(op) + " at " + address);
if (EXCEPTION_ON_BAD_OPERATION) {
EmulationException ex = new EmulationException("Bad operation: $" + Integer.toHexString(op) + " at $" + address);
ex.initCause(new Throwable("" + pc));
throw ex;
}
} /* after switch(op) */
/* If we have the same register as dst and src then copy here to get input
* in next loop
*/
if (repeats > 0 && srcRegister == dstRegister) {
src = dst;
src &= mode.mask;
//XXX if (word) {
// src &= 0xffff;
// } else if (wordx20) {
// src &= 0xfffff;
// } else {
// src &= 0xff;
// }
}
}
}
/* Processing after each instruction */
dst &= mode.mask;
//XXX if (word) {
// dst &= 0xffff;
// } else if (wordx20) {
// dst &= 0xfffff;
// } else {
// dst &= 0xff;
// }
if (write) {
if (dstRegMode) {
writeRegister(dstRegister, dst);
} else {
dstAddress &= 0xffff;
currentSegment.write(dstAddress, dst, mode);
}
}
if (updateStatus) {
// Update the Zero and Negative status!
// Carry and overflow must be set separately!
sr = readRegister(SR);
sr = (sr & ~(ZERO | NEGATIVE)) |
((dst == 0) ? ZERO : 0) | ((dst & mode.msb) > 0 ? NEGATIVE : 0);
//XXX (word ? ((dst & 0x8000) > 0 ? NEGATIVE : 0) :
// (wordx20 ? ((dst & 0x80000) > 0 ? NEGATIVE : 0) :
// ((dst & 0x80) > 0 ? NEGATIVE : 0)));
writeRegister(SR, sr);
}
//System.out.println("CYCLES AFTER: " + cycles);
// -------------------------------------------------------------------
// Event processing (when CPU is awake)
// -------------------------------------------------------------------
while (cycles >= nextEventCycles) {
executeEvents();
}
cpuCycles += cycles - startCycles;
/* return the address that was executed */
return pcBefore;
}
| public int emulateOP(long maxCycles) throws EmulationException {
//System.out.println("CYCLES BEFORE: " + cycles);
int pc = readRegister(PC);
long startCycles = cycles;
// -------------------------------------------------------------------
// Interrupt processing [after the last instruction was executed]
// -------------------------------------------------------------------
if (interruptsEnabled && servicedInterrupt == -1 && interruptMax >= 0) {
pc = serviceInterrupt(pc);
}
/* Did not execute any instructions */
if (cpuOff || flash.blocksCPU()) {
// System.out.println("Jumping: " + (nextIOTickCycles - cycles));
// nextEventCycles must exist, otherwise CPU can not wake up!?
// If CPU is not active we must run the events here!!!
// this can trigger interrupts that wake the CPU
// -------------------------------------------------------------------
// Event processing - note: This can trigger IRQs!
// -------------------------------------------------------------------
/* This can flag an interrupt! */
while (cycles >= nextEventCycles) {
executeEvents();
}
if (interruptsEnabled && interruptMax > 0) {
/* can not allow for jumping to nextEventCycles since that would jump too far */
return -1;
}
if (maxCycles >= 0 && maxCycles < nextEventCycles) {
// Should it just freeze or take on extra cycle step if cycles > max?
cycles = cycles < maxCycles ? maxCycles : cycles;
} else {
cycles = nextEventCycles;
}
return -1;
}
int pcBefore = pc;
instruction = currentSegment.read(pc, AccessMode.WORD, AccessType.EXECUTE);
if (isStopping) {
// Signaled to stop the execution before performing the instruction
return -2;
}
int ext3_0 = 0;
int ext10_7 = 0;
int extSrc = 0;
int extDst = 0;
boolean repeatsInDstReg = false;
boolean wordx20 = false;
/* check for extension words */
if ((instruction & 0xf800) == 0x1800) {
extWord = instruction;
ext3_0 = instruction & 0xf; /* bit 3 - 0 - either repeat count or dest 19-16 */
ext10_7 = (instruction >> 7) & 0xf; /* bit 10 - 7 - src 19-16 */
extSrc = ext10_7 << 16;
extDst = ext3_0 << 16;
pc += 2;
// Bit 7 in the extension word indicates that the number of
// repeats is found in the register pointed to by ext3_0. If
// the bit is 0, ext3_0 contains the number of repeats. If the
// bit is 1, ext3_0 contains the register number that holds
// the number of repeats.
if ((instruction & 0x80) == 0x80) {
repeatsInDstReg = true;
}
// Bit 6 indicates whether or not the data length mode should
// be 20 bits. A one means traditional MSP430 mode; a zero
// indicates 20 bit mode. (XXX: there is a reserved data
// length mode if this bit is zero and the MSP430 instruction
// that follows the extension word also has a zero bit data
// length mode.)
wordx20 = (instruction & 0x40) == 0;
instruction = currentSegment.read(pc, AccessMode.WORD, AccessType.EXECUTE);
// System.out.println("*** Extension word!!! " + Utils.hex16(extWord) +
// " read the instruction too: " + Utils.hex16(instruction) + " at " + Utils.hex16(pc - 2));
} else {
extWord = 0;
}
op = instruction >> 12;
int sp = 0;
int sr = 0;
int rval = 0; /* register value */
int repeats = 1; /* msp430X can repeat some instructions in some cases */
boolean zeroCarry = false; /* msp430X can zero carry in repeats */
boolean word = (instruction & 0x40) == 0;
/* NOTE: there is a mode when wordx20 = true & word = true that is resereved */
AccessMode mode = wordx20 ? AccessMode.WORD20 : (word ? AccessMode.WORD : AccessMode.BYTE);
if (mode == AccessMode.WORD20) System.out.println("WORD20 not really supported...");
// Destination vars
int dstRegister = 0;
int dstAddress = -1;
boolean dstRegMode = false;
int dst = -1;
boolean write = false;
boolean updateStatus = true;
// When is PC increased probably immediately (e.g. here)?
pc += 2;
writeRegister(PC, pc);
switch (op) {
case 0:
// MSP430X - additional instructions
op = instruction & 0xf0f0;
if (!MSP430XArch)
throw new EmulationException("Executing MSP430X instruction but MCU is not a MSP430X");
// System.out.println("Executing MSP430X instruction op:" + Utils.hex16(op) +
// " ins:" + Utils.hex16(instruction) + " PC = $" + getAddressAsString(pc - 2));
int src = 0;
/* data is either bit 19-16 or src register */
int srcData = (instruction & 0x0f00) >> 8;
int dstData = (instruction & 0x000f);
boolean rrword = true;
mode = AccessMode.WORD20;
switch(op) {
// 20 bit register write
case MOVA_IND:
/* Read from address in src register (20-bit?), move to destination register (=20 bit). */
writeRegister(dstData, currentSegment.read(readRegister(srcData), AccessMode.WORD20, AccessType.READ));
updateStatus = false;
cycles += 3;
break;
case MOVA_IND_AUTOINC:
if (profiler != null && instruction == 0x0110) {
profiler.profileReturn(cpuCycles);
}
writeRegister(PC, pc);
/* read from address in register */
src = readRegister(srcData);
// System.out.println("Reading $" + getAddressAsString(src) +
// " from register: " + srcData);
dst = currentSegment.read(src, AccessMode.WORD20, AccessType.READ);
// System.out.println("Reading from mem: $" + getAddressAsString(dst));
writeRegister(srcData, src + 4);
// System.out.println("*** Writing $" + getAddressAsString(dst) + " to reg: " + dstData);
writeRegister(dstData, dst);
updateStatus = false;
cycles += 3;
break;
case MOVA_ABS2REG:
src = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc += 2);
dst = src + (srcData << 16);
//System.out.println(Utils.hex20(pc) + " MOVA &ABS Reading from $" + getAddressAsString(dst) + " to reg: " + dstData);
dst = currentSegment.read(dst, AccessMode.WORD20, AccessType.READ);
//System.out.println(" => $" + getAddressAsString(dst));
writeRegister(dstData, dst);
updateStatus = false;
cycles += 4;
break;
case MOVA_INDX2REG:
/* Read data from address in memory, indexed by source
* register, and place into destination register. */
int index = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
int indexModifier = readRegister(srcData);
if(index > 0x8000) {
index = -(0x10000 - index);
}
writeRegister(dstData, currentSegment.read(indexModifier + index, AccessMode.WORD20, AccessType.READ));
writeRegister(PC, pc += 2);
updateStatus = false;
cycles += 4;
break;
case MOVA_REG2ABS:
dst = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc += 2);
currentSegment.write(dst + (dstData << 16), readRegister(srcData), AccessMode.WORD20);
updateStatus = false;
cycles += 4;
break;
case MOVA_REG2INDX:
/* Read data from register, write to address in memory,
* indexed by source register. */
index = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
indexModifier = readRegister(dstData);
if(index > 0x8000) {
index = -(0x10000 - index);
}
currentSegment.write(indexModifier + index, readRegister(srcData), AccessMode.WORD20);
writeRegister(PC, pc += 2);
updateStatus = false;
cycles += 4;
break;
case MOVA_IMM2REG:
src = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
writeRegister(PC, pc += 2);
dst = src + (srcData << 16);
// System.out.println("*** Writing $" + getAddressAsString(dst) + " to reg: " + dstData);
dst &= 0xfffff;
writeRegister(dstData, dst);
updateStatus = false;
cycles += 2;
break;
case ADDA_IMM:
// For all immediate instructions, the data low 16 bits of
// the data is stored in the following word (PC + 2) and
// the high 4 bits in the instruction word, which we have
// masked out as srcData.
int immData = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + (srcData << 16);
writeRegister(PC, pc += 2);
dst = readRegister(dstData) + immData;
// System.out.println("ADDA #" + Utils.hex20(immData) + " => " + Utils.hex20(dst));
dst &= 0xfffff;
writeRegister(dstData, dst);
cycles += 3;
break;
case CMPA_IMM: {
/* Status Bits N: Set if result is negative (src > dst), reset if positive (src ≤ dst)
Z: Set if result is zero (src = dst), reset otherwise (src ≠ dst)
C: Set if there is a carry from the MSB, reset otherwise
V: Set if the subtraction of a negative source operand from a positive destination
operand delivers a negative result, or if the subtraction of a positive source
operand from a negative destination operand delivers a positive result, reset
otherwise (no overflow) */
immData = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + (srcData << 16);
writeRegister(PC, pc += 2);
sr = readRegister(SR);
int destRegValue = readRegister(dstData);
sr &= ~(NEGATIVE | ZERO | CARRY | OVERFLOW);
if (destRegValue >= immData) {
sr |= CARRY;
}
if (destRegValue < immData) {
sr |= NEGATIVE;
}
if (destRegValue == immData) {
sr |= ZERO;
}
int cmpTmp = destRegValue - immData;
int b = 0x80000; // CMPA always use 20 bit data length
if (((destRegValue ^ cmpTmp) & b) == 0 &&
(((destRegValue ^ immData) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
updateStatus = false;
cycles += 3;
break;
}
case SUBA_IMM:
immData = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + (srcData << 16);
writeRegister(PC, pc += 2);
dst = readRegister(dstData) - immData;
writeRegister(dstData, dst);
cycles += 3;
break;
case MOVA_REG:
cycles += 1;
/* as = 0 since register mode */
writeRegister(dstData, readRegisterCG(srcData, 0));
break;
case CMPA_REG: {
sr = readRegister(SR);
sr &= ~(NEGATIVE | ZERO | CARRY | OVERFLOW);
int destRegValue = readRegister(dstData);
int srcRegValue = readRegisterCG(srcData, 0);
if (destRegValue >= srcRegValue) {
sr |= CARRY;
}
if (destRegValue < srcRegValue) {
sr |= NEGATIVE;
}
if (destRegValue == srcRegValue) {
sr |= ZERO;
}
int cmpTmp = destRegValue - srcRegValue;
int b = 0x80000; // CMPA always use 20 bit data length
if (((destRegValue ^ cmpTmp) & b) == 0 &&
(((destRegValue ^ srcRegValue) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
updateStatus = false;
cycles += 1;
break;
}
case ADDA_REG:
// Assume AS = 2
dst = readRegister(dstData) + readRegisterCG(srcData, 2);
writeRegister(dstData, dst);
cycles += 1;
break;
case SUBA_REG:
// Assume AS = 2
dst = readRegister(dstData) - readRegisterCG(srcData, 2);
writeRegister(dstData, dst);
cycles += 1;
break;
case RRXX_ADDR:
rrword = false;
case RRXX_WORD:
int count = ((instruction >> 10) & 0x03) + 1;
dst = readRegister(dstData);
sr = readRegister(SR);
int nxtCarry = 0;
int carry = (sr & CARRY) > 0? 1: 0;
if (rrword) {
mode = AccessMode.WORD;
dst = dst & 0xffff;
}
cycles += 1 + count;
switch(instruction & RRMASK) {
/* if word zero anything above */
case RRCM:
/* if (rrword): Rotate right through carry the 16-bit CPU register content
if (!rrword): Rotate right through carry the 20-bit CPU register content */
/* Pull the (count) lowest bits from dst - those will
* be placed in the (count) high bits of dst after the
* instruction is complete. */
int dst_low = dst & ((1 << count) - 1);
/* Grab the bit that will be in the carry flag when instruction completes. */
nxtCarry = (dst & (1 << (count + 1))) > 0? CARRY: 0;
/* Rotate dst. */
dst = dst >> (count);
/* Rotate the high bits, insert into dst. */
if (rrword) {
dst |= (dst_low << (17 - count)) | (carry << (16 - count));
} else {
dst |= (dst_low << (21 - count)) | (carry << (20 - count));
}
break;
case RRAM:
// System.out.println("RRAM executing");
/* roll in MSB from above */
/* 1 11 111 1111 needs to get in if MSB is 1 */
if ((dst & (rrword ? 0x8000 : 0x80000)) > 0) {
/* add some 1 bits above MSB if MSB is 1 */
dst = dst | (rrword ? 0xf8000 : 0xf80000);
}
dst = dst >> (count - 1);
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
break;
case RLAM:
// System.out.println("RLAM executing at " + pc);
/* just roll in "zeroes" from left */
dst = dst << (count - 1);
nxtCarry = (dst & (rrword ? 0x8000 : 0x80000)) > 0 ? CARRY : 0;
dst = dst << 1;
break;
case RRUM:
//System.out.println("RRUM executing");
/* just roll in "zeroes" from right */
dst = dst >> (count - 1);
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
break;
}
/* clear overflow - set carry according to above OP */
writeRegister(SR, (sr & ~(CARRY | OVERFLOW)) | nxtCarry);
dst = dst & (rrword ? 0xffff : 0xfffff);
writeRegister(dstData, dst);
break;
default:
System.out.println("MSP430X instruction not yet supported: " +
Utils.hex16(instruction) +
" op " + Utils.hex16(op));
throw new EmulationException("Found unsupported MSP430X instruction " +
Utils.hex16(instruction) +
" op " + Utils.hex16(op));
}
break;
case 1:
{
// -------------------------------------------------------------------
// Single operand instructions
// -------------------------------------------------------------------
// Register
dstRegister = instruction & 0xf;
/* check if this is a MSP430X CALLA instruction */
if ((op = instruction & CALLA_MASK) > RETI) {
pc = readRegister(PC);
dst = -1; /* will be -1 if not a call! */
/* do not update status after these instructions!!! */
updateStatus = false;
switch(op) {
case CALLA_REG:
// The CALLA operations increase the SP before
// address resolution!
// store on stack - always move 2 steps before resolution
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
dst = readRegister(dstRegister);
System.out.println("CALLA REG => " + Utils.hex20(dst));
cycles += 5;
break;
case CALLA_INDEX:
/* CALLA X(REG) => REG + X is the address*/
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
System.out.println("CALLA INDX: R" + dstRegister);
dst = readRegister(dstRegister);
/* what happens if wrapping here??? */
/* read the index which is from -15 bit - +15 bit. - so extend sign to 20-bit */
int v = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((v & 0x8000) != 0) {
v |= 0xf0000;
}
System.out.println("CALLA INDX: Reg = " + Utils.hex20(dst) + " INDX: " + v);
dst += v;
dst &= 0xfffff;
System.out.println("CALLA INDX => " + Utils.hex20(dst));
dst = currentSegment.read(dst, AccessMode.WORD20, AccessType.READ);
System.out.println("CALLA Read from INDX => " + Utils.hex20(dst));
cycles += 5;
pc += 2;
// System.exit(0);
break;
case CALLA_IMM:
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
dst = (dstRegister << 16) | currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
pc += 2;
cycles += 5;
break;
case CALLA_IND:
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
dstAddress = readRegister(dstRegister);
dst = currentSegment.read(dstAddress, AccessMode.WORD20, AccessType.READ);
pc += 2;
cycles += 5;
break;
case CALLA_ABS:
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
/* read the address of where the address to call is */
dst = (dstRegister << 16) | currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
dst = currentSegment.read(dst, AccessMode.WORD20, AccessType.READ);
pc += 2;
cycles += 7;
break;
default:
AccessMode type = AccessMode.WORD;
int size = 2;
sp = readRegister(SP);
/* check for PUSHM... POPM... */
switch(op & 0x1f00) {
case PUSHM_A:
type = AccessMode.WORD20;
size = 4;
cycles += 2;
case PUSHM_W:
int n = 1 + ((instruction >> 4) & 0x0f);
int regNo = instruction & 0x0f;
// System.out.println("PUSHM " + (type == AccessMode.WORD20 ? "A" : "W") +
// " n: " + n + " " + regNo + " at " + Utils.hex16(pcBefore));
/* decrease stack pointer and write n times */
for(int i = 0; i < n; i++) {
sp -= size;
cycles += 2;
currentSegment.write(sp, this.reg[regNo--], type);
// System.out.println("Saved reg: " + (regNo + 1) + " was " + reg[regNo + 1]);
/* what happens if regNo is wrapped ??? */
if (regNo < 0) regNo = 15;
}
writeRegister(SP, sp);
break;
case POPM_A:
type = AccessMode.WORD20;
size = 4;
cycles += 2;
case POPM_W:
n = 1 + ((instruction >> 4) & 0x0f);
regNo = instruction & 0x0f;
// System.out.println("POPM W " + (type == AccessMode.WORD20 ? "A" : "W") + " n: " +
// n + " " + regNo + " at " + Utils.hex16(pcBefore));
/* read and increase stack pointer n times */
for(int i = 0; i < n; i++) {
cycles += 2;
this.reg[regNo++] = currentSegment.read(sp, type, AccessType.READ);
// System.out.println("Restored reg: " + (regNo - 1) + " to " + reg[regNo - 1]);
sp += size;
/* what happens if regNo is wrapped ??? */
if (regNo > 15) regNo = 0;
}
writeRegister(SP, sp);
break;
default:
System.out.println("CALLA/PUSH/POP: mode not implemented");
throw new EmulationException("CALLA: mode not implemented "
+ Utils.hex16(instruction) + " => " + Utils.hex16(op));
}
}
// store current PC on stack. (current PC points to next instr.)
/* store 20 bits on stack (costs two words) */
if (dst != -1) {
currentSegment.write(sp, (pc >> 16) & 0xf, AccessMode.WORD);
sp = sp - 2;
currentSegment.write(sp, pc & 0xffff, AccessMode.WORD);
writeRegister(SP, sp);
writeRegister(PC, dst);
if (profiler != null) {
profileCall(dst, pc);
}
}
} else {
// Address mode of destination...
int ad = (instruction >> 4) & 3;
int nxtCarry = 0;
op = instruction & 0xff80;
if (op == PUSH || op == CALL) {
// The PUSH and CALL operations increase the SP before
// address resolution!
// store on stack - always move 2 steps (W) even if B./
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
}
if ((dstRegister == CG1 && ad > AM_INDEX) || dstRegister == CG2) {
dstRegMode = true;
cycles++;
} else {
switch(ad) {
// Operand in register!
case AM_REG:
dstRegMode = true;
cycles++;
break;
case AM_INDEX:
// TODO: needs to handle if SR is used!
rval = readRegisterCG(dstRegister, ad);
/* Support for MSP430X and below / above 64 KB */
/* if register is pointing to <64KB then it needs to be truncated to below 64 */
if (extWord != 0) {
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + extDst;
dstAddress += rval;
dstAddress &= 0xfffff;
} else if (rval <= 0xffff) {
dstAddress = (rval + currentSegment.read(pc, AccessMode.WORD, AccessType.READ)) & 0xffff;
} else {
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((dstAddress & 0x8000) > 0) {
dstAddress |= 0xf0000;
}
dstAddress += rval;
dstAddress &= 0xfffff;
}
// When is PC incremented - assuming immediately after "read"?
pc += 2;
writeRegister(PC, pc);
cycles += 4;
break;
// Indirect register
case AM_IND_REG:
dstAddress = readRegister(dstRegister);
cycles += 3;
break;
// Bugfix suggested by Matt Thompson
case AM_IND_AUTOINC:
if (dstRegister == PC) {
dstAddress = pc;
dst = currentSegment.read(dstAddress, mode != AccessMode.BYTE ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
dst += extDst;
pc += 2;
writeRegister(PC, pc);
} else {
dstAddress = readRegister(dstRegister);
writeRegister(dstRegister, dstAddress + mode.bytes); // XXX (word ? 2 : 1));
}
cycles += 3;
break;
}
}
// Perform the read
if (dstRegMode) {
dst = readRegisterCG(dstRegister, ad);
dst &= mode.mask;
/* set the repeat here! */
if (repeatsInDstReg) {
repeats = 1 + readRegister(ext3_0);
} else {
repeats = 1 + ext3_0;
}
zeroCarry = (extWord & EXTWORD_ZC) > 0;
// if (repeats > 1) {
// System.out.println("*** Repeat " + repeats + " ZeroCarry: " + zeroCarry);
// }
} else if (dst == -1) {
dst = currentSegment.read(dstAddress, mode, AccessType.READ);
}
/* TODO: test add the loop here! */
while(repeats-- > 0) {
sr = readRegister(SR);
/* always clear carry before repeat */
if (repeats >= 0) {
if (zeroCarry) {
sr = sr & ~CARRY;
//System.out.println("ZC => Cleared carry...");
}
//System.out.println("*** Repeat: " + repeats);
}
switch(op) {
case RRC:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = dst >> 1;
dst |= (sr & CARRY) > 0 ? mode.msb : 0;
//XXX if (word) {
// dst |= (sr & CARRY) > 0 ? 0x8000 : 0;
// } else if (wordx20) {
// dst |= (sr & CARRY) > 0 ? 0x80000 : 0;
// } else {
// dst |= (sr & CARRY) > 0 ? 0x80 : 0;
// }
// Indicate write to memory!!
write = true;
// Set the next carry!
writeRegister(SR, (sr & ~(CARRY | OVERFLOW)) | nxtCarry);
break;
case SWPB:
int tmp = dst;
dst = ((tmp >> 8) & 0xff) + ((tmp << 8) & 0xff00);
write = true;
break;
case RRA:
nxtCarry = (dst & 1) > 0 ? CARRY : 0;
dst = (dst & mode.msb) | dst >> 1;
//XXX if (word) {
// dst = (dst & 0x8000) | (dst >> 1);
// } else if (wordx20) {
// dst = (dst & 0x80000) | (dst >> 1);
// } else {
// dst = (dst & 0x80) | (dst >> 1);
// }
write = true;
writeRegister(SR, (sr & ~(CARRY | OVERFLOW)) | nxtCarry);
break;
case SXT:
// Extend Sign (bit 8-15 => same as bit 7)
dst = (dst & 0x80) > 0 ? dst | 0xfff00 : dst & 0x7f;
write = true;
sr = sr & ~(CARRY | OVERFLOW);
if (dst != 0) {
sr |= CARRY;
}
writeRegister(SR, sr);
break;
case PUSH:
if (mode == AccessMode.WORD20) {
sp = readRegister(SP) - 2;
writeRegister(SP, sp);
}
currentSegment.write(sp, dst, mode);
/* if REG or INDIRECT AUTOINC then add 2 cycles, otherwise 1 */
cycles += (ad == AM_REG || ad == AM_IND_AUTOINC) ? 2 : 1;
write = false;
updateStatus = false;
break;
case CALL:
// store current PC on stack. (current PC points to next instr.)
pc = readRegister(PC);
// memory[sp] = pc & 0xff;
// memory[sp + 1] = pc >> 8;
currentSegment.write(sp, pc, AccessMode.WORD);
writeRegister(PC, dst);
/* Additional cycles: REG => 3, AM_IND_AUTO => 2, other => 1 */
cycles += (ad == AM_REG) ? 3 : (ad == AM_IND_AUTOINC) ? 2 : 1;
/* profiler will be called during calls */
if (profiler != null) {
profileCall(dst, pc);
}
write = false;
updateStatus = false;
break;
case RETI:
// Put Top of stack to Status DstRegister (TOS -> SR)
servicedInterrupt = -1; /* needed before write to SR!!! */
sp = readRegister(SP);
sr = currentSegment.read(sp, AccessMode.WORD, AccessType.READ);
writeRegister(SR, sr & 0x0fff);
sp = sp + 2;
// writeRegister(SR, memory[sp++] + (memory[sp++] << 8));
// TOS -> PC
// writeRegister(PC, memory[sp++] + (memory[sp++] << 8));
writeRegister(PC, currentSegment.read(sp, AccessMode.WORD, AccessType.READ) | (sr & 0xf000) << 4);
sp = sp + 2;
writeRegister(SP, sp);
write = false;
updateStatus = false;
cycles += 4;
if (debugInterrupts) {
System.out.println("### RETI at " + pc + " => " + reg[PC] +
" SP after: " + reg[SP]);
}
if (profiler != null) {
profiler.profileRETI(cycles);
}
// This assumes that all interrupts will get back using RETI!
handlePendingInterrupts();
break;
default:
System.out.println("Error: Not implemented instruction:" +
Utils.hex16(instruction));
}
if (repeats > 0) {
//XXX if (word) {
// dst &= 0xffff;
// } else if (wordx20) {
// dst &= 0xfffff;
// } else {
// dst &= 0xff;
// }
dst &= mode.mask;
}
}
}
}
break;
// Jump instructions
case 2:
case 3:
// 10 bits for address for these => 0x00fc => remove 2 bits
int jmpOffset = instruction & 0x3ff;
jmpOffset = (jmpOffset & 0x200) == 0 ?
2 * jmpOffset : -(2 * (0x200 - (jmpOffset & 0x1ff)));
boolean jump = false;
// All jump takes two cycles
cycles += 2;
sr = readRegister(SR);
switch(instruction & 0xfc00) {
case JNE:
jump = (sr & ZERO) == 0;
break;
case JEQ:
jump = (sr & ZERO) > 0;
break;
case JNC:
jump = (sr & CARRY) == 0;
break;
case JC:
jump = (sr & CARRY) > 0;
break;
case JN:
jump = (sr & NEGATIVE) > 0;
break;
case JGE:
jump = (sr & NEGATIVE) > 0 == (sr & OVERFLOW) > 0;
break;
case JL:
jump = (sr & NEGATIVE) > 0 != (sr & OVERFLOW) > 0;
break;
case JMP:
jump = true;
break;
default:
logw(WarningType.EMULATION_ERROR, "Not implemented instruction: #" + Utils.binary16(instruction));
}
// Perform the Jump
if (jump) {
writeRegister(PC, pc + jmpOffset);
}
updateStatus = false;
break;
default:
// ---------------------------------------------------------------
// Double operand instructions!
// ---------------------------------------------------------------
dstRegister = instruction & 0xf;
int srcRegister = (instruction >> 8) & 0xf;
int as = (instruction >> 4) & 3;
// AD: 0 => register direct, 1 => register index, e.g. X(Rn)
dstRegMode = ((instruction >> 7) & 1) == 0;
dstAddress = -1;
int srcAddress = -1;
src = 0;
// Some CGs should be handled as registry reads only...
if ((srcRegister == CG1 && as > AM_INDEX) || srcRegister == CG2) {
src = CREG_VALUES[srcRegister - 2][as];
src &= mode.mask;
//XXX if (word) {
// src &= 0xffff;
// } else if (wordx20) {
// src &= 0xfffff;
// } else {
// src &= 0xff;
// }
cycles += dstRegMode ? 1 : 4;
} else {
switch(as) {
// Operand in register!
case AM_REG:
// CG handled above!
src = readRegister(srcRegister);
src &= mode.mask;
//XXX if (word) {
// src &= 0xffff;
// } else if (wordx20) {
// src &= 0xfffff;
// } else {
// src &= 0xff;
// }
cycles += dstRegMode ? 1 : 4;
/* add cycle if destination register = PC */
if (dstRegister == PC) cycles++;
if (dstRegMode) {
/* possible to have repeat, etc... */
/* TODO: decode the # also */
if (repeatsInDstReg) {
repeats = 1 + readRegister(ext3_0);
} else {
repeats = 1 + ext3_0;
}
zeroCarry = (extWord & EXTWORD_ZC) > 0;
}
break;
case AM_INDEX: {
// Indexed if reg != PC & CG1/CG2 - will PC be incremented?
int sval = readRegisterCG(srcRegister, as);
/* Support for MSP430X and below / above 64 KB */
/* if register is pointing to <64KB then it needs to be truncated to below 64 */
if (extWord != 0) {
srcAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ) + extSrc;
srcAddress += sval;
srcAddress &= 0xfffff;
} else if (sval <= 0xffff) {
srcAddress = (sval + currentSegment.read(pc, AccessMode.WORD, AccessType.READ)) & 0xffff;
} else {
srcAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((srcAddress & 0x8000) > 0) {
// Negative index
srcAddress |= 0xf0000;
}
srcAddress += sval;
srcAddress &= 0xfffff;
}
// When is PC incremented - assuming immediately after "read"?
pc += 2;
writeRegister(PC, pc);
cycles += dstRegMode ? 3 : 6;
break;
}
// Indirect register
case AM_IND_REG:
srcAddress = readRegister(srcRegister);
cycles += dstRegMode ? 2 : 5;
break;
case AM_IND_AUTOINC:
if (srcRegister == PC) {
/* PC is always handled as word */
src = currentSegment.read(pc, mode != AccessMode.BYTE ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
src += extSrc;
pc += 2;
writeRegister(PC, pc);
cycles += dstRegMode ? 2 : 5;
} else {
srcAddress = readRegister(srcRegister);
incRegister(srcRegister, mode.bytes);//XXX word ? 2 : 1);
cycles += dstRegMode ? 2 : 5;
}
/* If destination register is PC another cycle is consumed */
if (dstRegister == PC) {
cycles++;
}
break;
}
}
// Perform the read of destination!
if (dstRegMode) {
if (op != MOV) {
dst = readRegister(dstRegister);
dst &= mode.mask;
}
} else {
// PC Could have changed above!
pc = readRegister(PC);
if (dstRegister == 2) {
/* absolute mode */
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ); //memory[pc] + (memory[pc + 1] << 8);
} else {
// CG here - probably not!???
rval = readRegister(dstRegister);
/* Support for MSP430X and below / above 64 KB */
/* if register is pointing to <64KB then it needs to be truncated to below 64 */
if (rval <= 0xffff) {
dstAddress = (rval + currentSegment.read(pc, AccessMode.WORD, AccessType.READ)) & 0xffff;
} else {
dstAddress = currentSegment.read(pc, AccessMode.WORD, AccessType.READ);
if ((dstAddress & 0x8000) > 0) {
dstAddress |= 0xf0000;
}
dstAddress += rval;
dstAddress &= 0xfffff;
}
}
if (op != MOV) {
dst = currentSegment.read(dstAddress, word ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
}
pc += 2;
incRegister(PC, 2);
}
// **** Perform the read...
if (srcAddress != -1) {
// if (srcAddress > 0xffff) {
// System.out.println("SrcAddress is: " + Utils.hex20(srcAddress));
// }
// srcAddress = srcAddress & 0xffff;
src = currentSegment.read(srcAddress, mode, AccessType.READ);
// src = currentSegment.read(srcAddress, word ? AccessMode.WORD : AccessMode.BYTE, AccessType.READ);
// if (debug) {
// System.out.println("Reading from " + getAddressAsString(srcAddress) +
// " => " + src);
// }
}
/* TODO: test add the loop here! */
while(repeats-- > 0) {
sr = readRegister(SR);
if (repeats >= 0) {
if (zeroCarry) {
sr = sr & ~CARRY;
//System.out.println("ZC => Cleared carry...");
}
//System.out.println("*** Repeat: " + repeats);
}
int tmp = 0;
int tmpAdd = 0;
switch (op) {
case MOV: // MOV
dst = src;
write = true;
updateStatus = false;
if (instruction == RETURN && profiler != null) {
profiler.profileReturn(cpuCycles);
}
break;
// FIX THIS!!! - make SUB a separate operation so that
// it is clear that overflow flag is correct...
case SUB:
// Carry always 1 with SUB
tmpAdd = 1;
case SUBC:
// Both sub and subc does one complement (not) + 1 (or carry)
src = (src ^ 0xffff) & 0xffff;
case ADDC: // ADDC
if (op == ADDC || op == SUBC)
tmpAdd = ((sr & CARRY) > 0) ? 1 : 0;
case ADD: // ADD
// Tmp gives zero if same sign! if sign is different after -> overf.
sr &= ~(OVERFLOW | CARRY);
int b = word ? 0x8000 : (wordx20 ? 0x80000 : 0x80);
tmp = (src ^ dst) & b;
// Includes carry if carry should be added...
dst = dst + src + tmpAdd;
int b2 = word ? 0xffff : (wordx20 ? 0xfffff : 0xff);
if (dst > b2) {
sr |= CARRY;
}
// If tmp == 0 and currenly not the same sign for src & dst
if (tmp == 0 && ((src ^ dst) & b) != 0) {
sr |= OVERFLOW;
// System.out.println("OVERFLOW - ADD/SUB " + Utils.hex16(src)
// + " + " + Utils.hex16(tmpDst));
}
// System.out.println(Utils.hex16(dst) + " [SR=" +
// Utils.hex16(reg[SR]) + "]");
writeRegister(SR, sr);
write = true;
break;
case CMP: // CMP
// Set CARRY if A >= B, and it's clear if A < B
b = mode.msb;
sr = (sr & ~(CARRY | OVERFLOW)) | (dst >= src ? CARRY : 0);
tmp = (dst - src);
if (((src ^ tmp) & b) == 0 && (((src ^ dst) & b) != 0)) {
sr |= OVERFLOW;
}
writeRegister(SR, sr);
// Must set dst to the result to set the rest of the status register
dst = tmp;
break;
case DADD: // DADD
if (DEBUG)
log("DADD: Decimal add executed - result error!!!");
// Decimal add... this is wrong... each nibble is 0-9...
// So this has to be reimplemented...
dst = dst + src + ((sr & CARRY) > 0 ? 1 : 0);
write = true;
break;
case BIT: // BIT
dst = src & dst;
// Clear overflow and carry!
sr = sr & ~(CARRY | OVERFLOW);
// Set carry if result is non-zero!
if (dst != 0) {
sr |= CARRY;
}
writeRegister(SR, sr);
break;
case BIC: // BIC
// No status reg change
// System.out.println("BIC: =>" + Utils.hex16(dstAddress) + " => "
// + Utils.hex16(dst) + " AS: " + as +
// " sReg: " + srcRegister + " => " + src +
// " dReg: " + dstRegister + " => " + dst);
dst = (~src) & dst;
write = true;
updateStatus = false;
break;
case BIS: // BIS
dst = src | dst;
write = true;
updateStatus = false;
break;
case XOR: // XOR
sr = sr & ~(CARRY | OVERFLOW);
b = mode.msb; //word ? 0x8000 : (wordx20 ? 0x80000 : 0x80);
if ((src & b) != 0 && (dst & b) != 0) {
sr |= OVERFLOW;
}
dst = src ^ dst;
if (dst != 0) {
sr |= CARRY;
}
write = true;
writeRegister(SR, sr);
break;
case AND: // AND
sr = sr & ~(CARRY | OVERFLOW);
dst = src & dst;
if (dst != 0) {
sr |= CARRY;
}
write = true;
writeRegister(SR, sr);
break;
default:
String address = getAddressAsString(pc);
logw(WarningType.EMULATION_ERROR,
"DoubleOperand not implemented: op = " + Integer.toHexString(op) + " at " + address);
if (EXCEPTION_ON_BAD_OPERATION) {
EmulationException ex = new EmulationException("Bad operation: $" + Integer.toHexString(op) + " at $" + address);
ex.initCause(new Throwable("" + pc));
throw ex;
}
} /* after switch(op) */
/* If we have the same register as dst and src then copy here to get input
* in next loop
*/
if (repeats > 0 && srcRegister == dstRegister) {
src = dst;
src &= mode.mask;
//XXX if (word) {
// src &= 0xffff;
// } else if (wordx20) {
// src &= 0xfffff;
// } else {
// src &= 0xff;
// }
}
}
}
/* Processing after each instruction */
dst &= mode.mask;
//XXX if (word) {
// dst &= 0xffff;
// } else if (wordx20) {
// dst &= 0xfffff;
// } else {
// dst &= 0xff;
// }
if (write) {
if (dstRegMode) {
writeRegister(dstRegister, dst);
} else {
dstAddress &= 0xffff;
currentSegment.write(dstAddress, dst, mode);
}
}
if (updateStatus) {
// Update the Zero and Negative status!
// Carry and overflow must be set separately!
sr = readRegister(SR);
sr = (sr & ~(ZERO | NEGATIVE)) |
((dst == 0) ? ZERO : 0) | ((dst & mode.msb) > 0 ? NEGATIVE : 0);
//XXX (word ? ((dst & 0x8000) > 0 ? NEGATIVE : 0) :
// (wordx20 ? ((dst & 0x80000) > 0 ? NEGATIVE : 0) :
// ((dst & 0x80) > 0 ? NEGATIVE : 0)));
writeRegister(SR, sr);
}
//System.out.println("CYCLES AFTER: " + cycles);
// -------------------------------------------------------------------
// Event processing (when CPU is awake)
// -------------------------------------------------------------------
while (cycles >= nextEventCycles) {
executeEvents();
}
cpuCycles += cycles - startCycles;
/* return the address that was executed */
return pcBefore;
}
|
diff --git a/jas/MyClient.java b/jas/MyClient.java
index 06ba5af..88c536e 100644
--- a/jas/MyClient.java
+++ b/jas/MyClient.java
@@ -1,105 +1,109 @@
import java.io.*;
import java.net.*;
import java.util.Scanner;
import javax.swing.*;
public class MyClient {
String msg;
Bomberman b;
Player playerMe;
Player playerOpp;
String playerName;
public static void main (String args[]) {
new MyClient();
}
public MyClient() {
try {
System.out.println("\nClient: Connecting to server...");
Socket socket = new Socket("127.0.0.1",8080);
MyConnection con = new MyConnection(socket);
System.out.println("Client: I connected! ^_^\n");
clientThread getThread = new clientThread(con);
getThread.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class clientThread extends Thread {
MyConnection con;
clientThread(MyConnection con) {
this.con = con;
}
public void run() {
try {
while(!(msg=con.getMessage()).equals("/quit")) {
if (msg.startsWith("/thisisme ")) {
playerMe = new Player(msg.substring(10));
System.out.println(playerMe.name);
}
else if (msg.startsWith("/startpos ")) {
int startMe = Integer.parseInt(msg.substring(10));
playerMe.startPos = startMe;
}
else if (msg.startsWith("/thisisopp ")) {
playerOpp = new Player(msg.substring(11));
System.out.println(playerOpp.name);
}
else if (msg.startsWith("/opponentstartpos ")) {
int startOpp = Integer.parseInt(msg.substring(18));
playerOpp.startPos = startOpp;
}
else if (msg.startsWith("/map ")) {
b = new Bomberman(con, playerMe, playerOpp, msg.substring(5));
b.setVisible(true);
b.setTitle(playerMe.name + " - Bomberman");
b.repaint();
System.out.println(msg.substring(5));
}
else if (msg.startsWith("/startGame")) {
b.startGame();
}
else if (msg.startsWith("/playerMoveLeft ")) {
// int newLoc = b.player.moveLeft(b.board, Integer.parseInt(msg.substring(16)));
// JPanel panel = (JPanel) b.board.getComponent(newLoc);
// b.player = new Player("data/"+player.name+"_left.gif");
// panel.add(player);
// b.validate();
// b.repaint();
- if (msg.substring(16,21) == playerMe.name) {
- int newLoc = playerMe.moveLeft(b.board, Integer.parseInt(msg.substring(22)));
+ System.out.println("NAME:" + msg.substring(16,21));
+ System.out.println("PLAYER:" + playerMe.name);
+ if (msg.substring(16,21).equals(playerMe.name)) {
+ String[] loc = msg.split(" ");
+ int newLoc = playerMe.moveLeft(b.board, Integer.parseInt(loc[2]));
JPanel panel = (JPanel) b.board.getComponent(newLoc);
- playerMe = new Player("data/" + playerMe.name + "_left.gif");
+ b.playerMe = new Player("data/" + playerMe.name + "_left.gif");
panel.add(playerMe);
b.validate();
b.repaint();
- } else if (msg.substring(16,21) == playerOpp.name) {
- int newLoc = playerOpp.moveLeft(b.board, Integer.parseInt(msg.substring(22)));
+ } else if (msg.substring(16,21).equals(playerOpp.name)) {
+ String[] loc = msg.split(" ");
+ int newLoc = playerOpp.moveLeft(b.board, Integer.parseInt(loc[2]));
JPanel panel = (JPanel) b.board.getComponent(newLoc);
- playerMe = new Player("data/" + playerOpp.name + "_left.gif");
+ b.playerOpp = new Player("data/" + playerOpp.name + "_left.gif");
panel.add(playerOpp);
b.validate();
b.repaint();
}
System.out.println(msg);
}
else {
System.out.println(msg);
}
msg = "";
}
if(msg.equals("/quit")) {
//c.setVisible(false);
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
| false | true | public void run() {
try {
while(!(msg=con.getMessage()).equals("/quit")) {
if (msg.startsWith("/thisisme ")) {
playerMe = new Player(msg.substring(10));
System.out.println(playerMe.name);
}
else if (msg.startsWith("/startpos ")) {
int startMe = Integer.parseInt(msg.substring(10));
playerMe.startPos = startMe;
}
else if (msg.startsWith("/thisisopp ")) {
playerOpp = new Player(msg.substring(11));
System.out.println(playerOpp.name);
}
else if (msg.startsWith("/opponentstartpos ")) {
int startOpp = Integer.parseInt(msg.substring(18));
playerOpp.startPos = startOpp;
}
else if (msg.startsWith("/map ")) {
b = new Bomberman(con, playerMe, playerOpp, msg.substring(5));
b.setVisible(true);
b.setTitle(playerMe.name + " - Bomberman");
b.repaint();
System.out.println(msg.substring(5));
}
else if (msg.startsWith("/startGame")) {
b.startGame();
}
else if (msg.startsWith("/playerMoveLeft ")) {
// int newLoc = b.player.moveLeft(b.board, Integer.parseInt(msg.substring(16)));
// JPanel panel = (JPanel) b.board.getComponent(newLoc);
// b.player = new Player("data/"+player.name+"_left.gif");
// panel.add(player);
// b.validate();
// b.repaint();
if (msg.substring(16,21) == playerMe.name) {
int newLoc = playerMe.moveLeft(b.board, Integer.parseInt(msg.substring(22)));
JPanel panel = (JPanel) b.board.getComponent(newLoc);
playerMe = new Player("data/" + playerMe.name + "_left.gif");
panel.add(playerMe);
b.validate();
b.repaint();
} else if (msg.substring(16,21) == playerOpp.name) {
int newLoc = playerOpp.moveLeft(b.board, Integer.parseInt(msg.substring(22)));
JPanel panel = (JPanel) b.board.getComponent(newLoc);
playerMe = new Player("data/" + playerOpp.name + "_left.gif");
panel.add(playerOpp);
b.validate();
b.repaint();
}
System.out.println(msg);
}
else {
System.out.println(msg);
}
msg = "";
}
if(msg.equals("/quit")) {
//c.setVisible(false);
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
| public void run() {
try {
while(!(msg=con.getMessage()).equals("/quit")) {
if (msg.startsWith("/thisisme ")) {
playerMe = new Player(msg.substring(10));
System.out.println(playerMe.name);
}
else if (msg.startsWith("/startpos ")) {
int startMe = Integer.parseInt(msg.substring(10));
playerMe.startPos = startMe;
}
else if (msg.startsWith("/thisisopp ")) {
playerOpp = new Player(msg.substring(11));
System.out.println(playerOpp.name);
}
else if (msg.startsWith("/opponentstartpos ")) {
int startOpp = Integer.parseInt(msg.substring(18));
playerOpp.startPos = startOpp;
}
else if (msg.startsWith("/map ")) {
b = new Bomberman(con, playerMe, playerOpp, msg.substring(5));
b.setVisible(true);
b.setTitle(playerMe.name + " - Bomberman");
b.repaint();
System.out.println(msg.substring(5));
}
else if (msg.startsWith("/startGame")) {
b.startGame();
}
else if (msg.startsWith("/playerMoveLeft ")) {
// int newLoc = b.player.moveLeft(b.board, Integer.parseInt(msg.substring(16)));
// JPanel panel = (JPanel) b.board.getComponent(newLoc);
// b.player = new Player("data/"+player.name+"_left.gif");
// panel.add(player);
// b.validate();
// b.repaint();
System.out.println("NAME:" + msg.substring(16,21));
System.out.println("PLAYER:" + playerMe.name);
if (msg.substring(16,21).equals(playerMe.name)) {
String[] loc = msg.split(" ");
int newLoc = playerMe.moveLeft(b.board, Integer.parseInt(loc[2]));
JPanel panel = (JPanel) b.board.getComponent(newLoc);
b.playerMe = new Player("data/" + playerMe.name + "_left.gif");
panel.add(playerMe);
b.validate();
b.repaint();
} else if (msg.substring(16,21).equals(playerOpp.name)) {
String[] loc = msg.split(" ");
int newLoc = playerOpp.moveLeft(b.board, Integer.parseInt(loc[2]));
JPanel panel = (JPanel) b.board.getComponent(newLoc);
b.playerOpp = new Player("data/" + playerOpp.name + "_left.gif");
panel.add(playerOpp);
b.validate();
b.repaint();
}
System.out.println(msg);
}
else {
System.out.println(msg);
}
msg = "";
}
if(msg.equals("/quit")) {
//c.setVisible(false);
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.