diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/org/sonar/plugins/jira/JiraPriorities.java b/src/main/java/org/sonar/plugins/jira/JiraPriorities.java
index 8be2be6..00c9884 100644
--- a/src/main/java/org/sonar/plugins/jira/JiraPriorities.java
+++ b/src/main/java/org/sonar/plugins/jira/JiraPriorities.java
@@ -1,68 +1,67 @@
/*
* Sonar, entreprise quality control tool.
* Copyright (C) 2007-2008 Hortis-GRC SA
* mailto:be_agile HAT hortis DOT ch
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.plugins.jira;
import org.apache.commons.collections.Bag;
import org.apache.commons.collections.bag.HashBag;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class JiraPriorities {
private Bag prioritiesNameBag;
public JiraPriorities(Collection priorities) {
initPrioritiesBag(priorities);
}
private void initPrioritiesBag(Collection priorities) {
prioritiesNameBag = new HashBag();
for (Object priorityObj : priorities) {
String currentPriority = (String) priorityObj;
prioritiesNameBag.add(currentPriority);
}
}
public int getTotalPrioritesCount() {
return prioritiesNameBag.size();
}
public String getPriorityDistributionText() {
- String result = "";
+ StringBuilder result = new StringBuilder();
for (Object o : getOrderedPriorities()) {
String priority = (String) o;
int prioritySize = prioritiesNameBag.getCount(priority);
- result += priority + "=" + prioritySize + ",";
+ result.append(priority).append('=').append(prioritySize).append(',');
}
- result = StringUtils.removeEnd(result, ",");
- return result;
+ return StringUtils.removeEnd(result.toString(), ",");
}
private List<String> getOrderedPriorities() {
List<String> sortedPriorities = new ArrayList<String>(prioritiesNameBag.uniqueSet());
Collections.sort(sortedPriorities);
return sortedPriorities;
}
}
| false | true | public String getPriorityDistributionText() {
String result = "";
for (Object o : getOrderedPriorities()) {
String priority = (String) o;
int prioritySize = prioritiesNameBag.getCount(priority);
result += priority + "=" + prioritySize + ",";
}
result = StringUtils.removeEnd(result, ",");
return result;
}
| public String getPriorityDistributionText() {
StringBuilder result = new StringBuilder();
for (Object o : getOrderedPriorities()) {
String priority = (String) o;
int prioritySize = prioritiesNameBag.getCount(priority);
result.append(priority).append('=').append(prioritySize).append(',');
}
return StringUtils.removeEnd(result.toString(), ",");
}
|
diff --git a/hk2/config/src/java/org/jvnet/hk2/config/ConfigSupport.java b/hk2/config/src/java/org/jvnet/hk2/config/ConfigSupport.java
index 2e72494f7..cfcf97227 100644
--- a/hk2/config/src/java/org/jvnet/hk2/config/ConfigSupport.java
+++ b/hk2/config/src/java/org/jvnet/hk2/config/ConfigSupport.java
@@ -1,838 +1,838 @@
/*
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2007-2008 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.jvnet.hk2.config;
import org.jvnet.hk2.annotations.Service;
import org.jvnet.hk2.annotations.Scoped;
import org.jvnet.hk2.annotations.Inject;
import org.jvnet.hk2.component.Singleton;
import org.jvnet.hk2.component.Habitat;
import java.beans.PropertyVetoException;
import java.beans.PropertyChangeEvent;
import java.lang.reflect.*;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.*;
import org.jvnet.tiger_types.Types;
/**
* <p>
* Helper class to execute some code on configuration objects while taking
* care of the transaction boiler plate code.
* </p>
* <p>
* Programmers that wish to apply some changes to configuration objects
* can use these convenience methods to reduce the complexity of handling
* transactions.
* </p>
* <p>
* For instance, say a programmer need to change the HttpListener port from
* 8080 to 8989, it just needs to do :
* </p>
* <pre>
* ... in his code somewhere ...
* HttpListener httpListener = domain.get...
*
* // If the programmer tries to modify the httpListener directly
* // it will get an exception
* httpListener.setPort("8989"); // will generate a PropertyVetoException
*
* // instead he needs to use a transaction and can use the helper services
* ConfigSupport.apply(new SingleConfigCode<HttpListener>() {
* public Object run(HttpListener okToChange) throws PropertyException {
* okToChange.setPort("8989"); // good...
* httpListener.setPort("7878"); // not good, exceptions still raised...
* return null;
* });
*
* // Note that after this code
* System.out.println("Port is " + httpListener.getPort());
* // will display 8989
* }
* </pre>
* @author Jerome Dochez
*/
@Service
@Scoped(Singleton.class)
public class ConfigSupport {
@Inject
Habitat habitat;
/**
* Execute� some logic on one config bean of type T protected by a transaction
*
* @param code code to execute
* @param param config object participating in the transaction
* @return list of events that represents the modified config elements.
* @throws TransactionFailure when code did not run successfully
*/
public static <T extends ConfigBeanProxy> Object apply(final SingleConfigCode<T> code, T param)
throws TransactionFailure {
ConfigBeanProxy[] objects = { param };
return apply((new ConfigCode() {
@SuppressWarnings("unchecked")
public Object run(ConfigBeanProxy... objects) throws PropertyVetoException, TransactionFailure {
return code.run((T) objects[0]);
}
}), objects);
}
/**
* Executes some logic on some config beans protected by a transaction.
*
* @param code code to execute
* @param objects config beans participating to the transaction
* @return list of property change events
* @throws TransactionFailure when the code did run successfully due to a
* transaction exception
*/
public static Object apply(ConfigCode code, ConfigBeanProxy... objects)
throws TransactionFailure {
ConfigBean source = (ConfigBean) ConfigBean.unwrap(objects[0]);
return source.getHabitat().getComponent(ConfigSupport.class)._apply(code, objects);
}
/**
* Executes some logic on some config beans protected by a transaction.
*
* @param code code to execute
* @param objects config beans participating to the transaction
* @return list of property change events
* @throws TransactionFailure when the code did run successfully due to a
* transaction exception
*/
public Object _apply(ConfigCode code, ConfigBeanProxy... objects)
throws TransactionFailure {
// the fools think they operate on the "real" object while I am
// feeding them with writeable view. Only if the transaction succeed
// will I apply the "changes" to the real ones.
WriteableView[] views = new WriteableView[objects.length];
ConfigBeanProxy[] proxies = new ConfigBeanProxy[objects.length];
// create writeable views.
for (int i=0;i<objects.length;i++) {
proxies[i] = getWriteableView(objects[i]);
views[i] = (WriteableView) Proxy.getInvocationHandler(proxies[i]);
}
// Of course I am not locking the live objects but the writable views.
// if the user try to massage the real objects, he will get
// a well deserved nasty exception
Transaction t = new Transaction();
for (WriteableView view : views) {
if (!view.join(t)) {
t.rollback();
throw new TransactionFailure("Cannot enlist " + view.getMasterView().getProxyType()
+ " in transaction", null);
}
}
try {
final Object toReturn = code.run(proxies);
try {
t.commit();
if (toReturn instanceof WriteableView) {
return ((WriteableView) toReturn).getMasterView();
} else {
return toReturn;
}
} catch (RetryableException e) {
System.out.println("Retryable...");
// TODO : do something meaninful here
t.rollback();
return null;
} catch (TransactionFailure e) {
t.rollback();
throw e;
}
} catch(TransactionFailure e) {
t.rollback();
throw e;
} catch (Exception e) {
t.rollback();
throw new TransactionFailure(e.getMessage(), e);
}
}
<T extends ConfigBeanProxy> WriteableView getWriteableView(T s, ConfigBean sourceBean)
throws TransactionFailure {
WriteableView f = new WriteableView(s);
if (sourceBean.getLock().tryLock()) {
return f;
}
throw new TransactionFailure("Config bean already locked " + sourceBean, null);
}
/**
* Returns a writeable view of a configuration object
* @param source the configured interface implementation
* @return the new interface implementation providing write access
*/
public <T extends ConfigBeanProxy> T getWriteableView(final T source)
throws TransactionFailure {
ConfigView sourceBean = (ConfigView) Proxy.getInvocationHandler(source);
WriteableView writeableView = getWriteableView(source, (ConfigBean) sourceBean.getMasterView());
return (T) writeableView.getProxy(sourceBean.getProxyType());
}
/**
* Return the main implementation bean for a proxy.
* @param source configuration interface proxy
* @return the implementation bean
*/
public static ConfigView getImpl(ConfigBeanProxy source) {
Object bean = Proxy.getInvocationHandler(source);
if (bean instanceof ConfigView) {
return ((ConfigView) bean).getMasterView();
} else {
return (ConfigBean) bean;
}
}
/**
* Returns the type of configuration object this config proxy represents.
* @param element is the configuration object
* @return the configuration interface class
*/
public static <T extends ConfigBeanProxy> Class<T> proxyType(T element) {
ConfigView bean = getImpl(element);
return bean.getProxyType();
}
/**
* sort events and dispatch the changes. There will be only one notification of event
* per event type, per object, meaning that if an object has had 3 attributes changes, the
* Changed interface implementation will get notified only once.
*
* @param events of events that resulted of a successful configuration transaction
* @param target the intended receiver of the changes notification
* @param logger to log any issues.
*/
public static UnprocessedChangeEvents sortAndDispatch(PropertyChangeEvent[] events, Changed target, Logger logger) {
List<UnprocessedChangeEvent> unprocessed = new ArrayList<UnprocessedChangeEvent>();
List<Dom> added = new ArrayList<Dom>();
List<Dom> changed = new ArrayList<Dom>();
for (PropertyChangeEvent event : events) {
if (event.getOldValue()==null && event.getNewValue() instanceof ConfigBeanProxy) {
// something was added
try {
final ConfigBeanProxy proxy = ConfigBeanProxy.class.cast(event.getNewValue());
added.add(Dom.unwrap(proxy));
final NotProcessed nc = target.changed(Changed.TYPE.ADD, proxyType(proxy), proxy);
if ( nc != null ) {
unprocessed.add( new UnprocessedChangeEvent(event, nc.getReason() ) );
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Exception while processing config bean changes : ", e);
}
}
}
for (PropertyChangeEvent event : events) {
try {
Dom eventSource = Dom.unwrap((ConfigBeanProxy) event.getSource());
if (added.contains(eventSource)) {
// we don't really send the changed events for new comers.
continue;
}
ConfigBeanProxy proxy = null;
if (event.getNewValue()==null) {
try {
// getOldValue() can be null, we will notify a CHANGE event
proxy = ConfigBeanProxy.class.cast(event.getOldValue());
} catch (ClassCastException e) {
// this is ok, the old value was probably a string or something like this...
// we will notify the event.getSource() that it changed.
}
// new value is null, but not old value, we removed something
if (proxy!=null) {
final NotProcessed nc = target.changed(Changed.TYPE.REMOVE, proxyType(proxy), proxy );
if ( nc != null ) {
unprocessed.add( new UnprocessedChangeEvent(event, nc.getReason() ) );
}
continue;
}
}
// we fall back in this case, the newValue was nullm the old value was also null or was not a ConfigBean,
// we revert to just notify of the change.
// when the new value is not null, we also send the CHANGE on the source all the time, unless this was
// and added config bean.
if (!changed.contains(eventSource)) {
proxy = ConfigBeanProxy.class.cast(event.getSource());
changed.add(eventSource);
final NotProcessed nc = target.changed(Changed.TYPE.CHANGE, proxyType(proxy), proxy);
if ( nc != null ) {
unprocessed.add( new UnprocessedChangeEvent(event, nc.getReason() ) );
}
}
} catch (Exception e) {
logger.log(Level.SEVERE, "Exception while processing config bean changes : ", e);
}
}
return new UnprocessedChangeEvents( unprocessed );
}
// kind of insane, just to get the proper return type for my properties.
static private List<String> defaultPropertyValue() {
return null;
}
public void apply(Map<ConfigBean, Map<String, String>> mapOfChanges) throws TransactionFailure {
Transaction t = new Transaction();
for (Map.Entry<ConfigBean, Map<String, String>> configBeanChange : mapOfChanges.entrySet()) {
ConfigBean source = configBeanChange.getKey();
ConfigBeanProxy readableView = source.getProxy(source.getProxyType());
WriteableView writeable = getWriteableView(readableView, source);
if (!writeable.join(t)) {
t.rollback();
throw new TransactionFailure("Cannot enlist " + source.getProxyType() + " in transaction",null);
}
for (Map.Entry<String, String> change : configBeanChange.getValue().entrySet()) {
String xmlName = change.getKey();
ConfigModel.Property prop = writeable.getProperty(xmlName);
if (prop==null) {
throw new TransactionFailure("Unknown property name " + xmlName + " on " + source.getProxyType(), null);
}
if (prop.isCollection()) {
try {
List<String> values = (List<String>) writeable.getter(prop,
ConfigSupport.class.getDeclaredMethod("defaultPropertyValue", null).getGenericReturnType());
values.add(change.getValue());
} catch (NoSuchMethodException e) {
throw new TransactionFailure("Unknown property name " + xmlName + " on " + source.getProxyType(), null);
}
} else {
writeable.setter(prop, change.getValue(), String.class);
}
}
}
try {
t.commit();
} catch (RetryableException e) {
System.out.println("Retryable...");
// TODO : do something meaninful here
t.rollback();
throw new TransactionFailure(e.getMessage(), e);
} catch (TransactionFailure e) {
System.out.println("failure, not retryable...");
t.rollback();
throw e;
}
}
/**
* Returns the list of sub-elements supported by a ConfigBean
* @return array of classes reprensenting the sub elements of a particular
* @throws ClassNotFoundException for severe errors with the model associated
* with the passed config bean.
*/
public static Class<?>[] getSubElementsTypes(ConfigBean bean)
throws ClassNotFoundException {
List<Class<?>> subTypes = new ArrayList<Class<?>>();
for (ConfigModel.Property element : bean.model.elements.values()) {
if (!element.isLeaf()) {
ConfigModel elementModel = ((ConfigModel.Node) element).model;
Class<?> subType = elementModel.classLoaderHolder.get().loadClass(elementModel.targetTypeName);
subTypes.add(subType);
} else {
if (element.isCollection()) {
subTypes.add(List.class);
}
}
}
return subTypes.toArray(new Class[subTypes.size()]);
}
/**
* Returns the list of attributes names by the passed ConfigBean
* @return array of String for all the attributes names
*/
public String[] getAttributesNames(ConfigBean bean) {
return xmlNames(bean.model.attributes.values());
}
/**
* Returns the list of elements names by the passed ConfigBean
* @return array of String for all the elements names
*/
public String[] getElementsNames(ConfigBean bean) {
return xmlNames(bean.model.elements.values());
}
private String[] xmlNames(Collection<? extends ConfigModel.Property> properties) {
List<String> names = new ArrayList<String>();
for (ConfigModel.Property attribute : properties) {
names.add(attribute.xmlName());
}
return names.toArray(new String[names.size()]);
}
/**
* Creates a new child of the passed child and add it to the parent's live
* list of elements. The child is also initialized with the attributes passed
* where each key represent the xml property name for the attribute and the value
* represent the attribute's value.
*
* This code will be executed within a Transaction and can therefore throw
* a TransactionFailure when the creation or settings of attributes failed.
*
* Example creating a new http-listener element under http-service
* ConfigBean httpService = ... // got it from somwhere.
* Map<String, String> attributes = new HashMap<String, String>();
* attributes.put("id", "jerome-listener");
* attributes.put("enabled", "true");
* ConfigSupport.createAndSet(httpService, HttpListener.class, attributes);
*
* @param parent parent config bean to which the child will be added.
* @param childType child type
* @param attributes map of key value pair to set on the newly created child
* @throws TransactionFailure if the creation or attribute settings failed
*/
public static ConfigBean createAndSet(
final ConfigBean parent,
final Class<? extends ConfigBeanProxy> childType,
final Map<String, String> attributes,
final TransactionCallBack<WriteableView> runnable)
throws TransactionFailure {
return createAndSet(parent, childType, AttributeChanges.from(attributes), runnable);
}
/**
* Creates a new child of the passed child and add it to the parent's live
* list of elements. The child is also initialized with the attributes passed
* where each key represent the xml property name for the attribute and the value
* represent the attribute's value.
*
* This code will be executed within a Transaction and can therefore throw
* a TransactionFailure when the creation or settings of attributes failed.
*
* Example creating a new http-listener element under http-service
* ConfigBean httpService = ... // got it from somwhere.
* Map<String, String> attributes = new HashMap<String, String>();
* attributes.put("id", "jerome-listener");
* attributes.put("enabled", "true");
* ConfigSupport.createAndSet(httpService, HttpListener.class, attributes);
*
* @param parent parent config bean to which the child will be added.
* @param childType child type
* @param attributes list of attribute changes to apply to the newly created child
* @param runnable code that will be invoked as part of the transaction to add
* more attributes or elements to the newly create type
* @throws TransactionFailure if the creation or attribute settings failed
*/
public static ConfigBean createAndSet(
final ConfigBean parent,
final Class<? extends ConfigBeanProxy> childType,
final List<AttributeChanges> attributes,
final TransactionCallBack<WriteableView> runnable)
throws TransactionFailure {
return parent.getHabitat().getComponent(ConfigSupport.class).
_createAndSet(parent, childType, attributes, runnable);
}
ConfigBean _createAndSet(
final ConfigBean parent,
final Class<? extends ConfigBeanProxy> childType,
final List<AttributeChanges> attributes,
final TransactionCallBack<WriteableView> runnable)
throws TransactionFailure {
ConfigBeanProxy readableView = parent.getProxy(parent.getProxyType());
ConfigBeanProxy readableChild = (ConfigBeanProxy)
apply(new SingleConfigCode<ConfigBeanProxy>() {
/**
* Runs the following command passing the configration object. The code will be run
* within a transaction, returning true will commit the transaction, false will abort
* it.
*
* @param param is the configuration object protected by the transaction
* @return any object that should be returned from within the transaction code
* @throws java.beans.PropertyVetoException
* if the changes cannot be applied
* to the configuration
*/
public Object run(ConfigBeanProxy param) throws PropertyVetoException, TransactionFailure {
// create the child
ConfigBeanProxy child = param.createChild(childType);
// add the child to the parent.
WriteableView writeableParent = (WriteableView) Proxy.getInvocationHandler(param);
Class parentProxyType = parent.getProxyType();
Class<?> targetClass = null;
// first we need to find the element associated with this type
ConfigModel.Property element = null;
for (ConfigModel.Property e : parent.model.elements.values()) {
if (e.isLeaf()) {
continue;
}
ConfigModel elementModel = ((ConfigModel.Node) e).model;
if (Logger.getAnonymousLogger().isLoggable(Level.FINE)) {
Logger.getAnonymousLogger().fine( "elementModel.targetTypeName = " + elementModel.targetTypeName +
", collection: " + e.isCollection() + ", childType.getName() = " + childType.getName() );
}
if (elementModel.targetTypeName.equals(childType.getName())) {
element = e;
break;
}
else if ( e.isCollection() ) {
try {
- final Class<?> tempClass = childType.getClassLoader().loadClass( elementModel.targetTypeName);
+ final Class<?> tempClass = elementModel.classLoaderHolder.get().loadClass(elementModel.targetTypeName);
if ( tempClass.isAssignableFrom( childType ) ) {
element = e;
targetClass = tempClass;
break;
}
} catch (Exception ex ) {
throw new TransactionFailure("EXCEPTION getting class for " + elementModel.targetTypeName, ex);
}
}
}
// now depending whether this is a collection or a single leaf,
// we need to process this setting differently
if (element != null) {
if (element.isCollection()) {
// this is kind of nasty, I have to find the method that returns the collection
// object because trying to do a element.get without having the parametized List
// type will not work.
for (Method m : parentProxyType.getMethods()) {
final Class returnType = m.getReturnType();
if (Collection.class.isAssignableFrom(returnType)) {
// this could be it...
if (!(m.getGenericReturnType() instanceof ParameterizedType))
throw new IllegalArgumentException("List needs to be parameterized");
final Class itemType = Types.erasure(Types.getTypeArgument(m.getGenericReturnType(), 0));
if (itemType.isAssignableFrom(childType)) {
List list = null;
try {
list = (List) m.invoke(param, null);
} catch (IllegalAccessException e) {
throw new TransactionFailure("Exception while adding to the parent", e);
} catch (InvocationTargetException e) {
throw new TransactionFailure("Exception while adding to the parent", e);
}
if (list != null) {
list.add(child);
break;
}
}
}
}
} else {
// much simpler, I can use the setter directly.
writeableParent.setter(element, child, childType);
}
} else {
throw new TransactionFailure("Parent " + parent.getProxyType() + " does not have a child of type " + childType);
}
WriteableView writeableChild = (WriteableView) Proxy.getInvocationHandler(child);
applyProperties(writeableChild, attributes);
if (runnable!=null) {
runnable.performOn(writeableChild);
}
return child;
}
}, readableView);
return (ConfigBean) Dom.unwrap(readableChild);
}
private void applyProperties(WriteableView target, List<? extends AttributeChanges> changes)
throws TransactionFailure {
if (changes != null) {
for (AttributeChanges change : changes) {
ConfigModel.Property prop = target.getProperty(change.name);
if (prop == null) {
throw new TransactionFailure("Unknown property name " + change.name + " on " + target.getProxyType());
}
if (prop.isCollection()) {
// we need access to the List
try {
List list = (List) target.getter(prop, ConfigSupport.class.getDeclaredMethod("defaultPropertyValue", null).getGenericReturnType());
for (String value : change.values()) {
list.add(value);
}
} catch (NoSuchMethodException e) {
throw new TransactionFailure(e.getMessage(), e);
}
} else {
target.setter(prop, change.values()[0], String.class);
}
}
}
}
/**
* Creates a new child of the passed child and add it to the parent's live
* list of elements. The child is also initialized with the attributes passed
* where each key represent the xml property name for the attribute and the value
* represent the attribute's value.
*
* This code will be executed within a Transaction and can therefore throw
* a TransactionFailure when the creation or settings of attributes failed.
*
* Example creating a new http-listener element under http-service
* ConfigBean httpService = ... // got it from somwhere.
* Map<String, String> attributes = new HashMap<String, String>();
* attributes.put("id", "jerome-listener");
* attributes.put("enabled", "true");
* ConfigSupport.createAndSet(httpService, HttpListener.class, attributes);
*
* @param parent parent config bean to which the child will be added.
* @param childType child type
* @param attributes list of attributes changes to apply to the new created child
* @throws TransactionFailure if the creation or attribute settings failed
*/
public static ConfigBean createAndSet(
final ConfigBean parent,
final Class<? extends ConfigBeanProxy> childType,
final Map<String, String> attributes)
throws TransactionFailure {
return createAndSet(parent, childType, attributes, null);
}
public ConfigBean createAndSet(
final ConfigBean parent,
final Class<? extends ConfigBeanProxy> childType,
final List<AttributeChanges> attributes)
throws TransactionFailure {
return createAndSet(parent, childType, attributes, null);
}
public static void deleteChild(
final ConfigBean parent,
final ConfigBean child)
throws TransactionFailure {
ConfigBeanProxy readableView = parent.getProxy(parent.getProxyType());
final Class<? extends ConfigBeanProxy> childType = child.getProxyType();
apply(new SingleConfigCode<ConfigBeanProxy>() {
/**
* Runs the following command passing the configration object. The code will be run
* within a transaction, returning true will commit the transaction, false will abort
* it.
*
* @param param is the configuration object protected by the transaction
* @return any object that should be returned from within the transaction code
* @throws java.beans.PropertyVetoException
* if the changes cannot be applied
* to the configuration
*/
public Object run(ConfigBeanProxy param) throws PropertyVetoException, TransactionFailure {
// get the child
ConfigBeanProxy childProxy = child.getProxy(childType);
// remove the child from the parent.
WriteableView writeableParent = (WriteableView) Proxy.getInvocationHandler(param);
Class parentProxyType = parent.getProxyType();
// first we need to find the element associated with this type
ConfigModel.Property element = null;
for (ConfigModel.Property e : parent.model.elements.values()) {
ConfigModel elementModel = ((ConfigModel.Node) e).model;
try {
final Class<?> targetClass = parent.model.classLoaderHolder.get().loadClass(elementModel.targetTypeName);
if (targetClass.isAssignableFrom(childType)) {
element = e;
break;
}
} catch(Exception ex) {
// ok.
}
}
// now depending whether this is a collection or a single leaf,
// we need to process this setting differently
if (element != null) {
if (element.isCollection()) {
// this is kind of nasty, I have to find the method that returns the collection
// object because trying to do a element.get without having the parametized List
// type will not work.
for (Method m : parentProxyType.getMethods()) {
final Class returnType = m.getReturnType();
if (Collection.class.isAssignableFrom(returnType)) {
// this could be it...
if (!(m.getGenericReturnType() instanceof ParameterizedType))
throw new IllegalArgumentException("List needs to be parameterized");
final Class itemType = Types.erasure(Types.getTypeArgument(m.getGenericReturnType(), 0));
if (itemType.isAssignableFrom(childType)) {
List list = null;
try {
list = (List) m.invoke(param, null);
} catch (IllegalAccessException e) {
throw new TransactionFailure("Exception while adding to the parent", e);
} catch (InvocationTargetException e) {
throw new TransactionFailure("Exception while adding to the parent", e);
}
if (list != null) {
list.remove(childProxy);
break;
}
}
}
}
} else {
// much simpler, I can use the setter directly.
writeableParent.setter(element, child, childType);
}
} else {
throw new TransactionFailure("Parent " + parent.getProxyType() + " does not have a child of type " + childType);
}
return child;
}
}, readableView);
}
public interface TransactionCallBack<T> {
public void performOn(T param) throws TransactionFailure;
}
public static abstract class AttributeChanges {
final String name;
AttributeChanges(String name) {
this.name = name;
}
abstract String[] values();
static List<AttributeChanges> from(Map<String, String> values) {
if (values==null) {
return null;
}
List<AttributeChanges> changes = new ArrayList<AttributeChanges>();
for(Map.Entry<String, String> entry : values.entrySet()) {
changes.add(new SingleAttributeChange(entry.getKey(), entry.getValue()));
}
return changes;
}
}
public static class SingleAttributeChange extends AttributeChanges {
final String[] values = new String[1];
public SingleAttributeChange(String name, String value) {
super(name);
values[0] = value;
}
String[] values() {
return values;
}
}
public static class MultipleAttributeChanges extends AttributeChanges {
final String[] values;
public MultipleAttributeChanges(String name, String[] values) {
super(name);
this.values = values;
}
String[] values() {
return values;
}
}
public static Class<? extends ConfigBeanProxy> getElementTypeByName(ConfigBeanProxy parent, String elementName)
throws ClassNotFoundException {
final Dom parentDom = Dom.unwrap(parent);
DomDocument document = parentDom.document;
ConfigModel.Property a = parentDom.model.elements.get(elementName);
if (a!=null) {
if (a.isLeaf()) {
// dochez : I am not too sure, but that should be a String @Element
return null;
} else {
ConfigModel childModel = ((ConfigModel.Node) a).model;
return (Class<? extends ConfigBeanProxy>) childModel.classLoaderHolder.get().loadClass(childModel.targetTypeName);
}
}
// global lookup
ConfigModel model = document.getModelByElementName(elementName);
if (model!=null) {
return (Class<? extends ConfigBeanProxy>) model.classLoaderHolder.get().loadClass(model.targetTypeName);
}
return null;
}
}
| true | true | ConfigBean _createAndSet(
final ConfigBean parent,
final Class<? extends ConfigBeanProxy> childType,
final List<AttributeChanges> attributes,
final TransactionCallBack<WriteableView> runnable)
throws TransactionFailure {
ConfigBeanProxy readableView = parent.getProxy(parent.getProxyType());
ConfigBeanProxy readableChild = (ConfigBeanProxy)
apply(new SingleConfigCode<ConfigBeanProxy>() {
/**
* Runs the following command passing the configration object. The code will be run
* within a transaction, returning true will commit the transaction, false will abort
* it.
*
* @param param is the configuration object protected by the transaction
* @return any object that should be returned from within the transaction code
* @throws java.beans.PropertyVetoException
* if the changes cannot be applied
* to the configuration
*/
public Object run(ConfigBeanProxy param) throws PropertyVetoException, TransactionFailure {
// create the child
ConfigBeanProxy child = param.createChild(childType);
// add the child to the parent.
WriteableView writeableParent = (WriteableView) Proxy.getInvocationHandler(param);
Class parentProxyType = parent.getProxyType();
Class<?> targetClass = null;
// first we need to find the element associated with this type
ConfigModel.Property element = null;
for (ConfigModel.Property e : parent.model.elements.values()) {
if (e.isLeaf()) {
continue;
}
ConfigModel elementModel = ((ConfigModel.Node) e).model;
if (Logger.getAnonymousLogger().isLoggable(Level.FINE)) {
Logger.getAnonymousLogger().fine( "elementModel.targetTypeName = " + elementModel.targetTypeName +
", collection: " + e.isCollection() + ", childType.getName() = " + childType.getName() );
}
if (elementModel.targetTypeName.equals(childType.getName())) {
element = e;
break;
}
else if ( e.isCollection() ) {
try {
final Class<?> tempClass = childType.getClassLoader().loadClass( elementModel.targetTypeName);
if ( tempClass.isAssignableFrom( childType ) ) {
element = e;
targetClass = tempClass;
break;
}
} catch (Exception ex ) {
throw new TransactionFailure("EXCEPTION getting class for " + elementModel.targetTypeName, ex);
}
}
}
// now depending whether this is a collection or a single leaf,
// we need to process this setting differently
if (element != null) {
if (element.isCollection()) {
// this is kind of nasty, I have to find the method that returns the collection
// object because trying to do a element.get without having the parametized List
// type will not work.
for (Method m : parentProxyType.getMethods()) {
final Class returnType = m.getReturnType();
if (Collection.class.isAssignableFrom(returnType)) {
// this could be it...
if (!(m.getGenericReturnType() instanceof ParameterizedType))
throw new IllegalArgumentException("List needs to be parameterized");
final Class itemType = Types.erasure(Types.getTypeArgument(m.getGenericReturnType(), 0));
if (itemType.isAssignableFrom(childType)) {
List list = null;
try {
list = (List) m.invoke(param, null);
} catch (IllegalAccessException e) {
throw new TransactionFailure("Exception while adding to the parent", e);
} catch (InvocationTargetException e) {
throw new TransactionFailure("Exception while adding to the parent", e);
}
if (list != null) {
list.add(child);
break;
}
}
}
}
} else {
// much simpler, I can use the setter directly.
writeableParent.setter(element, child, childType);
}
} else {
throw new TransactionFailure("Parent " + parent.getProxyType() + " does not have a child of type " + childType);
}
WriteableView writeableChild = (WriteableView) Proxy.getInvocationHandler(child);
applyProperties(writeableChild, attributes);
if (runnable!=null) {
runnable.performOn(writeableChild);
}
return child;
}
}, readableView);
return (ConfigBean) Dom.unwrap(readableChild);
}
| ConfigBean _createAndSet(
final ConfigBean parent,
final Class<? extends ConfigBeanProxy> childType,
final List<AttributeChanges> attributes,
final TransactionCallBack<WriteableView> runnable)
throws TransactionFailure {
ConfigBeanProxy readableView = parent.getProxy(parent.getProxyType());
ConfigBeanProxy readableChild = (ConfigBeanProxy)
apply(new SingleConfigCode<ConfigBeanProxy>() {
/**
* Runs the following command passing the configration object. The code will be run
* within a transaction, returning true will commit the transaction, false will abort
* it.
*
* @param param is the configuration object protected by the transaction
* @return any object that should be returned from within the transaction code
* @throws java.beans.PropertyVetoException
* if the changes cannot be applied
* to the configuration
*/
public Object run(ConfigBeanProxy param) throws PropertyVetoException, TransactionFailure {
// create the child
ConfigBeanProxy child = param.createChild(childType);
// add the child to the parent.
WriteableView writeableParent = (WriteableView) Proxy.getInvocationHandler(param);
Class parentProxyType = parent.getProxyType();
Class<?> targetClass = null;
// first we need to find the element associated with this type
ConfigModel.Property element = null;
for (ConfigModel.Property e : parent.model.elements.values()) {
if (e.isLeaf()) {
continue;
}
ConfigModel elementModel = ((ConfigModel.Node) e).model;
if (Logger.getAnonymousLogger().isLoggable(Level.FINE)) {
Logger.getAnonymousLogger().fine( "elementModel.targetTypeName = " + elementModel.targetTypeName +
", collection: " + e.isCollection() + ", childType.getName() = " + childType.getName() );
}
if (elementModel.targetTypeName.equals(childType.getName())) {
element = e;
break;
}
else if ( e.isCollection() ) {
try {
final Class<?> tempClass = elementModel.classLoaderHolder.get().loadClass(elementModel.targetTypeName);
if ( tempClass.isAssignableFrom( childType ) ) {
element = e;
targetClass = tempClass;
break;
}
} catch (Exception ex ) {
throw new TransactionFailure("EXCEPTION getting class for " + elementModel.targetTypeName, ex);
}
}
}
// now depending whether this is a collection or a single leaf,
// we need to process this setting differently
if (element != null) {
if (element.isCollection()) {
// this is kind of nasty, I have to find the method that returns the collection
// object because trying to do a element.get without having the parametized List
// type will not work.
for (Method m : parentProxyType.getMethods()) {
final Class returnType = m.getReturnType();
if (Collection.class.isAssignableFrom(returnType)) {
// this could be it...
if (!(m.getGenericReturnType() instanceof ParameterizedType))
throw new IllegalArgumentException("List needs to be parameterized");
final Class itemType = Types.erasure(Types.getTypeArgument(m.getGenericReturnType(), 0));
if (itemType.isAssignableFrom(childType)) {
List list = null;
try {
list = (List) m.invoke(param, null);
} catch (IllegalAccessException e) {
throw new TransactionFailure("Exception while adding to the parent", e);
} catch (InvocationTargetException e) {
throw new TransactionFailure("Exception while adding to the parent", e);
}
if (list != null) {
list.add(child);
break;
}
}
}
}
} else {
// much simpler, I can use the setter directly.
writeableParent.setter(element, child, childType);
}
} else {
throw new TransactionFailure("Parent " + parent.getProxyType() + " does not have a child of type " + childType);
}
WriteableView writeableChild = (WriteableView) Proxy.getInvocationHandler(child);
applyProperties(writeableChild, attributes);
if (runnable!=null) {
runnable.performOn(writeableChild);
}
return child;
}
}, readableView);
return (ConfigBean) Dom.unwrap(readableChild);
}
|
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java
index 56ecdbac..3638f498 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/QuickSettings.java
@@ -1,1799 +1,1803 @@
/*
* Copyright (C) 2012 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.systemui.statusbar.phone;
import com.android.internal.view.RotationPolicy;
import com.android.internal.widget.LockPatternUtils;
import com.android.systemui.R;
import com.android.systemui.statusbar.phone.QuickSettingsModel.BluetoothState;
import com.android.systemui.statusbar.phone.QuickSettingsModel.RSSIState;
import com.android.systemui.statusbar.phone.QuickSettingsModel.State;
import com.android.systemui.statusbar.phone.QuickSettingsModel.UserState;
import com.android.systemui.statusbar.phone.QuickSettingsModel.WifiState;
import com.android.systemui.statusbar.policy.BatteryController;
import com.android.systemui.statusbar.policy.BluetoothController;
import com.android.systemui.statusbar.policy.BrightnessController;
import com.android.systemui.statusbar.policy.LocationController;
import com.android.systemui.statusbar.policy.NetworkController;
import com.android.systemui.statusbar.policy.Prefs;
import com.android.systemui.statusbar.policy.ToggleSlider;
import android.app.Activity;
import android.app.ActivityManagerNative;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.UserInfo;
import android.content.res.Resources;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.hardware.display.DisplayManager;
import android.hardware.display.WifiDisplayStatus;
import android.location.LocationManager;
import android.nfc.NfcAdapter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Profile;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManagerGlobal;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.internal.telephony.PhoneConstants;
import com.android.systemui.aokp.AokpTarget;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
/**
*
*/
class QuickSettings {
private static final String TAG = "QuickSettings";
public static final boolean SHOW_IME_TILE = false;
private static final String TOGGLE_PIPE = "|";
private static final int USER_TILE = 0;
private static final int BRIGHTNESS_TILE = 1;
private static final int SETTINGS_TILE = 2;
private static final int WIFI_TILE = 3;
private static final int SIGNAL_TILE = 4;
private static final int ROTATE_TILE = 5;
private static final int CLOCK_TILE = 6;
private static final int GPS_TILE = 7;
private static final int IME_TILE = 8;
private static final int BATTERY_TILE = 9;
private static final int AIRPLANE_TILE = 10;
private static final int BLUETOOTH_TILE = 11;
private static final int SWAGGER_TILE = 12;
private static final int VIBRATE_TILE = 13;
private static final int SILENT_TILE = 14;
private static final int FCHARGE_TILE = 15;
private static final int SYNC_TILE = 16;
private static final int NFC_TILE = 17;
private static final int TORCH_TILE = 18;
private static final int WIFI_TETHER_TILE = 19;
private static final int USB_TETHER_TILE = 20;
private static final int TWOG_TILE = 21;
private static final int LTE_TILE = 22;
private static final int FAV_CONTACT_TILE = 23;
// private static final int BT_TETHER_TILE = 23;
private static final int SOUND_STATE_TILE = 24;
public static final String USER_TOGGLE = "USER";
public static final String BRIGHTNESS_TOGGLE = "BRIGHTNESS";
public static final String SETTINGS_TOGGLE = "SETTINGS";
public static final String WIFI_TOGGLE = "WIFI";
public static final String SIGNAL_TOGGLE = "SIGNAL";
public static final String ROTATE_TOGGLE = "ROTATE";
public static final String CLOCK_TOGGLE = "CLOCK";
public static final String GPS_TOGGLE = "GPS";
public static final String IME_TOGGLE = "IME";
public static final String BATTERY_TOGGLE = "BATTERY";
public static final String AIRPLANE_TOGGLE = "AIRPLANE_MODE";
public static final String BLUETOOTH_TOGGLE = "BLUETOOTH";
public static final String SWAGGER_TOGGLE = "SWAGGER";
public static final String VIBRATE_TOGGLE = "VIBRATE";
public static final String SILENT_TOGGLE = "SILENT";
public static final String FCHARGE_TOGGLE = "FCHARGE";
public static final String SYNC_TOGGLE = "SYNC";
public static final String NFC_TOGGLE = "NFC";
public static final String TORCH_TOGGLE = "TORCH";
public static final String WIFI_TETHER_TOGGLE = "WIFITETHER";
// public static final String BT_TETHER_TOGGLE = "BTTETHER";
public static final String USB_TETHER_TOGGLE = "USBTETHER";
public static final String TWOG_TOGGLE = "2G";
public static final String LTE_TOGGLE = "LTE";
public static final String FAV_CONTACT_TOGGLE = "FAVCONTACT";
public static final String SOUND_STATE_TOGGLE = "SOUNDSTATE";
private static final String DEFAULT_TOGGLES = "default";
private int mWifiApState = WifiManager.WIFI_AP_STATE_DISABLED;
private int mWifiState = WifiManager.WIFI_STATE_DISABLED;
private int mDataState = -1;
private boolean usbTethered;
private Context mContext;
private PanelBar mBar;
private QuickSettingsModel mModel;
private ViewGroup mContainerView;
private DisplayManager mDisplayManager;
private WifiDisplayStatus mWifiDisplayStatus;
private WifiManager wifiManager;
private ConnectivityManager connManager;
private LocationManager locationManager;
private PhoneStatusBar mStatusBarService;
private BluetoothState mBluetoothState;
private TelephonyManager tm;
private ConnectivityManager mConnService;
private NfcAdapter mNfcAdapter;
private AokpTarget mAokpTarget;
private BrightnessController mBrightnessController;
private BluetoothController mBluetoothController;
private Dialog mBrightnessDialog;
private int mBrightnessDialogShortTimeout;
private int mBrightnessDialogLongTimeout;
private AsyncTask<Void, Void, Pair<String, Drawable>> mUserInfoTask;
private AsyncTask<Void, Void, Pair<String, Drawable>> mFavContactInfoTask;
private LevelListDrawable mBatteryLevels;
private LevelListDrawable mChargingBatteryLevels;
boolean mTilesSetUp = false;
private Handler mHandler;
private ArrayList<String> toggles;
private String userToggles = null;
private long tacoSwagger = 0;
private boolean tacoToggle = false;
private int mTileTextSize = 12;
private String mFastChargePath;
private HashMap<String, Integer> toggleMap;
private HashMap<String, Integer> getToggleMap() {
if (toggleMap == null) {
toggleMap = new HashMap<String, Integer>();
toggleMap.put(USER_TOGGLE, USER_TILE);
toggleMap.put(BRIGHTNESS_TOGGLE, BRIGHTNESS_TILE);
toggleMap.put(SETTINGS_TOGGLE, SETTINGS_TILE);
toggleMap.put(WIFI_TOGGLE, WIFI_TILE);
toggleMap.put(SIGNAL_TOGGLE, SIGNAL_TILE);
toggleMap.put(ROTATE_TOGGLE, ROTATE_TILE);
toggleMap.put(CLOCK_TOGGLE, CLOCK_TILE);
toggleMap.put(GPS_TOGGLE, GPS_TILE);
toggleMap.put(IME_TOGGLE, IME_TILE);
toggleMap.put(BATTERY_TOGGLE, BATTERY_TILE);
toggleMap.put(AIRPLANE_TOGGLE, AIRPLANE_TILE);
toggleMap.put(BLUETOOTH_TOGGLE, BLUETOOTH_TILE);
toggleMap.put(VIBRATE_TOGGLE, VIBRATE_TILE);
toggleMap.put(SILENT_TOGGLE, SILENT_TILE);
toggleMap.put(FCHARGE_TOGGLE, FCHARGE_TILE);
toggleMap.put(SYNC_TOGGLE, SYNC_TILE);
toggleMap.put(NFC_TOGGLE, NFC_TILE);
toggleMap.put(TORCH_TOGGLE, TORCH_TILE);
toggleMap.put(WIFI_TETHER_TOGGLE, WIFI_TETHER_TILE);
toggleMap.put(USB_TETHER_TOGGLE, USB_TETHER_TILE);
toggleMap.put(TWOG_TOGGLE, TWOG_TILE);
toggleMap.put(LTE_TOGGLE, LTE_TILE);
toggleMap.put(FAV_CONTACT_TOGGLE, FAV_CONTACT_TILE);
toggleMap.put(SOUND_STATE_TOGGLE, SOUND_STATE_TILE);
//toggleMap.put(BT_TETHER_TOGGLE, BT_TETHER_TILE);
}
return toggleMap;
}
private final RotationPolicy.RotationPolicyListener mRotationPolicyListener =
new RotationPolicy.RotationPolicyListener() {
@Override
public void onChange() {
mModel.onRotationLockChanged();
}
};
public QuickSettings(Context context, QuickSettingsContainerView container) {
mDisplayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
mContext = context;
mContainerView = container;
mModel = new QuickSettingsModel(context);
mWifiDisplayStatus = new WifiDisplayStatus();
wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
connManager = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
mBluetoothState = new QuickSettingsModel.BluetoothState();
mHandler = new Handler();
mAokpTarget = new AokpTarget(mContext);
Resources r = mContext.getResources();
mBatteryLevels = (LevelListDrawable) r.getDrawable(R.drawable.qs_sys_battery);
mChargingBatteryLevels =
(LevelListDrawable) r.getDrawable(R.drawable.qs_sys_battery_charging);
mBrightnessDialogLongTimeout =
r.getInteger(R.integer.quick_settings_brightness_dialog_long_timeout);
mBrightnessDialogShortTimeout =
r.getInteger(R.integer.quick_settings_brightness_dialog_short_timeout);
mFastChargePath = r.getString(com.android.internal.R.string.config_fastChargePath);
IntentFilter filter = new IntentFilter();
filter.addAction(DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(Intent.ACTION_USER_SWITCHED);
filter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
mContext.registerReceiver(mReceiver, filter);
IntentFilter profileFilter = new IntentFilter();
profileFilter.addAction(ContactsContract.Intents.ACTION_PROFILE_CHANGED);
profileFilter.addAction(Intent.ACTION_USER_INFO_CHANGED);
mContext.registerReceiverAsUser(mProfileReceiver, UserHandle.ALL, profileFilter,
null, null);
new SettingsObserver(new Handler()).observe();
new SoundObserver(new Handler()).observe();
new NetworkModeObserver(new Handler()).observe();
}
public void setBar(PanelBar bar) {
mBar = bar;
}
public void setService(PhoneStatusBar phoneStatusBar) {
mStatusBarService = phoneStatusBar;
}
public PhoneStatusBar getService() {
return mStatusBarService;
}
public void setImeWindowStatus(boolean visible) {
mModel.onImeWindowStatusChanged(visible);
}
public void setup(NetworkController networkController, BluetoothController bluetoothController,
BatteryController batteryController, LocationController locationController) {
mBluetoothController = bluetoothController;
setupQuickSettings();
updateWifiDisplayStatus();
updateResources();
ArrayList<String> userTiles = getCustomUserTiles();
if (userTiles.contains(SIGNAL_TOGGLE) || userTiles.contains(WIFI_TOGGLE))
networkController.addNetworkSignalChangedCallback(mModel);
if (userTiles.contains(BLUETOOTH_TOGGLE))
bluetoothController.addStateChangedCallback(mModel);
if (userTiles.contains(BATTERY_TOGGLE))
batteryController.addStateChangedCallback(mModel);
if (userTiles.contains(GPS_TOGGLE))
locationController.addStateChangedCallback(mModel);
if (userTiles.contains(ROTATE_TOGGLE))
RotationPolicy.registerRotationPolicyListener(mContext, mRotationPolicyListener,
UserHandle.USER_ALL);
}
private void queryForUserInformation() {
Context currentUserContext = null;
UserInfo userInfo = null;
try {
userInfo = ActivityManagerNative.getDefault().getCurrentUser();
currentUserContext = mContext.createPackageContextAsUser("android", 0,
new UserHandle(userInfo.id));
} catch (NameNotFoundException e) {
Log.e(TAG, "Couldn't create user context", e);
throw new RuntimeException(e);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't get user info", e);
}
final int userId = userInfo.id;
final String userName = userInfo.name;
final Context context = currentUserContext;
mUserInfoTask = new AsyncTask<Void, Void, Pair<String, Drawable>>() {
@Override
protected Pair<String, Drawable> doInBackground(Void... params) {
final UserManager um =
(UserManager) mContext.getSystemService(Context.USER_SERVICE);
// Fall back to the UserManager nickname if we can't read the
// name from the local
// profile below.
String name = userName;
Drawable avatar = null;
Bitmap rawAvatar = um.getUserIcon(userId);
if (rawAvatar != null) {
avatar = new BitmapDrawable(mContext.getResources(), rawAvatar);
} else {
avatar = mContext.getResources().getDrawable(R.drawable.ic_qs_default_user);
}
// If it's a single-user device, get the profile name, since the
// nickname is not
// usually valid
if (um.getUsers().size() <= 1) {
// Try and read the display name from the local profile
final Cursor cursor = context.getContentResolver().query(
Profile.CONTENT_URI, new String[] {
Phone._ID, Phone.DISPLAY_NAME
},
null, null, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
}
return new Pair<String, Drawable>(name, avatar);
}
@Override
protected void onPostExecute(Pair<String, Drawable> result) {
super.onPostExecute(result);
mModel.setUserTileInfo(result.first, result.second);
mUserInfoTask = null;
}
};
mUserInfoTask.execute();
}
private void queryForFavContactInformation() {
mFavContactInfoTask = new AsyncTask<Void, Void, Pair<String, Drawable>>() {
@Override
protected Pair<String, Drawable> doInBackground(Void... params) {
String name = "";
Drawable avatar = mContext.getResources().getDrawable(R.drawable.ic_qs_default_user);
Bitmap rawAvatar = null;
String lookupKey = Settings.System.getString(mContext.getContentResolver(),
Settings.System.QUICK_TOGGLE_FAV_CONTACT);
if (lookupKey != null && lookupKey.length() > 0) {
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
Uri res = ContactsContract.Contacts.lookupContact(mContext.getContentResolver(), lookupUri);
String[] projection = new String[] {
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_URI,
ContactsContract.Contacts.LOOKUP_KEY};
final Cursor cursor = mContext.getContentResolver().query(res,projection,null,null,null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
InputStream input = ContactsContract.Contacts.
openContactPhotoInputStream(mContext.getContentResolver(), res, true);
if (input != null) {
rawAvatar = BitmapFactory.decodeStream(input);
}
if (rawAvatar != null) {
avatar = new BitmapDrawable(mContext.getResources(), rawAvatar);
}
}
return new Pair<String, Drawable>(name, avatar);
}
@Override
protected void onPostExecute(Pair<String, Drawable> result) {
super.onPostExecute(result);
mModel.setFavContactTileInfo(result.first, result.second);
mFavContactInfoTask = null;
}
};
mFavContactInfoTask.execute();
}
private void setupQuickSettings() {
// Setup the tiles that we are going to be showing (including the
// temporary ones)
LayoutInflater inflater = LayoutInflater.from(mContext);
addUserTiles(mContainerView, inflater);
addTemporaryTiles(mContainerView, inflater);
queryForUserInformation();
queryForFavContactInformation();
mTilesSetUp = true;
}
private void startSettingsActivity(String action) {
Intent intent = new Intent(action);
startSettingsActivity(intent);
}
private void startSettingsActivity(Intent intent) {
startSettingsActivity(intent, true);
}
private void startSettingsActivity(Intent intent, boolean onlyProvisioned) {
if (onlyProvisioned && !getService().isDeviceProvisioned())
return;
try {
// Dismiss the lock screen when Settings starts.
ActivityManagerNative.getDefault().dismissKeyguardOnNextActivity();
} catch (RemoteException e) {
}
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
getService().animateCollapsePanels();
}
private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) {
final Resources r = mContext.getResources();
QuickSettingsTileView quick = null;
switch (tile) {
case USER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_user, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
final UserManager um =
(UserManager) mContext.getSystemService(Context.USER_SERVICE);
if (um.getUsers(true).size() > 1) {
try {
WindowManagerGlobal.getWindowManagerService().lockNow(null);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't show user switcher", e);
}
} else {
Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
mContext, v, ContactsContract.Profile.CONTENT_URI,
ContactsContract.QuickContact.MODE_LARGE, null);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
}
}
});
mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
UserState us = (UserState) state;
ImageView iv = (ImageView) view.findViewById(R.id.user_imageview);
TextView tv = (TextView) view.findViewById(R.id.user_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
iv.setImageDrawable(us.avatar);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_user, state.label));
}
});
break;
case CLOCK_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_time, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider"));
intent.addCategory("android.intent.category.LAUNCHER");
startSettingsActivity(intent);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(Intent.ACTION_QUICK_CLOCK);
return true;
}
});
mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State alarmState) {
TextView tv = (TextView) view.findViewById(R.id.clock_textview);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SIGNAL_TILE:
if (mModel.deviceSupportsTelephony()) {
// Mobile Network state
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rssi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true);
String strData = connManager.getMobileDataEnabled() ?
r.getString(R.string.quick_settings_data_off_label)
: r.getString(R.string.quick_settings_data_on_label);
Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.android.settings",
"com.android.settings.Settings$DataUsageSummaryActivity"));
startSettingsActivity(intent);
return true;
}
});
mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
RSSIState rssiState = (RSSIState) state;
ImageView iv = (ImageView) view.findViewById(R.id.rssi_image);
ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image);
TextView tv = (TextView) view.findViewById(R.id.rssi_textview);
iv.setImageResource(rssiState.signalIconId);
if (rssiState.dataTypeIconId > 0) {
iov.setImageResource(rssiState.dataTypeIconId);
} else {
iov.setImageDrawable(null);
}
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getResources().getString(
R.string.accessibility_quick_settings_mobile,
rssiState.signalContentDescription, rssiState.dataContentDescription,
state.label));
}
});
}
break;
case BRIGHTNESS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_brightness, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
showBrightnessDialog();
}
});
mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.brightness_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
dismissBrightnessDialog(mBrightnessDialogShortTimeout);
}
});
break;
case SETTINGS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_settings, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SETTINGS);
}
});
mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.settings_tileview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case WIFI_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWifiState = wifiManager.getWifiState();
if (mWifiState == WifiManager.WIFI_STATE_DISABLED
|| mWifiState == WifiManager.WIFI_STATE_DISABLING) {
changeWifiState(true);
} else {
changeWifiState(false);
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS);
return true;
}
});
mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
WifiState wifiState = (WifiState) state;
TextView tv = (TextView) view.findViewById(R.id.wifi_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0);
tv.setText(wifiState.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_wifi,
wifiState.signalContentDescription,
(wifiState.connected) ? wifiState.label : ""));
}
});
break;
case TWOG_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_twog, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) {
tm.toggle2G(false);
} else {
tm.toggle2G(true);
}
mModel.refresh2gTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
return true;
}
});
mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.twog_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case LTE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_lte, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO
|| mDataState == PhoneConstants.NT_MODE_GLOBAL) {
tm.toggleLTE(false);
} else {
tm.toggleLTE(true);
}
mModel.refreshLTETile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.lte_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case VIBRATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_vibrate, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_VIB);
mModel.refreshVibrateTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.vibrate_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SILENT_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_silent, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT);
mModel.refreshSilentTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.silent_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SOUND_STATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_sound_state, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT_VIB);
mModel.refreshSoundStateTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addSoundStateTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.sound_state_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case TORCH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_torch, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// maybe something here?
return true;
}
});
mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.torch_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case FCHARGE_TILE:
if((mFastChargePath == null || mFastChargePath.isEmpty()) ||
!new File(mFastChargePath).exists()) {
// config not set or config set and kernel doesn't support it?
break;
}
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_fcharge, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setFastCharge(!Prefs.getLastFastChargeState(mContext));
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// What do we put here?
return true;
}
});
mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.fcharge_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
restoreFChargeState();
break;
case WIFI_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWifiApState = wifiManager.getWifiApState();
if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED
|| mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) {
changeWifiApState(true);
} else {
changeWifiApState(false);
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
- startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
+ Intent intent = new Intent();
+ intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity"));
+ startSettingsActivity(intent);
return true;
}
});
mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case USB_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = updateUsbState() ? false : true;
if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
mHandler.postDelayed(delayedRefresh, 1000);
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
- startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
+ Intent intent = new Intent();
+ intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity"));
+ startSettingsActivity(intent);
return true;
}
});
mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SYNC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_sync, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = ContentResolver.getMasterSyncAutomatically();
ContentResolver.setMasterSyncAutomatically(enabled ? false : true);
mModel.refreshSyncTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS);
return true;
}
});
mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.sync_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case NFC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_nfc, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = false;
if (mNfcAdapter == null) {
mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext);
}
try {
enabled = mNfcAdapter.isEnabled();
if (enabled) {
mNfcAdapter.disable();
} else {
mNfcAdapter.enable();
}
} catch (NullPointerException ex) {
// we'll ignore this click
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.nfc_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case ROTATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean locked = RotationPolicy.isRotationLocked(mContext);
RotationPolicy.setRotationLock(mContext, !locked);
}
});
mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BATTERY_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_battery, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY);
}
});
mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
QuickSettingsModel.BatteryState batteryState =
(QuickSettingsModel.BatteryState) state;
TextView tv = (TextView) view.findViewById(R.id.battery_textview);
ImageView iv = (ImageView) view.findViewById(R.id.battery_image);
Drawable d = batteryState.pluggedIn
? mChargingBatteryLevels
: mBatteryLevels;
String t;
if (batteryState.batteryLevel == 100) {
t = mContext.getString(R.string.quick_settings_battery_charged_label);
} else {
t = batteryState.pluggedIn
? mContext.getString(R.string.quick_settings_battery_charging_label,
batteryState.batteryLevel)
: mContext.getString(R.string.status_bar_settings_battery_meter_format,
batteryState.batteryLevel);
}
iv.setImageDrawable(d);
iv.setImageLevel(batteryState.batteryLevel);
tv.setText(t);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_battery, t));
}
});
break;
case AIRPLANE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_airplane, inflater);
mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
String airplaneState = mContext.getString(
(state.enabled) ? R.string.accessibility_desc_on
: R.string.accessibility_desc_off);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState));
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BLUETOOTH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter.isEnabled()) {
adapter.disable();
} else {
adapter.enable();
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
return true;
}
});
mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
BluetoothState bluetoothState = (BluetoothState) state;
TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
Resources r = mContext.getResources();
String label = state.label;
/*
* //TODO: Show connected bluetooth device label
* Set<BluetoothDevice> btDevices =
* mBluetoothController.getBondedBluetoothDevices(); if
* (btDevices.size() == 1) { // Show the name of the
* bluetooth device you are connected to label =
* btDevices.iterator().next().getName(); } else if
* (btDevices.size() > 1) { // Show a generic label
* about the number of bluetooth devices label =
* r.getString(R.string
* .quick_settings_bluetooth_multiple_devices_label,
* btDevices.size()); }
*/
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_bluetooth,
bluetoothState.stateContentDescription));
tv.setText(label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case GPS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_location, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(),
LocationManager.GPS_PROVIDER, gpsEnabled ? false : true);
TextView tv = (TextView) v.findViewById(R.id.location_textview);
tv.setText(gpsEnabled ? R.string.quick_settings_gps_off_label
: R.string.quick_settings_gps_on_label);
tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ?
R.drawable.ic_qs_gps_off : R.drawable.ic_qs_gps_on, 0, 0);
tv.setTextSize(1, mTileTextSize);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
return true;
}
});
mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
TextView tv = (TextView) view.findViewById(R.id.location_textview);
tv.setText(gpsEnabled
? R.string.quick_settings_gps_on_label
: R.string.quick_settings_gps_off_label);
if (state.iconId == 0) {
tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ?
R.drawable.ic_qs_gps_on : R.drawable.ic_qs_gps_off, 0, 0);
}
else {
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
}
tv.setTextSize(1, mTileTextSize);
}
});
break;
case IME_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_ime, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mBar.collapseAllPanels(true);
Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
pendingIntent.send();
} catch (Exception e) {
}
}
});
mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.ime_textview);
if (state.label != null) {
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
}
});
break;
case FAV_CONTACT_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_user, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String lookupKey = Settings.System.getString(mContext.getContentResolver(),
Settings.System.QUICK_TOGGLE_FAV_CONTACT);
if (lookupKey != null && lookupKey.length() > 0) {
mBar.collapseAllPanels(true);
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
Uri res = ContactsContract.Contacts.lookupContact(mContext.getContentResolver(), lookupUri);
Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
mContext, v, res,
ContactsContract.QuickContact.MODE_LARGE, null);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
}
}
});
mModel.addFavContactTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
UserState us = (UserState) state;
ImageView iv = (ImageView) view.findViewById(R.id.user_imageview);
TextView tv = (TextView) view.findViewById(R.id.user_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
iv.setImageDrawable(us.avatar);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_user, state.label));
}
});
break;
}
return quick;
}
private ArrayList<String> getCustomUserTiles() {
ArrayList<String> tiles = new ArrayList<String>();
if (userToggles == null)
return getDefaultTiles();
String[] splitter = userToggles.split("\\" + TOGGLE_PIPE);
for (String toggle : splitter) {
tiles.add(toggle);
}
return tiles;
}
private ArrayList<String> getDefaultTiles() {
ArrayList<String> tiles = new ArrayList<String>();
tiles.add(USER_TOGGLE);
tiles.add(BRIGHTNESS_TOGGLE);
tiles.add(SETTINGS_TOGGLE);
tiles.add(WIFI_TOGGLE);
if (mModel.deviceSupportsTelephony()) {
tiles.add(SIGNAL_TOGGLE);
}
if (mContext.getResources().getBoolean(R.bool.quick_settings_show_rotation_lock)) {
tiles.add(ROTATE_TOGGLE);
}
tiles.add(BATTERY_TOGGLE);
tiles.add(AIRPLANE_TOGGLE);
if (mModel.deviceSupportsBluetooth()) {
tiles.add(BLUETOOTH_TOGGLE);
}
return tiles;
}
private void addUserTiles(ViewGroup parent, LayoutInflater inflater) {
if (parent.getChildCount() > 0)
parent.removeAllViews();
toggles = getCustomUserTiles();
if (!toggles.get(0).equals("")) {
for (String toggle : toggles) {
View v = getTile(getToggleMap().get(toggle), parent, inflater);
if(v != null) {
parent.addView(v);
}
}
}
}
private void addTemporaryTiles(final ViewGroup parent, final LayoutInflater inflater) {
// Alarm tile
QuickSettingsTileView alarmTile = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
alarmTile.setContent(R.layout.quick_settings_tile_alarm, inflater);
alarmTile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO: Jump into the alarm application
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.android.deskclock",
"com.android.deskclock.AlarmClock"));
startSettingsActivity(intent);
}
});
mModel.addAlarmTile(alarmTile, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State alarmState) {
TextView tv = (TextView) view.findViewById(R.id.alarm_textview);
tv.setText(alarmState.label);
tv.setTextSize(1, mTileTextSize);
view.setVisibility(alarmState.enabled ? View.VISIBLE : View.GONE);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_alarm, alarmState.label));
}
});
parent.addView(alarmTile);
// Wifi Display
QuickSettingsTileView wifiDisplayTile = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
wifiDisplayTile.setContent(R.layout.quick_settings_tile_wifi_display, inflater);
wifiDisplayTile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIFI_DISPLAY_SETTINGS);
}
});
mModel.addWifiDisplayTile(wifiDisplayTile, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.wifi_display_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
view.setVisibility(state.enabled ? View.VISIBLE : View.GONE);
}
});
parent.addView(wifiDisplayTile);
// Bug reports
QuickSettingsTileView bugreportTile = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
bugreportTile.setContent(R.layout.quick_settings_tile_bugreport, inflater);
bugreportTile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
showBugreportDialog();
}
});
mModel.addBugreportTile(bugreportTile, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
view.setVisibility(state.enabled ? View.VISIBLE : View.GONE);
}
});
parent.addView(bugreportTile);
/*
* QuickSettingsTileView mediaTile = (QuickSettingsTileView)
* inflater.inflate(R.layout.quick_settings_tile, parent, false);
* mediaTile.setContent(R.layout.quick_settings_tile_media, inflater);
* parent.addView(mediaTile); QuickSettingsTileView imeTile =
* (QuickSettingsTileView)
* inflater.inflate(R.layout.quick_settings_tile, parent, false);
* imeTile.setContent(R.layout.quick_settings_tile_ime, inflater);
* imeTile.setOnClickListener(new View.OnClickListener() {
* @Override public void onClick(View v) { parent.removeViewAt(0); } });
* parent.addView(imeTile);
*/
}
void updateResources() {
Resources r = mContext.getResources();
// Update the model
mModel.updateResources(getCustomUserTiles());
((QuickSettingsContainerView) mContainerView).updateResources();
mContainerView.requestLayout();
// Reset the dialog
boolean isBrightnessDialogVisible = false;
if (mBrightnessDialog != null) {
removeAllBrightnessDialogCallbacks();
isBrightnessDialogVisible = mBrightnessDialog.isShowing();
mBrightnessDialog.dismiss();
}
mBrightnessDialog = null;
if (isBrightnessDialogVisible) {
showBrightnessDialog();
}
}
private void removeAllBrightnessDialogCallbacks() {
mHandler.removeCallbacks(mDismissBrightnessDialogRunnable);
}
private Runnable mDismissBrightnessDialogRunnable = new Runnable() {
public void run() {
if (mBrightnessDialog != null && mBrightnessDialog.isShowing()) {
mBrightnessDialog.dismiss();
}
removeAllBrightnessDialogCallbacks();
};
};
private void showBrightnessDialog() {
if (mBrightnessDialog == null) {
mBrightnessDialog = new Dialog(mContext);
mBrightnessDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
mBrightnessDialog.setContentView(R.layout.quick_settings_brightness_dialog);
mBrightnessDialog.setCanceledOnTouchOutside(true);
mBrightnessController = new BrightnessController(mContext,
(ImageView) mBrightnessDialog.findViewById(R.id.brightness_icon),
(ToggleSlider) mBrightnessDialog.findViewById(R.id.brightness_slider));
mBrightnessController.addStateChangedCallback(mModel);
mBrightnessDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
mBrightnessController = null;
}
});
mBrightnessDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
mBrightnessDialog.getWindow().getAttributes().privateFlags |=
WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS;
mBrightnessDialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
if (!mBrightnessDialog.isShowing()) {
try {
WindowManagerGlobal.getWindowManagerService().dismissKeyguard();
} catch (RemoteException e) {
}
mBrightnessDialog.show();
dismissBrightnessDialog(mBrightnessDialogLongTimeout);
}
}
private void dismissBrightnessDialog(int timeout) {
removeAllBrightnessDialogCallbacks();
if (mBrightnessDialog != null) {
mHandler.postDelayed(mDismissBrightnessDialogRunnable, timeout);
}
}
private void showBugreportDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setPositiveButton(com.android.internal.R.string.report, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
// Add a little delay before executing, to give the
// dialog a chance to go away before it takes a
// screenshot.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
ActivityManagerNative.getDefault()
.requestBugReport();
} catch (RemoteException e) {
}
}
}, 500);
}
}
});
builder.setMessage(com.android.internal.R.string.bugreport_message);
builder.setTitle(com.android.internal.R.string.bugreport_title);
builder.setCancelable(true);
final Dialog dialog = builder.create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
try {
WindowManagerGlobal.getWindowManagerService().dismissKeyguard();
} catch (RemoteException e) {
}
dialog.show();
}
private void updateWifiDisplayStatus() {
mWifiDisplayStatus = mDisplayManager.getWifiDisplayStatus();
applyWifiDisplayStatus();
}
private void applyWifiDisplayStatus() {
mModel.onWifiDisplayStateChanged(mWifiDisplayStatus);
}
private void applyBluetoothStatus() {
mModel.onBluetoothStateChange(mBluetoothState);
}
void reloadUserInfo() {
if (mUserInfoTask != null) {
mUserInfoTask.cancel(false);
mUserInfoTask = null;
}
if (mTilesSetUp) {
queryForUserInformation();
}
}
void reloadFavContactInfo() {
if (mFavContactInfoTask != null) {
mFavContactInfoTask.cancel(false);
mFavContactInfoTask = null;
}
if (mTilesSetUp) {
queryForFavContactInformation();
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (DisplayManager.ACTION_WIFI_DISPLAY_STATUS_CHANGED.equals(action)) {
WifiDisplayStatus status = (WifiDisplayStatus) intent.getParcelableExtra(
DisplayManager.EXTRA_WIFI_DISPLAY_STATUS);
mWifiDisplayStatus = status;
applyWifiDisplayStatus();
} else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
mBluetoothState.enabled = (state == BluetoothAdapter.STATE_ON);
applyBluetoothStatus();
} else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
int status = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
BluetoothAdapter.STATE_DISCONNECTED);
mBluetoothState.connected = (status == BluetoothAdapter.STATE_CONNECTED);
applyBluetoothStatus();
} else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
reloadUserInfo();
reloadFavContactInfo();
} else if (WifiManager.WIFI_AP_STATE_CHANGED_ACTION.equals(action)) {
mHandler.postDelayed(delayedRefresh, 1000);
}
}
};
private final BroadcastReceiver mProfileReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (ContactsContract.Intents.ACTION_PROFILE_CHANGED.equals(action) ||
Intent.ACTION_USER_INFO_CHANGED.equals(action)) {
try {
final int userId = ActivityManagerNative.getDefault().getCurrentUser().id;
if (getSendingUserId() == userId) {
reloadUserInfo();
reloadFavContactInfo();
}
} catch (RemoteException e) {
Log.e(TAG, "Couldn't get current user id for profile change", e);
}
}
}
};
private void setFastCharge(final boolean on) {
Intent fastChargeIntent = new Intent("com.android.settings.ACTION_CHANGE_FCHARGE_STATE");
fastChargeIntent.setPackage("com.android.settings");
fastChargeIntent.putExtra("newState", on);
mContext.sendBroadcast(fastChargeIntent);
mHandler.postDelayed(new Runnable() {
public void run() {
mModel.refreshFChargeTile();
}
}, 250);
}
private void changeWifiApState(final boolean desiredState) {
if (wifiManager == null) {
return;
}
AsyncTask.execute(new Runnable() {
public void run() {
int wifiState = wifiManager.getWifiState();
if (desiredState
&& ((wifiState == WifiManager.WIFI_STATE_ENABLING)
|| (wifiState == WifiManager.WIFI_STATE_ENABLED))) {
wifiManager.setWifiEnabled(false);
}
wifiManager.setWifiApEnabled(null, desiredState);
return;
}
});
}
private void changeWifiState(final boolean desiredState) {
if (wifiManager == null) {
return;
}
AsyncTask.execute(new Runnable() {
public void run() {
int wifiApState = wifiManager.getWifiApState();
if (desiredState
&& ((wifiApState == WifiManager.WIFI_AP_STATE_ENABLING)
|| (wifiApState == WifiManager.WIFI_AP_STATE_ENABLED))) {
wifiManager.setWifiApEnabled(null, false);
}
wifiManager.setWifiEnabled(desiredState);
return;
}
});
}
public boolean updateUsbState() {
String[] mUsbRegexs = connManager.getTetherableUsbRegexs();
String[] tethered = connManager.getTetheredIfaces();
usbTethered = false;
for (String s : tethered) {
for (String regex : mUsbRegexs) {
if (s.matches(regex)) {
return true;
} else {
return false;
}
}
}
return false;
}
final Runnable delayedRefresh = new Runnable () {
public void run() {
mModel.refreshWifiTetherTile();
mModel.refreshUSBTetherTile();
}
};
private void restoreFChargeState() {
new AsyncTask<Void, Void, Boolean>() {
@Override
protected Boolean doInBackground(Void... params) {
if(Prefs.getLastFastChargeState(mContext) && !mModel.isFastChargeOn()) {
setFastCharge(true);
}
return null;
}
}.execute();
}
void updateTileTextSize(int colnum) {
// adjust Tile Text Size based on column count
switch (colnum) {
case 5:
mTileTextSize = 8;
break;
case 4:
mTileTextSize = 10;
break;
case 3:
default:
mTileTextSize = 12;
break;
}
}
private void updateSettings() {
ContentResolver resolver = mContext.getContentResolver();
userToggles = Settings.System.getString(resolver, Settings.System.QUICK_TOGGLES);
int columnCount = Settings.System.getInt(resolver, Settings.System.QUICK_TOGGLES_PER_ROW,
mContext.getResources().getInteger(R.integer.quick_settings_num_columns));
((QuickSettingsContainerView) mContainerView).setColumnCount(columnCount);
updateTileTextSize(columnCount);
setupQuickSettings();
updateWifiDisplayStatus();
updateResources();
reloadFavContactInfo();
mModel.refreshTorchTile();
}
class SettingsObserver extends ContentObserver {
SettingsObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.System
.getUriFor(Settings.System.QUICK_TOGGLES),
false, this);
resolver.registerContentObserver(Settings.System
.getUriFor(Settings.System.QUICK_TOGGLES_PER_ROW),
false, this);
resolver.registerContentObserver(Settings.System
.getUriFor(Settings.System.QUICK_TOGGLE_FAV_CONTACT),
false, this);
updateSettings();
}
@Override
public void onChange(boolean selfChange) {
updateSettings();
}
}
class SoundObserver extends ContentObserver {
SoundObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.Global
.getUriFor(Settings.Global.MODE_RINGER),
false, this);
mModel.refreshVibrateTile();
mModel.refreshSilentTile();
mModel.refreshSoundStateTile();
}
@Override
public void onChange(boolean selfChange) {
mModel.refreshVibrateTile();
mModel.refreshSilentTile();
mModel.refreshSoundStateTile();
}
}
class NetworkModeObserver extends ContentObserver {
NetworkModeObserver(Handler handler) {
super(handler);
}
void observe() {
ContentResolver resolver = mContext.getContentResolver();
resolver.registerContentObserver(Settings.Global
.getUriFor(Settings.Global.PREFERRED_NETWORK_MODE),
false, this);
mModel.refresh2gTile();
mModel.refreshLTETile();
}
@Override
public void onChange(boolean selfChange) {
mModel.refresh2gTile();
mModel.refreshLTETile();
}
}
}
| false | true | private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) {
final Resources r = mContext.getResources();
QuickSettingsTileView quick = null;
switch (tile) {
case USER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_user, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
final UserManager um =
(UserManager) mContext.getSystemService(Context.USER_SERVICE);
if (um.getUsers(true).size() > 1) {
try {
WindowManagerGlobal.getWindowManagerService().lockNow(null);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't show user switcher", e);
}
} else {
Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
mContext, v, ContactsContract.Profile.CONTENT_URI,
ContactsContract.QuickContact.MODE_LARGE, null);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
}
}
});
mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
UserState us = (UserState) state;
ImageView iv = (ImageView) view.findViewById(R.id.user_imageview);
TextView tv = (TextView) view.findViewById(R.id.user_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
iv.setImageDrawable(us.avatar);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_user, state.label));
}
});
break;
case CLOCK_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_time, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider"));
intent.addCategory("android.intent.category.LAUNCHER");
startSettingsActivity(intent);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(Intent.ACTION_QUICK_CLOCK);
return true;
}
});
mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State alarmState) {
TextView tv = (TextView) view.findViewById(R.id.clock_textview);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SIGNAL_TILE:
if (mModel.deviceSupportsTelephony()) {
// Mobile Network state
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rssi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true);
String strData = connManager.getMobileDataEnabled() ?
r.getString(R.string.quick_settings_data_off_label)
: r.getString(R.string.quick_settings_data_on_label);
Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.android.settings",
"com.android.settings.Settings$DataUsageSummaryActivity"));
startSettingsActivity(intent);
return true;
}
});
mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
RSSIState rssiState = (RSSIState) state;
ImageView iv = (ImageView) view.findViewById(R.id.rssi_image);
ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image);
TextView tv = (TextView) view.findViewById(R.id.rssi_textview);
iv.setImageResource(rssiState.signalIconId);
if (rssiState.dataTypeIconId > 0) {
iov.setImageResource(rssiState.dataTypeIconId);
} else {
iov.setImageDrawable(null);
}
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getResources().getString(
R.string.accessibility_quick_settings_mobile,
rssiState.signalContentDescription, rssiState.dataContentDescription,
state.label));
}
});
}
break;
case BRIGHTNESS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_brightness, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
showBrightnessDialog();
}
});
mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.brightness_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
dismissBrightnessDialog(mBrightnessDialogShortTimeout);
}
});
break;
case SETTINGS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_settings, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SETTINGS);
}
});
mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.settings_tileview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case WIFI_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWifiState = wifiManager.getWifiState();
if (mWifiState == WifiManager.WIFI_STATE_DISABLED
|| mWifiState == WifiManager.WIFI_STATE_DISABLING) {
changeWifiState(true);
} else {
changeWifiState(false);
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS);
return true;
}
});
mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
WifiState wifiState = (WifiState) state;
TextView tv = (TextView) view.findViewById(R.id.wifi_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0);
tv.setText(wifiState.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_wifi,
wifiState.signalContentDescription,
(wifiState.connected) ? wifiState.label : ""));
}
});
break;
case TWOG_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_twog, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) {
tm.toggle2G(false);
} else {
tm.toggle2G(true);
}
mModel.refresh2gTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
return true;
}
});
mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.twog_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case LTE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_lte, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO
|| mDataState == PhoneConstants.NT_MODE_GLOBAL) {
tm.toggleLTE(false);
} else {
tm.toggleLTE(true);
}
mModel.refreshLTETile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.lte_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case VIBRATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_vibrate, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_VIB);
mModel.refreshVibrateTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.vibrate_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SILENT_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_silent, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT);
mModel.refreshSilentTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.silent_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SOUND_STATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_sound_state, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT_VIB);
mModel.refreshSoundStateTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addSoundStateTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.sound_state_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case TORCH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_torch, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// maybe something here?
return true;
}
});
mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.torch_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case FCHARGE_TILE:
if((mFastChargePath == null || mFastChargePath.isEmpty()) ||
!new File(mFastChargePath).exists()) {
// config not set or config set and kernel doesn't support it?
break;
}
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_fcharge, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setFastCharge(!Prefs.getLastFastChargeState(mContext));
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// What do we put here?
return true;
}
});
mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.fcharge_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
restoreFChargeState();
break;
case WIFI_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWifiApState = wifiManager.getWifiApState();
if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED
|| mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) {
changeWifiApState(true);
} else {
changeWifiApState(false);
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case USB_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = updateUsbState() ? false : true;
if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
mHandler.postDelayed(delayedRefresh, 1000);
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SYNC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_sync, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = ContentResolver.getMasterSyncAutomatically();
ContentResolver.setMasterSyncAutomatically(enabled ? false : true);
mModel.refreshSyncTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS);
return true;
}
});
mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.sync_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case NFC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_nfc, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = false;
if (mNfcAdapter == null) {
mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext);
}
try {
enabled = mNfcAdapter.isEnabled();
if (enabled) {
mNfcAdapter.disable();
} else {
mNfcAdapter.enable();
}
} catch (NullPointerException ex) {
// we'll ignore this click
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.nfc_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case ROTATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean locked = RotationPolicy.isRotationLocked(mContext);
RotationPolicy.setRotationLock(mContext, !locked);
}
});
mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BATTERY_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_battery, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY);
}
});
mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
QuickSettingsModel.BatteryState batteryState =
(QuickSettingsModel.BatteryState) state;
TextView tv = (TextView) view.findViewById(R.id.battery_textview);
ImageView iv = (ImageView) view.findViewById(R.id.battery_image);
Drawable d = batteryState.pluggedIn
? mChargingBatteryLevels
: mBatteryLevels;
String t;
if (batteryState.batteryLevel == 100) {
t = mContext.getString(R.string.quick_settings_battery_charged_label);
} else {
t = batteryState.pluggedIn
? mContext.getString(R.string.quick_settings_battery_charging_label,
batteryState.batteryLevel)
: mContext.getString(R.string.status_bar_settings_battery_meter_format,
batteryState.batteryLevel);
}
iv.setImageDrawable(d);
iv.setImageLevel(batteryState.batteryLevel);
tv.setText(t);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_battery, t));
}
});
break;
case AIRPLANE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_airplane, inflater);
mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
String airplaneState = mContext.getString(
(state.enabled) ? R.string.accessibility_desc_on
: R.string.accessibility_desc_off);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState));
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BLUETOOTH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter.isEnabled()) {
adapter.disable();
} else {
adapter.enable();
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
return true;
}
});
mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
BluetoothState bluetoothState = (BluetoothState) state;
TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
Resources r = mContext.getResources();
String label = state.label;
/*
* //TODO: Show connected bluetooth device label
* Set<BluetoothDevice> btDevices =
* mBluetoothController.getBondedBluetoothDevices(); if
* (btDevices.size() == 1) { // Show the name of the
* bluetooth device you are connected to label =
* btDevices.iterator().next().getName(); } else if
* (btDevices.size() > 1) { // Show a generic label
* about the number of bluetooth devices label =
* r.getString(R.string
* .quick_settings_bluetooth_multiple_devices_label,
* btDevices.size()); }
*/
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_bluetooth,
bluetoothState.stateContentDescription));
tv.setText(label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case GPS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_location, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(),
LocationManager.GPS_PROVIDER, gpsEnabled ? false : true);
TextView tv = (TextView) v.findViewById(R.id.location_textview);
tv.setText(gpsEnabled ? R.string.quick_settings_gps_off_label
: R.string.quick_settings_gps_on_label);
tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ?
R.drawable.ic_qs_gps_off : R.drawable.ic_qs_gps_on, 0, 0);
tv.setTextSize(1, mTileTextSize);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
return true;
}
});
mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
TextView tv = (TextView) view.findViewById(R.id.location_textview);
tv.setText(gpsEnabled
? R.string.quick_settings_gps_on_label
: R.string.quick_settings_gps_off_label);
if (state.iconId == 0) {
tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ?
R.drawable.ic_qs_gps_on : R.drawable.ic_qs_gps_off, 0, 0);
}
else {
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
}
tv.setTextSize(1, mTileTextSize);
}
});
break;
case IME_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_ime, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mBar.collapseAllPanels(true);
Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
pendingIntent.send();
} catch (Exception e) {
}
}
});
mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.ime_textview);
if (state.label != null) {
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
}
});
break;
case FAV_CONTACT_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_user, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String lookupKey = Settings.System.getString(mContext.getContentResolver(),
Settings.System.QUICK_TOGGLE_FAV_CONTACT);
if (lookupKey != null && lookupKey.length() > 0) {
mBar.collapseAllPanels(true);
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
Uri res = ContactsContract.Contacts.lookupContact(mContext.getContentResolver(), lookupUri);
Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
mContext, v, res,
ContactsContract.QuickContact.MODE_LARGE, null);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
}
}
});
mModel.addFavContactTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
UserState us = (UserState) state;
ImageView iv = (ImageView) view.findViewById(R.id.user_imageview);
TextView tv = (TextView) view.findViewById(R.id.user_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
iv.setImageDrawable(us.avatar);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_user, state.label));
}
});
break;
}
return quick;
}
| private QuickSettingsTileView getTile(int tile, ViewGroup parent, LayoutInflater inflater) {
final Resources r = mContext.getResources();
QuickSettingsTileView quick = null;
switch (tile) {
case USER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_user, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
final UserManager um =
(UserManager) mContext.getSystemService(Context.USER_SERVICE);
if (um.getUsers(true).size() > 1) {
try {
WindowManagerGlobal.getWindowManagerService().lockNow(null);
} catch (RemoteException e) {
Log.e(TAG, "Couldn't show user switcher", e);
}
} else {
Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
mContext, v, ContactsContract.Profile.CONTENT_URI,
ContactsContract.QuickContact.MODE_LARGE, null);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
}
}
});
mModel.addUserTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
UserState us = (UserState) state;
ImageView iv = (ImageView) view.findViewById(R.id.user_imageview);
TextView tv = (TextView) view.findViewById(R.id.user_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
iv.setImageDrawable(us.avatar);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_user, state.label));
}
});
break;
case CLOCK_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_time, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(ComponentName.unflattenFromString("com.android.deskclock.AlarmProvider"));
intent.addCategory("android.intent.category.LAUNCHER");
startSettingsActivity(intent);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(Intent.ACTION_QUICK_CLOCK);
return true;
}
});
mModel.addTimeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State alarmState) {
TextView tv = (TextView) view.findViewById(R.id.clock_textview);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SIGNAL_TILE:
if (mModel.deviceSupportsTelephony()) {
// Mobile Network state
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rssi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
connManager.setMobileDataEnabled(connManager.getMobileDataEnabled() ? false : true);
String strData = connManager.getMobileDataEnabled() ?
r.getString(R.string.quick_settings_data_off_label)
: r.getString(R.string.quick_settings_data_on_label);
Toast.makeText(mContext, strData, Toast.LENGTH_SHORT).show();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(
"com.android.settings",
"com.android.settings.Settings$DataUsageSummaryActivity"));
startSettingsActivity(intent);
return true;
}
});
mModel.addRSSITile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
RSSIState rssiState = (RSSIState) state;
ImageView iv = (ImageView) view.findViewById(R.id.rssi_image);
ImageView iov = (ImageView) view.findViewById(R.id.rssi_overlay_image);
TextView tv = (TextView) view.findViewById(R.id.rssi_textview);
iv.setImageResource(rssiState.signalIconId);
if (rssiState.dataTypeIconId > 0) {
iov.setImageResource(rssiState.dataTypeIconId);
} else {
iov.setImageDrawable(null);
}
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getResources().getString(
R.string.accessibility_quick_settings_mobile,
rssiState.signalContentDescription, rssiState.dataContentDescription,
state.label));
}
});
}
break;
case BRIGHTNESS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_brightness, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mBar.collapseAllPanels(true);
showBrightnessDialog();
}
});
mModel.addBrightnessTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.brightness_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
dismissBrightnessDialog(mBrightnessDialogShortTimeout);
}
});
break;
case SETTINGS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_settings, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SETTINGS);
}
});
mModel.addSettingsTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.settings_tileview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case WIFI_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWifiState = wifiManager.getWifiState();
if (mWifiState == WifiManager.WIFI_STATE_DISABLED
|| mWifiState == WifiManager.WIFI_STATE_DISABLING) {
changeWifiState(true);
} else {
changeWifiState(false);
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIFI_SETTINGS);
return true;
}
});
mModel.addWifiTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
WifiState wifiState = (WifiState) state;
TextView tv = (TextView) view.findViewById(R.id.wifi_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, wifiState.iconId, 0, 0);
tv.setText(wifiState.label);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_wifi,
wifiState.signalContentDescription,
(wifiState.connected) ? wifiState.label : ""));
}
});
break;
case TWOG_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_twog, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_GSM_ONLY) {
tm.toggle2G(false);
} else {
tm.toggle2G(true);
}
mModel.refresh2gTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_DATA_ROAMING_SETTINGS);
return true;
}
});
mModel.add2gTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.twog_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case LTE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_lte, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mDataState = Settings.Global.getInt(mContext.getContentResolver(),
Settings.Global.PREFERRED_NETWORK_MODE);
} catch (SettingNotFoundException e) {
e.printStackTrace();
}
if (mDataState == PhoneConstants.NT_MODE_LTE_CDMA_EVDO
|| mDataState == PhoneConstants.NT_MODE_GLOBAL) {
tm.toggleLTE(false);
} else {
tm.toggleLTE(true);
}
mModel.refreshLTETile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addLTETile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.lte_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case VIBRATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_vibrate, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_VIB);
mModel.refreshVibrateTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addVibrateTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.vibrate_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SILENT_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_silent, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT);
mModel.refreshSilentTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addSilentTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.silent_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SOUND_STATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_sound_state, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_SILENT_VIB);
mModel.refreshSoundStateTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SOUND_SETTINGS);
return true;
}
});
mModel.addSoundStateTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.sound_state_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case TORCH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_torch, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAokpTarget.launchAction(mAokpTarget.ACTION_TORCH);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// maybe something here?
return true;
}
});
mModel.addTorchTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.torch_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case FCHARGE_TILE:
if((mFastChargePath == null || mFastChargePath.isEmpty()) ||
!new File(mFastChargePath).exists()) {
// config not set or config set and kernel doesn't support it?
break;
}
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_fcharge, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setFastCharge(!Prefs.getLastFastChargeState(mContext));
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// What do we put here?
return true;
}
});
mModel.addFChargeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.fcharge_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
restoreFChargeState();
break;
case WIFI_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_wifi_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mWifiApState = wifiManager.getWifiApState();
if (mWifiApState == WifiManager.WIFI_AP_STATE_DISABLED
|| mWifiApState == WifiManager.WIFI_AP_STATE_DISABLING) {
changeWifiApState(true);
} else {
changeWifiApState(false);
}
mHandler.postDelayed(delayedRefresh, 1000);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity"));
startSettingsActivity(intent);
return true;
}
});
mModel.addWifiTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.wifi_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case USB_TETHER_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_usb_tether, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = updateUsbState() ? false : true;
if (connManager.setUsbTethering(enabled) == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
mHandler.postDelayed(delayedRefresh, 1000);
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.android.settings", "com.android.settings.Settings$TetherSettingsActivity"));
startSettingsActivity(intent);
return true;
}
});
mModel.addUSBTetherTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.usb_tether_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case SYNC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_sync, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = ContentResolver.getMasterSyncAutomatically();
ContentResolver.setMasterSyncAutomatically(enabled ? false : true);
mModel.refreshSyncTile();
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_SYNC_SETTINGS);
return true;
}
});
mModel.addSyncTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.sync_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case NFC_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_nfc, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean enabled = false;
if (mNfcAdapter == null) {
mNfcAdapter = NfcAdapter.getDefaultAdapter(mContext);
}
try {
enabled = mNfcAdapter.isEnabled();
if (enabled) {
mNfcAdapter.disable();
} else {
mNfcAdapter.enable();
}
} catch (NullPointerException ex) {
// we'll ignore this click
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
return true;
}
});
mModel.addNFCTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.nfc_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case ROTATE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_rotation_lock, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean locked = RotationPolicy.isRotationLocked(mContext);
RotationPolicy.setRotationLock(mContext, !locked);
}
});
mModel.addRotationLockTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.rotation_lock_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BATTERY_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_battery, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSettingsActivity(Intent.ACTION_POWER_USAGE_SUMMARY);
}
});
mModel.addBatteryTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
QuickSettingsModel.BatteryState batteryState =
(QuickSettingsModel.BatteryState) state;
TextView tv = (TextView) view.findViewById(R.id.battery_textview);
ImageView iv = (ImageView) view.findViewById(R.id.battery_image);
Drawable d = batteryState.pluggedIn
? mChargingBatteryLevels
: mBatteryLevels;
String t;
if (batteryState.batteryLevel == 100) {
t = mContext.getString(R.string.quick_settings_battery_charged_label);
} else {
t = batteryState.pluggedIn
? mContext.getString(R.string.quick_settings_battery_charging_label,
batteryState.batteryLevel)
: mContext.getString(R.string.status_bar_settings_battery_meter_format,
batteryState.batteryLevel);
}
iv.setImageDrawable(d);
iv.setImageLevel(batteryState.batteryLevel);
tv.setText(t);
tv.setTextSize(1, mTileTextSize);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_battery, t));
}
});
break;
case AIRPLANE_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_airplane, inflater);
mModel.addAirplaneModeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.airplane_mode_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
String airplaneState = mContext.getString(
(state.enabled) ? R.string.accessibility_desc_on
: R.string.accessibility_desc_off);
view.setContentDescription(
mContext.getString(R.string.accessibility_quick_settings_airplane, airplaneState));
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case BLUETOOTH_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_bluetooth, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter.isEnabled()) {
adapter.disable();
} else {
adapter.enable();
}
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_BLUETOOTH_SETTINGS);
return true;
}
});
mModel.addBluetoothTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
BluetoothState bluetoothState = (BluetoothState) state;
TextView tv = (TextView) view.findViewById(R.id.bluetooth_textview);
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
Resources r = mContext.getResources();
String label = state.label;
/*
* //TODO: Show connected bluetooth device label
* Set<BluetoothDevice> btDevices =
* mBluetoothController.getBondedBluetoothDevices(); if
* (btDevices.size() == 1) { // Show the name of the
* bluetooth device you are connected to label =
* btDevices.iterator().next().getName(); } else if
* (btDevices.size() > 1) { // Show a generic label
* about the number of bluetooth devices label =
* r.getString(R.string
* .quick_settings_bluetooth_multiple_devices_label,
* btDevices.size()); }
*/
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_bluetooth,
bluetoothState.stateContentDescription));
tv.setText(label);
tv.setTextSize(1, mTileTextSize);
}
});
break;
case GPS_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_location, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
Settings.Secure.setLocationProviderEnabled(mContext.getContentResolver(),
LocationManager.GPS_PROVIDER, gpsEnabled ? false : true);
TextView tv = (TextView) v.findViewById(R.id.location_textview);
tv.setText(gpsEnabled ? R.string.quick_settings_gps_off_label
: R.string.quick_settings_gps_on_label);
tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ?
R.drawable.ic_qs_gps_off : R.drawable.ic_qs_gps_on, 0, 0);
tv.setTextSize(1, mTileTextSize);
}
});
quick.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
startSettingsActivity(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
return true;
}
});
mModel.addLocationTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
boolean gpsEnabled = Settings.Secure.isLocationProviderEnabled(
mContext.getContentResolver(), LocationManager.GPS_PROVIDER);
TextView tv = (TextView) view.findViewById(R.id.location_textview);
tv.setText(gpsEnabled
? R.string.quick_settings_gps_on_label
: R.string.quick_settings_gps_off_label);
if (state.iconId == 0) {
tv.setCompoundDrawablesWithIntrinsicBounds(0, gpsEnabled ?
R.drawable.ic_qs_gps_on : R.drawable.ic_qs_gps_off, 0, 0);
}
else {
tv.setCompoundDrawablesWithIntrinsicBounds(0, state.iconId, 0, 0);
}
tv.setTextSize(1, mTileTextSize);
}
});
break;
case IME_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_ime, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
mBar.collapseAllPanels(true);
Intent intent = new Intent(Settings.ACTION_SHOW_INPUT_METHOD_PICKER);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
pendingIntent.send();
} catch (Exception e) {
}
}
});
mModel.addImeTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
TextView tv = (TextView) view.findViewById(R.id.ime_textview);
if (state.label != null) {
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
}
}
});
break;
case FAV_CONTACT_TILE:
quick = (QuickSettingsTileView)
inflater.inflate(R.layout.quick_settings_tile, parent, false);
quick.setContent(R.layout.quick_settings_tile_user, inflater);
quick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String lookupKey = Settings.System.getString(mContext.getContentResolver(),
Settings.System.QUICK_TOGGLE_FAV_CONTACT);
if (lookupKey != null && lookupKey.length() > 0) {
mBar.collapseAllPanels(true);
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
Uri res = ContactsContract.Contacts.lookupContact(mContext.getContentResolver(), lookupUri);
Intent intent = ContactsContract.QuickContact.composeQuickContactsIntent(
mContext, v, res,
ContactsContract.QuickContact.MODE_LARGE, null);
mContext.startActivityAsUser(intent, new UserHandle(UserHandle.USER_CURRENT));
}
}
});
mModel.addFavContactTile(quick, new QuickSettingsModel.RefreshCallback() {
@Override
public void refreshView(QuickSettingsTileView view, State state) {
UserState us = (UserState) state;
ImageView iv = (ImageView) view.findViewById(R.id.user_imageview);
TextView tv = (TextView) view.findViewById(R.id.user_textview);
tv.setText(state.label);
tv.setTextSize(1, mTileTextSize);
iv.setImageDrawable(us.avatar);
view.setContentDescription(mContext.getString(
R.string.accessibility_quick_settings_user, state.label));
}
});
break;
}
return quick;
}
|
diff --git a/src/main/java/cc/redberry/core/number/parser/OperatorToken.java b/src/main/java/cc/redberry/core/number/parser/OperatorToken.java
index a0a10f0..cdcfd76 100644
--- a/src/main/java/cc/redberry/core/number/parser/OperatorToken.java
+++ b/src/main/java/cc/redberry/core/number/parser/OperatorToken.java
@@ -1,106 +1,98 @@
/*
* Redberry: symbolic tensor computations.
*
* Copyright (c) 2010-2012:
* Stanislav Poslavsky <[email protected]>
* Bolotin Dmitriy <[email protected]>
*
* This file is part of Redberry.
*
* Redberry 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.
*
* Redberry 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 Redberry. If not, see <http://www.gnu.org/licenses/>.
*/
package cc.redberry.core.number.parser;
/**
*
* @author Stanislav Poslavsky
*/
public abstract class OperatorToken<T extends cc.redberry.core.number.Number<T>>
implements TokenParser<T> {
private final char operationSymbol, operationInverseSymbol;
public OperatorToken(char operationSymbol, char operationInverseSymbol) {
this.operationSymbol = operationSymbol;
this.operationInverseSymbol = operationInverseSymbol;
}
private boolean canParse(String expression) {
//TODO improve
if (expression.contains("**"))
return false;
char[] expressionChars = expression.toCharArray();
int level = 0;
for (char c : expressionChars) {
if (c == '(' || c == '[')
level++;
if (c == ')' || c == ']')
level--;
if (level < 0)
throw new BracketsError(expression);
if (c == operationSymbol && level == 0)
return true;
if (c == operationInverseSymbol && level == 0)
return true;
}
return false;
}
@Override
public T parse(String expression, NumberParser<T> parser) {
if (!canParse(expression))
return null;
char[] expressionChars = expression.toCharArray();
StringBuffer buffer = new StringBuffer();
- T temp = null;
+ T temp = neutral();
int level = 0;
boolean mode = false;//true - inverse
for (char c : expressionChars) {
if (c == '(')
level++;
if (c == ')')
level--;
if (level < 0)
throw new BracketsError();
if (c == operationSymbol && level == 0) {
- String toParse = buffer.toString();
- if (!toParse.isEmpty())
- if (temp == null)
- temp = parser.parse(toParse);
- else
- temp = operation(temp, parser.parse(toParse), mode);
+ if (buffer.length() != 0)
+ temp = operation(temp, parser.parse(buffer.toString()), mode);
buffer = new StringBuffer();
mode = false;
} else if (c == operationInverseSymbol && level == 0) {
- String toParse = buffer.toString();
- if (!toParse.isEmpty()) {
- if (temp == null)
- temp = neutral();
- temp = operation(temp, parser.parse(toParse), mode);
- }
+ if (buffer.length() != 0)
+ temp = operation(temp, parser.parse(buffer.toString()), mode);
buffer = new StringBuffer();
mode = true;
} else
buffer.append(c);
}
if (temp == null)
temp = neutral();
temp = operation(temp, parser.parse(buffer.toString()), mode);
return temp;
}
protected abstract T neutral();
protected abstract T operation(T c1, T c2, boolean mode);
}
| false | true | public T parse(String expression, NumberParser<T> parser) {
if (!canParse(expression))
return null;
char[] expressionChars = expression.toCharArray();
StringBuffer buffer = new StringBuffer();
T temp = null;
int level = 0;
boolean mode = false;//true - inverse
for (char c : expressionChars) {
if (c == '(')
level++;
if (c == ')')
level--;
if (level < 0)
throw new BracketsError();
if (c == operationSymbol && level == 0) {
String toParse = buffer.toString();
if (!toParse.isEmpty())
if (temp == null)
temp = parser.parse(toParse);
else
temp = operation(temp, parser.parse(toParse), mode);
buffer = new StringBuffer();
mode = false;
} else if (c == operationInverseSymbol && level == 0) {
String toParse = buffer.toString();
if (!toParse.isEmpty()) {
if (temp == null)
temp = neutral();
temp = operation(temp, parser.parse(toParse), mode);
}
buffer = new StringBuffer();
mode = true;
} else
buffer.append(c);
}
if (temp == null)
temp = neutral();
temp = operation(temp, parser.parse(buffer.toString()), mode);
return temp;
}
| public T parse(String expression, NumberParser<T> parser) {
if (!canParse(expression))
return null;
char[] expressionChars = expression.toCharArray();
StringBuffer buffer = new StringBuffer();
T temp = neutral();
int level = 0;
boolean mode = false;//true - inverse
for (char c : expressionChars) {
if (c == '(')
level++;
if (c == ')')
level--;
if (level < 0)
throw new BracketsError();
if (c == operationSymbol && level == 0) {
if (buffer.length() != 0)
temp = operation(temp, parser.parse(buffer.toString()), mode);
buffer = new StringBuffer();
mode = false;
} else if (c == operationInverseSymbol && level == 0) {
if (buffer.length() != 0)
temp = operation(temp, parser.parse(buffer.toString()), mode);
buffer = new StringBuffer();
mode = true;
} else
buffer.append(c);
}
if (temp == null)
temp = neutral();
temp = operation(temp, parser.parse(buffer.toString()), mode);
return temp;
}
|
diff --git a/de.walware.statet.nico.ui/src/de/walware/statet/nico/ui/console/NIConsolePage.java b/de.walware.statet.nico.ui/src/de/walware/statet/nico/ui/console/NIConsolePage.java
index 3d360edd..b205d870 100644
--- a/de.walware.statet.nico.ui/src/de/walware/statet/nico/ui/console/NIConsolePage.java
+++ b/de.walware.statet.nico.ui/src/de/walware/statet/nico/ui/console/NIConsolePage.java
@@ -1,878 +1,879 @@
/*******************************************************************************
* Copyright (c) 2005-2007 WalWare/StatET-Project (www.walware.de/goto/statet).
* 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:
* Stephan Wahlbrink - initial API and implementation
*******************************************************************************/
package de.walware.statet.nico.ui.console;
import java.util.ResourceBundle;
import java.util.Set;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.ListenerList;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.debug.internal.ui.views.console.ConsoleRemoveAllTerminatedAction;
import org.eclipse.debug.internal.ui.views.console.ConsoleRemoveLaunchAction;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.jface.text.IFindReplaceTarget;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.TreeSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.dnd.Clipboard;
import org.eclipse.swt.dnd.TextTransfer;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.graphics.Font;
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.Sash;
import org.eclipse.swt.widgets.ScrollBar;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.console.actions.ClearOutputAction;
import org.eclipse.ui.contexts.IContextService;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.internal.console.IOConsoleViewer;
import org.eclipse.ui.internal.contexts.NestableContextService;
import org.eclipse.ui.internal.handlers.NestableHandlerService;
import org.eclipse.ui.internal.services.ServiceLocator;
import org.eclipse.ui.menus.CommandContributionItem;
import org.eclipse.ui.menus.CommandContributionItemParameter;
import org.eclipse.ui.part.IPageBookViewPage;
import org.eclipse.ui.part.IPageSite;
import org.eclipse.ui.part.IShowInSource;
import org.eclipse.ui.part.IShowInTargetList;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.texteditor.FindReplaceAction;
import org.eclipse.ui.texteditor.IWorkbenchActionDefinitionIds;
import de.walware.eclipsecommons.preferences.SettingsChangeNotifier.ChangeListener;
import de.walware.eclipsecommons.ui.HandlerContributionItem;
import de.walware.eclipsecommons.ui.SharedMessages;
import de.walware.eclipsecommons.ui.util.DNDUtil;
import de.walware.eclipsecommons.ui.util.DialogUtil;
import de.walware.eclipsecommons.ui.util.LayoutUtil;
import de.walware.eclipsecommons.ui.util.UIAccess;
import de.walware.statet.base.core.StatetCore;
import de.walware.statet.base.ui.sourceeditors.IEditorAdapter;
import de.walware.statet.base.ui.sourceeditors.SourceViewerConfigurator;
import de.walware.statet.base.ui.sourceeditors.TextViewerAction;
import de.walware.statet.nico.core.runtime.Prompt;
import de.walware.statet.nico.core.runtime.ToolController;
import de.walware.statet.nico.core.runtime.ToolProcess;
import de.walware.statet.nico.core.runtime.ToolWorkspace;
import de.walware.statet.nico.core.util.IToolProvider;
import de.walware.statet.nico.core.util.IToolRetargetable;
import de.walware.statet.nico.internal.ui.Messages;
import de.walware.statet.nico.internal.ui.NicoUIPlugin;
import de.walware.statet.nico.ui.NicoUI;
import de.walware.statet.nico.ui.actions.CancelHandler;
/**
* A page for a <code>NIConsole</code>.
* <p>
* The page contains beside the usual output viewer
* a separete input field with submit button.
*/
public abstract class NIConsolePage implements IPageBookViewPage,
IAdaptable, IShowInSource, IShowInTargetList,
IPropertyChangeListener, ScrollLockAction.Receiver, IToolProvider, ChangeListener {
private static final String DIALOG_ID = "Console"; //$NON-NLS-1$
private static final String SETTING_INPUTHEIGHT = "InputHeight"; //$NON-NLS-1$
private class FindReplaceUpdater implements IDocumentListener {
private boolean wasEmpty = true;
public void documentAboutToBeChanged(final DocumentEvent event) {
}
public void documentChanged(final DocumentEvent event) {
final boolean isEmpty = (event.fDocument.getLength() == 0);
if (isEmpty != wasEmpty) {
fMultiActionHandler.updateEnabledState();
wasEmpty = isEmpty;
}
}
}
private class PostUpdater implements IDocumentListener, Runnable {
private volatile boolean fIsSheduled = false;
public void documentAboutToBeChanged(final DocumentEvent event) {
}
public void documentChanged(final DocumentEvent event) {
if (!fIsSheduled) {
fIsSheduled = true;
final Display display = UIAccess.getDisplay(getSite().getShell());
display.asyncExec(this);
}
}
public void run() {
// post change run
fIsSheduled = false;
fMultiActionHandler.updateEnabledState();
}
}
private class SizeControl implements Listener {
private final Sash fSash;
private final GridData fOutputGD;
private final GridData fInputGD;
private int fLastExplicit;
public SizeControl(final Sash sash, final GridData outputGD, final GridData inputGD) {
fSash = sash;
fOutputGD = outputGD;
fInputGD = inputGD;
fLastExplicit = -1;
}
public void handleEvent(final Event event) {
if (event.widget == fSash) {
if (event.type == SWT.Selection && event.detail != SWT.DRAG) {
final Rectangle bounds = fControl.getClientArea();
// System.out.println(bounds.height);
// Rectangle bounds2 = fInputGroup.getComposite().getBounds();
// System.out.println(bounds2.y+bounds2.height);
setNewInputHeight(bounds.height - event.y - fSash.getSize().y, true);
}
return;
}
if (event.widget == fControl) {
if (event.type == SWT.Resize) {
setNewInputHeight(fInputGD.heightHint, false);
}
}
}
private void setNewInputHeight(int height, final boolean explicit) {
if (!explicit) {
height = fLastExplicit;
}
if (height == -1) {
return;
}
final Rectangle bounds = fControl.getClientArea();
final int max = bounds.height - fOutputGD.minimumHeight - fSash.getSize().y;
if (height > max) {
height = max;
}
if (height < fInputGD.minimumHeight) {
height = -1;
}
if (explicit) {
fLastExplicit = height;
}
if (fInputGD.heightHint == height) {
return;
}
fInputGD.heightHint = height;
fControl.layout(new Control[] { fInputGroup.getComposite() });
}
private void fontChanged() {
fOutputGD.minimumHeight = LayoutUtil.hintHeight(fOutputViewer.getTextWidget(), 4);
final ScrollBar bar = fOutputViewer.getTextWidget().getHorizontalBar();
if (bar.isVisible()) {
fOutputGD.minimumHeight += bar.getSize().y;
}
fInputGD.minimumHeight = fInputGroup.getComposite().computeSize(800, -1).y;
if (fInputGD.heightHint != -1
&& fInputGD.minimumHeight > fInputGD.heightHint) {
fInputGD.heightHint = -1;
}
}
}
private final NIConsole fConsole;
private final IConsoleView fConsoleView;
private IPageSite fSite;
private Composite fControl;
private Clipboard fClipboard;
private IOConsoleViewer fOutputViewer;
private InputGroup fInputGroup;
private SizeControl fResizer;
private MenuManager fOutputMenuManager;
private MenuManager fInputMenuManager;
private volatile boolean fIsCreated = false;
// Actions
private MultiActionHandler fMultiActionHandler;
private final ListenerList fToolActions = new ListenerList();
private ServiceLocator fInputServices;
private FindReplaceUpdater fFindReplaceUpdater;
private FindReplaceAction fFindReplaceAction;
// Output viewer actions
private TextViewerAction fOutputCopyAction;
private SubmitPasteAction fOutputPasteAction;
private TextViewerAction fOutputSelectAllAction;
private ClearOutputAction fOutputClearAllAction;
private Action fOutputScrollLockAction;
// Input viewer actions
private TextViewerAction fInputDeleteAction;
private TextViewerAction fInputCutAction;
private TextViewerAction fInputCopyAction;
private TextViewerAction fInputPasteAction;
private TextViewerAction fInputSelectAllAction;
private TextViewerAction fInputUndoAction;
private TextViewerAction fInputRedoAction;
// Process control actions
private IDebugEventSetListener fDebugListener;
private ConsoleRemoveLaunchAction fRemoveAction;
private ConsoleRemoveAllTerminatedAction fRemoveAllAction;
private TerminateToolAction fTerminateAction;
private CancelHandler fCancelCurrentHandler;
private CancelHandler fCancelAllHandler;
private CancelHandler fCancelPauseHandler;
/**
* Constructs a console page for the given console in the given view.
*
* @param console the console
* @param view the console view the page is contained in
*/
public NIConsolePage(final NIConsole console, final IConsoleView view) {
fConsole = console;
fConsoleView = view;
}
public void init(final IPageSite site) throws PartInitException {
fSite = site;
fInputGroup = createInputGroup();
fDebugListener = new IDebugEventSetListener() {
public void handleDebugEvents(final DebugEvent[] events) {
final ToolProcess process = getConsole().getProcess();
final ToolWorkspace data = process.getWorkspaceData();
for (final DebugEvent event : events) {
final Object source = event.getSource();
if (source == process) {
switch (event.getKind()) {
case DebugEvent.TERMINATE:
onToolTerminated();
break;
}
}
else if (source == data) {
if (event.getKind() == DebugEvent.CHANGE
&& event.getDetail() == ToolWorkspace.DETAIL_PROMPT && fIsCreated) {
final Prompt prompt = (Prompt) event.getData();
fInputGroup.updatePrompt(prompt);
}
}
}
}
};
DebugPlugin.getDefault().addDebugEventListener(fDebugListener);
}
protected InputGroup createInputGroup() {
return new InputGroup(this);
}
protected InputGroup getInputGroup() {
return fInputGroup;
}
protected IOConsoleViewer getOutputViewer() {
return fOutputViewer;
}
public void createControl(final Composite parent) {
StatetCore.getSettingsChangeNotifier().addChangeListener(this);
fConsole.addPropertyChangeListener(this);
fControl = new Composite(parent, SWT.NONE) {
@Override
public boolean setFocus() {
return false; // our page handles focus
}
};
final GridLayout layout = new GridLayout(1, false);
layout.marginHeight = 0;
layout.verticalSpacing = 0;
layout.marginWidth = 0;
fControl.setLayout(layout);
fOutputViewer = new IOConsoleViewer(fControl, fConsole);
fOutputViewer.setReadOnly();
final GridData outputGD = new GridData(SWT.FILL, SWT.FILL, true, true);
fOutputViewer.getControl().setLayoutData(outputGD);
fOutputViewer.getTextWidget().addKeyListener(new KeyListener() {
public void keyPressed(final KeyEvent e) {
- }
- public void keyReleased(final KeyEvent e) {
if (e.doit
&& (e.character >= 32)
&& (e.stateMask == SWT.NONE || e.stateMask == SWT.SHIFT)
- && (e.keyCode & SWT.KEYCODE_BIT) == 0) {
+ && ( ((e.keyCode & SWT.KEYCODE_BIT) == 0)
+ || (SWT.KEYCODE_BIT + 32 <= e.keyCode && e.keyCode <= (SWT.KEYCODE_BIT + 80)) )) {
final StyledText textWidget = fInputGroup.getSourceViewer().getTextWidget();
if (!UIAccess.isOkToUse(textWidget)) {
return;
}
if (textWidget.getCharCount() == 0) {
textWidget.replaceTextRange(0, 0, Character.toString(e.character));
textWidget.setCaretOffset(textWidget.getCharCount());
}
else {
Display.getCurrent().beep();
}
setFocus();
}
}
+ public void keyReleased(final KeyEvent e) {
+ }
});
final Sash sash = new Sash(fControl, SWT.HORIZONTAL);
// sash.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
fInputGroup.createControl(fControl, createInputEditorConfigurator());
final GridData inputGD = new GridData(SWT.FILL, SWT.FILL, true, false);
fInputGroup.getComposite().setLayoutData(inputGD);
fOutputViewer.getTextWidget().getHorizontalBar().setVisible(false);
fResizer = new SizeControl(sash, outputGD, inputGD);
sash.addListener(SWT.Selection, fResizer);
fControl.addListener(SWT.Resize, fResizer);
fClipboard = new Clipboard(fControl.getDisplay());
createActions();
hookContextMenu();
hookDND();
contributeToActionBars();
new ConsoleActivationNotifier();
fIsCreated = true;
fInputGroup.updatePrompt(null);
final IDialogSettings dialogSettings = DialogUtil.getDialogSettings(NicoUIPlugin.getDefault(), DIALOG_ID);
try {
final int height = dialogSettings.getInt(SETTING_INPUTHEIGHT);
if (height > 0) {
fResizer.fLastExplicit = height;
}
}
catch (final NumberFormatException e) {
// missing value
}
fResizer.fontChanged();
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
if (UIAccess.isOkToUse(fInputGroup.getSourceViewer())
&& fOutputViewer.getControl().isFocusControl()) {
setFocus();
}
}
});
}
/**
* Creates the adapter to configure the input source viewer.
* Will be disposed automatically.
*
* @return the adapter
*/
protected abstract SourceViewerConfigurator createInputEditorConfigurator();
private class ConsoleActivationNotifier implements Listener {
private ConsoleActivationNotifier() {
fControl.addListener(SWT.Activate, this);
fControl.addListener(SWT.Dispose, this);
if (fControl.isVisible()) {
NicoUIPlugin.getDefault().getToolRegistry().consoleActivated(fConsoleView, fConsole);
}
}
public void handleEvent(final Event event) {
switch (event.type) {
case SWT.Activate:
NicoUIPlugin.getDefault().getToolRegistry().consoleActivated(fConsoleView, fConsole);
break;
case SWT.Dispose:
fControl.removeListener(SWT.Activate, this);
fControl.removeListener(SWT.Dispose, this);
break;
}
}
}
protected void createActions() {
final Control outputControl = fOutputViewer.getControl();
final SourceViewer inputViewer = fInputGroup.getSourceViewer();
final Control inputControl = inputViewer.getControl();
fInputServices = new ServiceLocator(getSite());
final IHandlerService pageCommands = (IHandlerService) getSite().getService(IHandlerService.class);
final IHandlerService inputCommands = new NestableHandlerService(pageCommands, null);
fInputServices.registerService(IHandlerService.class, inputCommands);
final IContextService pageKeys = (IContextService) getSite().getService(IContextService.class);
final IContextService inputKeys = new NestableContextService(pageKeys, null);
fInputServices.registerService(IContextService.class, inputKeys);
inputControl.addListener(SWT.FocusIn, new Listener() {
public void handleEvent(final Event event) {
if (fInputServices != null) {
fInputServices.activate();
getSite().getActionBars().updateActionBars();
}
}
});
inputControl.addListener(SWT.FocusOut, new Listener() {
public void handleEvent(final Event event) {
if (fInputServices != null) {
fInputServices.deactivate();
getSite().getActionBars().updateActionBars();
}
}
});
fMultiActionHandler = new MultiActionHandler();
fRemoveAction = new ConsoleRemoveLaunchAction(fConsole.getProcess().getLaunch());
fRemoveAllAction = new ConsoleRemoveAllTerminatedAction();
fTerminateAction = new TerminateToolAction(fConsole.getProcess());
fCancelCurrentHandler = new CancelHandler(this, ToolController.CANCEL_CURRENT);
pageCommands.activateHandler(CancelHandler.COMMAND_CURRENT, fCancelCurrentHandler);
fCancelAllHandler = new CancelHandler(this, ToolController.CANCEL_ALL);
pageCommands.activateHandler(CancelHandler.COMMAND_ALL, fCancelAllHandler);
fCancelPauseHandler = new CancelHandler(this, ToolController.CANCEL_CURRENT | ToolController.CANCEL_PAUSE);
pageCommands.activateHandler(CancelHandler.COMMAND_CURRENTPAUSE, fCancelPauseHandler);
// Conflict with binding CTRL+Z (in console EOF)
// pageKeys.activateContext("org.eclipse.debug.ui.console"); //$NON-NLS-1$
fOutputCopyAction = TextViewerAction.createCopyAction(fOutputViewer);
fMultiActionHandler.addGlobalAction(outputControl, ActionFactory.COPY.getId(), fOutputCopyAction);
fOutputPasteAction = new SubmitPasteAction(this);
fOutputPasteAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.PASTE);
fMultiActionHandler.addGlobalAction(outputControl, ActionFactory.PASTE.getId(), fOutputPasteAction);
fOutputSelectAllAction = TextViewerAction.createSelectAllAction(fOutputViewer);
fMultiActionHandler.addGlobalAction(outputControl, ActionFactory.SELECT_ALL.getId(), fOutputSelectAllAction);
fOutputClearAllAction = new ClearOutputAction(fConsole);
fOutputScrollLockAction = new ScrollLockAction(this, false);
fInputDeleteAction = TextViewerAction.createDeleteAction(inputViewer);
fMultiActionHandler.addGlobalAction(inputControl, ActionFactory.DELETE.getId(), fInputDeleteAction);
fInputCutAction = TextViewerAction.createCutAction(inputViewer);
fMultiActionHandler.addGlobalAction(inputControl, ActionFactory.CUT.getId(), fInputCutAction);
fInputCopyAction = TextViewerAction.createCopyAction(inputViewer);
fMultiActionHandler.addGlobalAction(inputControl, ActionFactory.COPY.getId(), fInputCopyAction);
fInputPasteAction = TextViewerAction.createPasteAction(inputViewer);
fMultiActionHandler.addGlobalAction(inputControl, ActionFactory.PASTE.getId(), fInputPasteAction);
fInputSelectAllAction = TextViewerAction.createSelectAllAction(inputViewer);
fMultiActionHandler.addGlobalAction(inputControl, ActionFactory.SELECT_ALL.getId(), fInputSelectAllAction);
fInputUndoAction = TextViewerAction.createUndoAction(inputViewer);
fMultiActionHandler.addGlobalAction(inputControl, ActionFactory.UNDO.getId(), fInputUndoAction);
fInputRedoAction = TextViewerAction.createRedoAction(inputViewer);
fMultiActionHandler.addGlobalAction(inputControl, ActionFactory.REDO.getId(), fInputRedoAction);
final ResourceBundle bundle = SharedMessages.getCompatibilityBundle();
fFindReplaceAction = new FindReplaceAction(bundle, "FindReplaceAction_", fConsoleView); //$NON-NLS-1$
fFindReplaceAction.setActionDefinitionId(IWorkbenchActionDefinitionIds.FIND_REPLACE);
fMultiActionHandler.addGlobalAction(outputControl, ActionFactory.FIND.getId(), fFindReplaceAction);
fMultiActionHandler.addGlobalAction(inputControl, ActionFactory.FIND.getId(), fFindReplaceAction);
fFindReplaceUpdater = new FindReplaceUpdater();
fConsole.getDocument().addDocumentListener(fFindReplaceUpdater);
inputViewer.getDocument().addDocumentListener(new PostUpdater());
fInputGroup.configureServices(inputCommands, inputKeys);
inputViewer.addSelectionChangedListener(fMultiActionHandler);
fOutputViewer.addSelectionChangedListener(fMultiActionHandler);
}
private void hookContextMenu() {
String id = NIConsole.NICONSOLE_TYPE + "#OutputContextMenu"; //$NON-NLS-1$
fOutputMenuManager = new MenuManager("ContextMenu", id); //$NON-NLS-1$
fOutputMenuManager.setRemoveAllWhenShown(true);
fOutputMenuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(final IMenuManager manager) {
fillOutputContextMenu(manager);
}
});
Control control = fOutputViewer.getControl();
Menu menu = fOutputMenuManager.createContextMenu(control);
control.setMenu(menu);
getSite().registerContextMenu(id, fOutputMenuManager, fOutputViewer);
id = NIConsole.NICONSOLE_TYPE + "#InputContextMenu"; //$NON-NLS-1$
fInputMenuManager = new MenuManager("ContextMenu", id); //$NON-NLS-1$
fInputMenuManager.setRemoveAllWhenShown(true);
fInputMenuManager.addMenuListener(new IMenuListener() {
public void menuAboutToShow(final IMenuManager manager) {
fillInputContextMenu(manager);
}
});
control = fInputGroup.getSourceViewer().getControl();
menu = fInputMenuManager.createContextMenu(control);
control.setMenu(menu);
getSite().registerContextMenu(id, fInputMenuManager, fInputGroup.getSourceViewer());
}
protected void hookDND() {
DNDUtil.addDropSupport(fOutputViewer.getControl(),
new SubmitDropAdapter(this),
new Transfer[] { TextTransfer.getInstance() } );
}
protected void contributeToActionBars() {
final IActionBars bars = getSite().getActionBars();
fMultiActionHandler.registerActions(bars);
final IToolBarManager toolBar = bars.getToolBarManager();
toolBar.appendToGroup(IConsoleConstants.OUTPUT_GROUP, fOutputClearAllAction);
toolBar.appendToGroup(IConsoleConstants.OUTPUT_GROUP, fOutputScrollLockAction);
toolBar.appendToGroup(IConsoleConstants.LAUNCH_GROUP, new HandlerContributionItem(
new CommandContributionItemParameter(getSite(), CancelHandler.MENU_ID,
CancelHandler.COMMAND_CURRENT, null,
NicoUI.getImageDescriptor(NicoUI.IMG_LOCTOOL_CANCEL), NicoUI.getImageDescriptor(NicoUI.IMG_LOCTOOLD_CANCEL), null,
Messages.CancelAction_name, null, Messages.CancelAction_tooltip,
CommandContributionItem.STYLE_PULLDOWN, null), fCancelCurrentHandler));
toolBar.appendToGroup(IConsoleConstants.LAUNCH_GROUP, fTerminateAction);
toolBar.appendToGroup(IConsoleConstants.LAUNCH_GROUP, fRemoveAction);
toolBar.appendToGroup(IConsoleConstants.LAUNCH_GROUP, fRemoveAllAction);
}
protected void fillInputContextMenu(final IMenuManager manager) {
manager.add(fInputCutAction);
manager.add(fInputCopyAction);
manager.add(fInputPasteAction);
manager.add(new GroupMarker(IWorkbenchActionConstants.CUT_EXT));
manager.add(new Separator());
manager.add(fInputUndoAction);
manager.add(fInputRedoAction);
manager.add(new GroupMarker(IWorkbenchActionConstants.UNDO_EXT));
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
protected void fillOutputContextMenu(final IMenuManager manager) {
manager.add(fOutputCopyAction);
manager.add(fOutputSelectAllAction);
manager.add(new Separator("more")); //$NON-NLS-1$
manager.add(fFindReplaceAction);
// manager.add(new FollowHyperlinkAction(fViewer));
manager.add(new Separator("submit")); //$NON-NLS-1$
manager.add(fOutputPasteAction);
manager.add(new Separator("view")); //$NON-NLS-1$
manager.add(fOutputClearAllAction);
manager.add(fOutputScrollLockAction);
manager.add(new Separator(IWorkbenchActionConstants.MB_ADDITIONS));
}
public void dispose() {
fConsole.removePropertyChangeListener(this);
StatetCore.getSettingsChangeNotifier().removeChangeListener(this);
if (fDebugListener != null) {
final DebugPlugin debug = DebugPlugin.getDefault();
if (debug != null) {
debug.removeDebugEventListener(fDebugListener);
}
fDebugListener = null;
}
if (fIsCreated) { // control created
fIsCreated = false;
try {
fConsole.getDocument().removeDocumentListener(fFindReplaceUpdater);
fOutputViewer.removeSelectionChangedListener(fMultiActionHandler);
fInputGroup.getSourceViewer().removeSelectionChangedListener(fMultiActionHandler);
}
catch (final Exception e) {
NicoUIPlugin.logError(NicoUIPlugin.INTERNAL_ERROR, Messages.Console_error_UnexpectedException_message, e);
}
fMultiActionHandler.dispose();
fMultiActionHandler = null;
fInputServices.dispose();
fInputServices = null;
fFindReplaceAction = null;
fOutputCopyAction = null;
fOutputPasteAction = null;
fOutputSelectAllAction = null;
fOutputClearAllAction = null;
fInputDeleteAction = null;
fInputCutAction = null;
fInputCopyAction = null;
fInputPasteAction = null;
fInputSelectAllAction = null;
fInputUndoAction = null;
fDebugListener = null;
fRemoveAction.dispose();
fRemoveAction = null;
fRemoveAllAction.dispose();
fRemoveAllAction = null;
fTerminateAction.dispose();
fTerminateAction = null;
fOutputViewer = null;
}
if (fInputGroup != null) {
fInputGroup.dispose();
fInputGroup = null;
}
}
public IPageSite getSite() {
return fSite;
}
public IConsoleView getView() {
return fConsoleView;
}
public Control getControl() {
return fControl;
}
public NIConsole getConsole() {
return fConsole;
}
public Clipboard getClipboard() {
return fClipboard;
}
public ToolProcess getTool() {
return fConsole.getProcess();
}
public void addToolRetargetable(final IToolRetargetable action) {
fToolActions.add(action);
}
public IMenuManager getOutputContextMenuManager() {
return fOutputMenuManager;
}
public IMenuManager getInputContextMenuManager() {
return fInputMenuManager;
}
/**
* Return the text in the input line.
*
* @return
*/
public String getInput() {
return fInputGroup.fDocument.get();
}
/**
* Clear the input line (e.g. after successful submit).
*/
public void clearInput() {
fInputGroup.clear();
}
public Object getAdapter(final Class required) {
if (Widget.class.equals(required)) {
if (fOutputViewer.getControl().isFocusControl())
return fOutputViewer.getTextWidget();
return fInputGroup.getSourceViewer().getTextWidget();
}
if (IFindReplaceTarget.class.equals(required)) {
if (fInputGroup.getSourceViewer().getControl().isFocusControl())
return fInputGroup.getSourceViewer().getFindReplaceTarget();
return fOutputViewer.getFindReplaceTarget();
}
if (IShowInSource.class.equals(required)) {
return this;
}
if (IShowInTargetList.class.equals(required)) {
return this;
}
if (IEditorAdapter.class.equals(required)) {
return fInputGroup.fEditorAdapter;
}
return fConsole.getAdapter(required);
}
public ShowInContext getShowInContext() {
final IProcess process = fConsole.getProcess();
if (process == null) {
return null;
}
final IDebugTarget target = (IDebugTarget) process.getAdapter(IDebugTarget.class);
ISelection selection = null;
if (target == null) {
selection = new TreeSelection(new TreePath(new Object[]{
DebugPlugin.getDefault().getLaunchManager(),
process.getLaunch(),
process}));
} else {
selection = new TreeSelection(new TreePath(new Object[]{
DebugPlugin.getDefault().getLaunchManager(),
target.getLaunch(),
target}));
}
return new ShowInContext(null, selection);
}
public String[] getShowInTargetIds() {
return new String[] { IDebugUIConstants.ID_DEBUG_VIEW };
}
public void setActionBars(final IActionBars actionBars) {
// fOutputViewer.setActionBars(actionBars);
}
public void setFocus() {
fInputGroup.getSourceViewer().getControl().setFocus();
}
protected void onToolTerminated() {
if (fIsCreated) {
fTerminateAction.update();
for (final Object action : fToolActions.getListeners()) {
((IToolRetargetable) action).handleToolTerminated();
}
fOutputPasteAction.setEnabled(false);
final Button button = fInputGroup.getSubmitButton();
UIAccess.getDisplay(getSite().getShell()).asyncExec(new Runnable() {
public void run() {
if (UIAccess.isOkToUse(button)) {
button.setEnabled(false);
}
}
});
final IDialogSettings dialogSettings = DialogUtil.getDialogSettings(NicoUIPlugin.getDefault(), DIALOG_ID);
dialogSettings.put(SETTING_INPUTHEIGHT, fResizer.fLastExplicit);
}
}
public void setAutoScroll(final boolean enabled) {
fOutputViewer.setAutoScroll(enabled);
fOutputScrollLockAction.setChecked(!enabled);
}
public void propertyChange(final PropertyChangeEvent event) {
if (UIAccess.isOkToUse(fControl) ) {
final Object source = event.getSource();
final String property = event.getProperty();
if (source.equals(fConsole) && IConsoleConstants.P_FONT.equals(property)) {
final Font font = fConsole.getFont();
fOutputViewer.setFont(font);
fInputGroup.setFont(font);
fResizer.fontChanged();
fControl.layout();
}
else if (IConsoleConstants.P_FONT_STYLE.equals(property)) {
fControl.redraw();
}
else if (property.equals(IConsoleConstants.P_STREAM_COLOR)) {
fOutputViewer.getTextWidget().redraw();
}
// else if (source.equals(fConsole) && property.equals(IConsoleConstants.P_TAB_SIZE)) {
// int tabSize = ((Integer) event.getNewValue()).intValue();
// fOutputViewer.setTabWidth(tabSize);
// fInputGroup.getSourceViewer().setTabWidth(tabSize);
// }
else if (source.equals(fConsole) && property.equals(IConsoleConstants.P_CONSOLE_WIDTH)) {
fOutputViewer.setConsoleWidth(fConsole.getConsoleWidth());
}
}
}
public void settingsChanged(final Set<String> groupIds) {
UIAccess.getDisplay().syncExec(new Runnable() {
public void run() {
if (UIAccess.isOkToUse(fControl)) {
handleSettingsChanged(groupIds);
}
}
});
}
protected void handleSettingsChanged(final Set<String> groupIds) {
fInputGroup.handleSettingsChanged(groupIds, null);
}
}
| false | true | public void createControl(final Composite parent) {
StatetCore.getSettingsChangeNotifier().addChangeListener(this);
fConsole.addPropertyChangeListener(this);
fControl = new Composite(parent, SWT.NONE) {
@Override
public boolean setFocus() {
return false; // our page handles focus
}
};
final GridLayout layout = new GridLayout(1, false);
layout.marginHeight = 0;
layout.verticalSpacing = 0;
layout.marginWidth = 0;
fControl.setLayout(layout);
fOutputViewer = new IOConsoleViewer(fControl, fConsole);
fOutputViewer.setReadOnly();
final GridData outputGD = new GridData(SWT.FILL, SWT.FILL, true, true);
fOutputViewer.getControl().setLayoutData(outputGD);
fOutputViewer.getTextWidget().addKeyListener(new KeyListener() {
public void keyPressed(final KeyEvent e) {
}
public void keyReleased(final KeyEvent e) {
if (e.doit
&& (e.character >= 32)
&& (e.stateMask == SWT.NONE || e.stateMask == SWT.SHIFT)
&& (e.keyCode & SWT.KEYCODE_BIT) == 0) {
final StyledText textWidget = fInputGroup.getSourceViewer().getTextWidget();
if (!UIAccess.isOkToUse(textWidget)) {
return;
}
if (textWidget.getCharCount() == 0) {
textWidget.replaceTextRange(0, 0, Character.toString(e.character));
textWidget.setCaretOffset(textWidget.getCharCount());
}
else {
Display.getCurrent().beep();
}
setFocus();
}
}
});
final Sash sash = new Sash(fControl, SWT.HORIZONTAL);
// sash.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
fInputGroup.createControl(fControl, createInputEditorConfigurator());
final GridData inputGD = new GridData(SWT.FILL, SWT.FILL, true, false);
fInputGroup.getComposite().setLayoutData(inputGD);
fOutputViewer.getTextWidget().getHorizontalBar().setVisible(false);
fResizer = new SizeControl(sash, outputGD, inputGD);
sash.addListener(SWT.Selection, fResizer);
fControl.addListener(SWT.Resize, fResizer);
fClipboard = new Clipboard(fControl.getDisplay());
createActions();
hookContextMenu();
hookDND();
contributeToActionBars();
new ConsoleActivationNotifier();
fIsCreated = true;
fInputGroup.updatePrompt(null);
final IDialogSettings dialogSettings = DialogUtil.getDialogSettings(NicoUIPlugin.getDefault(), DIALOG_ID);
try {
final int height = dialogSettings.getInt(SETTING_INPUTHEIGHT);
if (height > 0) {
fResizer.fLastExplicit = height;
}
}
catch (final NumberFormatException e) {
// missing value
}
fResizer.fontChanged();
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
if (UIAccess.isOkToUse(fInputGroup.getSourceViewer())
&& fOutputViewer.getControl().isFocusControl()) {
setFocus();
}
}
});
}
| public void createControl(final Composite parent) {
StatetCore.getSettingsChangeNotifier().addChangeListener(this);
fConsole.addPropertyChangeListener(this);
fControl = new Composite(parent, SWT.NONE) {
@Override
public boolean setFocus() {
return false; // our page handles focus
}
};
final GridLayout layout = new GridLayout(1, false);
layout.marginHeight = 0;
layout.verticalSpacing = 0;
layout.marginWidth = 0;
fControl.setLayout(layout);
fOutputViewer = new IOConsoleViewer(fControl, fConsole);
fOutputViewer.setReadOnly();
final GridData outputGD = new GridData(SWT.FILL, SWT.FILL, true, true);
fOutputViewer.getControl().setLayoutData(outputGD);
fOutputViewer.getTextWidget().addKeyListener(new KeyListener() {
public void keyPressed(final KeyEvent e) {
if (e.doit
&& (e.character >= 32)
&& (e.stateMask == SWT.NONE || e.stateMask == SWT.SHIFT)
&& ( ((e.keyCode & SWT.KEYCODE_BIT) == 0)
|| (SWT.KEYCODE_BIT + 32 <= e.keyCode && e.keyCode <= (SWT.KEYCODE_BIT + 80)) )) {
final StyledText textWidget = fInputGroup.getSourceViewer().getTextWidget();
if (!UIAccess.isOkToUse(textWidget)) {
return;
}
if (textWidget.getCharCount() == 0) {
textWidget.replaceTextRange(0, 0, Character.toString(e.character));
textWidget.setCaretOffset(textWidget.getCharCount());
}
else {
Display.getCurrent().beep();
}
setFocus();
}
}
public void keyReleased(final KeyEvent e) {
}
});
final Sash sash = new Sash(fControl, SWT.HORIZONTAL);
// sash.setBackground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
sash.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
fInputGroup.createControl(fControl, createInputEditorConfigurator());
final GridData inputGD = new GridData(SWT.FILL, SWT.FILL, true, false);
fInputGroup.getComposite().setLayoutData(inputGD);
fOutputViewer.getTextWidget().getHorizontalBar().setVisible(false);
fResizer = new SizeControl(sash, outputGD, inputGD);
sash.addListener(SWT.Selection, fResizer);
fControl.addListener(SWT.Resize, fResizer);
fClipboard = new Clipboard(fControl.getDisplay());
createActions();
hookContextMenu();
hookDND();
contributeToActionBars();
new ConsoleActivationNotifier();
fIsCreated = true;
fInputGroup.updatePrompt(null);
final IDialogSettings dialogSettings = DialogUtil.getDialogSettings(NicoUIPlugin.getDefault(), DIALOG_ID);
try {
final int height = dialogSettings.getInt(SETTING_INPUTHEIGHT);
if (height > 0) {
fResizer.fLastExplicit = height;
}
}
catch (final NumberFormatException e) {
// missing value
}
fResizer.fontChanged();
Display.getCurrent().asyncExec(new Runnable() {
public void run() {
if (UIAccess.isOkToUse(fInputGroup.getSourceViewer())
&& fOutputViewer.getControl().isFocusControl()) {
setFocus();
}
}
});
}
|
diff --git a/src/Servlets/AcctManagementServlet.java b/src/Servlets/AcctManagementServlet.java
index 506b769..c72e748 100755
--- a/src/Servlets/AcctManagementServlet.java
+++ b/src/Servlets/AcctManagementServlet.java
@@ -1,66 +1,66 @@
package Servlets;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Accounts.Account;
import Accounts.AccountManager;
/**
* Servlet implementation class AcctManagementServlet
*/
@WebServlet("/AcctManagementServlet")
public class AcctManagementServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AcctManagementServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("Action");
String name = request.getParameter("User");
String pass = request.getParameter("Pass");
System.out.println(action);
ServletContext sc = request.getServletContext();
AccountManager am = (AccountManager) sc.getAttribute("accounts");
if (action.equals("Create")) {
Account acct = am.createAccount(name, pass);
if (acct == null) {
request.getRequestDispatcher("/NameTaken.jsp").forward(request, response);
} else {
sc.setAttribute("user", name);
Account curracct = (Account) request.getSession().getAttribute("account");
curracct = acct;
- request.getRequestDispatcher("/accountDebug.jsp").forward(request, response);
+ request.getRequestDispatcher("/UserHome.jsp").forward(request, response);
}
} else if (action.equals("Delete")) {
am.deleteAccount(name);
request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
} else if (action.equals("Logout")) {
am.logoutAccount((Account) request.getSession().getAttribute("account"));
request.getSession().setAttribute("account", null);
request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
}
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("Action");
String name = request.getParameter("User");
String pass = request.getParameter("Pass");
System.out.println(action);
ServletContext sc = request.getServletContext();
AccountManager am = (AccountManager) sc.getAttribute("accounts");
if (action.equals("Create")) {
Account acct = am.createAccount(name, pass);
if (acct == null) {
request.getRequestDispatcher("/NameTaken.jsp").forward(request, response);
} else {
sc.setAttribute("user", name);
Account curracct = (Account) request.getSession().getAttribute("account");
curracct = acct;
request.getRequestDispatcher("/accountDebug.jsp").forward(request, response);
}
} else if (action.equals("Delete")) {
am.deleteAccount(name);
request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
} else if (action.equals("Logout")) {
am.logoutAccount((Account) request.getSession().getAttribute("account"));
request.getSession().setAttribute("account", null);
request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
}
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("Action");
String name = request.getParameter("User");
String pass = request.getParameter("Pass");
System.out.println(action);
ServletContext sc = request.getServletContext();
AccountManager am = (AccountManager) sc.getAttribute("accounts");
if (action.equals("Create")) {
Account acct = am.createAccount(name, pass);
if (acct == null) {
request.getRequestDispatcher("/NameTaken.jsp").forward(request, response);
} else {
sc.setAttribute("user", name);
Account curracct = (Account) request.getSession().getAttribute("account");
curracct = acct;
request.getRequestDispatcher("/UserHome.jsp").forward(request, response);
}
} else if (action.equals("Delete")) {
am.deleteAccount(name);
request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
} else if (action.equals("Logout")) {
am.logoutAccount((Account) request.getSession().getAttribute("account"));
request.getSession().setAttribute("account", null);
request.getRequestDispatcher("/GuestHome.jsp").forward(request, response);
}
}
|
diff --git a/src/main/java/com/senseidb/clue/ClueApplication.java b/src/main/java/com/senseidb/clue/ClueApplication.java
index ae3817a..48d9095 100644
--- a/src/main/java/com/senseidb/clue/ClueApplication.java
+++ b/src/main/java/com/senseidb/clue/ClueApplication.java
@@ -1,96 +1,97 @@
package com.senseidb.clue;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import com.senseidb.clue.commands.ClueCommand;
import com.senseidb.clue.commands.HelpCommand;
public class ClueApplication {
private final ClueContext ctx;
private final ClueCommand helpCommand;
public ClueApplication(String idxLocation, boolean interactiveMode) throws IOException{
FSDirectory dir = FSDirectory.open(new File(idxLocation));
if (!DirectoryReader.indexExists(dir)){
System.out.println("lucene index does not exist at: "+idxLocation);
System.exit(1);
}
IndexWriterConfig writerConfig = new IndexWriterConfig(Version.LUCENE_43, new StandardAnalyzer(Version.LUCENE_43));
ctx = new ClueContext(dir, new IndexReaderFactory(dir), writerConfig, interactiveMode);
helpCommand = ctx.getCommand(HelpCommand.CMD_NAME);
}
public void handleCommand(String cmdName, String[] args, PrintStream out){
ClueCommand cmd = ctx.getCommand(cmdName);
if (cmd == null){
out.println(cmdName+" is not supported:");
cmd = helpCommand;
}
try{
cmd.execute(args, out);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
if (args.length < 1){
System.out.println("usage: <index location> <command> <command args>");
System.exit(1);
}
String idxLocation = args[0];
ClueApplication app = null;
if (args.length > 1){
String cmd = args[1];
if ("readonly".equalsIgnoreCase(cmd)) {
if (args.length > 2) {
cmd = args[2];
app = new ClueApplication(idxLocation, false);
String[] cmdArgs;
cmdArgs = new String[args.length - 3];
System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length);
app.ctx.setReadOnlyMode(true);
app.handleCommand(cmd, cmdArgs, System.out);
}
}
else {
app = new ClueApplication(idxLocation, false);
String[] cmdArgs;
cmdArgs = new String[args.length - 2];
System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
return;
}
app = new ClueApplication(idxLocation, true);
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("> ");
- String line = inReader.readLine().trim();
- if (line.isEmpty()) continue;
+ String line = inReader.readLine();
+ if (line == null || line.isEmpty()) continue;
+ line = line.trim();
String[] parts = line.split("\\s");
if (parts.length > 0){
String cmd = parts[0];
String[] cmdArgs = new String[parts.length - 1];
System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
}
}
}
| true | true | public static void main(String[] args) throws Exception {
if (args.length < 1){
System.out.println("usage: <index location> <command> <command args>");
System.exit(1);
}
String idxLocation = args[0];
ClueApplication app = null;
if (args.length > 1){
String cmd = args[1];
if ("readonly".equalsIgnoreCase(cmd)) {
if (args.length > 2) {
cmd = args[2];
app = new ClueApplication(idxLocation, false);
String[] cmdArgs;
cmdArgs = new String[args.length - 3];
System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length);
app.ctx.setReadOnlyMode(true);
app.handleCommand(cmd, cmdArgs, System.out);
}
}
else {
app = new ClueApplication(idxLocation, false);
String[] cmdArgs;
cmdArgs = new String[args.length - 2];
System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
return;
}
app = new ClueApplication(idxLocation, true);
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("> ");
String line = inReader.readLine().trim();
if (line.isEmpty()) continue;
String[] parts = line.split("\\s");
if (parts.length > 0){
String cmd = parts[0];
String[] cmdArgs = new String[parts.length - 1];
System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
}
}
| public static void main(String[] args) throws Exception {
if (args.length < 1){
System.out.println("usage: <index location> <command> <command args>");
System.exit(1);
}
String idxLocation = args[0];
ClueApplication app = null;
if (args.length > 1){
String cmd = args[1];
if ("readonly".equalsIgnoreCase(cmd)) {
if (args.length > 2) {
cmd = args[2];
app = new ClueApplication(idxLocation, false);
String[] cmdArgs;
cmdArgs = new String[args.length - 3];
System.arraycopy(args, 3, cmdArgs, 0, cmdArgs.length);
app.ctx.setReadOnlyMode(true);
app.handleCommand(cmd, cmdArgs, System.out);
}
}
else {
app = new ClueApplication(idxLocation, false);
String[] cmdArgs;
cmdArgs = new String[args.length - 2];
System.arraycopy(args, 2, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
return;
}
app = new ClueApplication(idxLocation, true);
BufferedReader inReader = new BufferedReader(new InputStreamReader(System.in));
while(true){
System.out.print("> ");
String line = inReader.readLine();
if (line == null || line.isEmpty()) continue;
line = line.trim();
String[] parts = line.split("\\s");
if (parts.length > 0){
String cmd = parts[0];
String[] cmdArgs = new String[parts.length - 1];
System.arraycopy(parts, 1, cmdArgs, 0, cmdArgs.length);
app.handleCommand(cmd, cmdArgs, System.out);
}
}
}
|
diff --git a/GraderGenerator.java b/GraderGenerator.java
index eb5e54f..d214605 100644
--- a/GraderGenerator.java
+++ b/GraderGenerator.java
@@ -1,500 +1,500 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class GraderGenerator
{
// A HashSet to quickly parse a "yes"
static HashSet<String> possibleYes = new HashSet<String>();
static {
possibleYes.add("Yes");
possibleYes.add("yes");
possibleYes.add("y");
possibleYes.add("Y");
possibleYes.add("YES");
possibleYes.add("");
}
// Scanner to read user input
private Scanner in;
//
private LinkedList<LinkedHashMap<String, String>> partAnswers;
// This class will ask a series of questions to construct a Grader Script
public GraderGenerator()
{
in = new Scanner(System.in);
partAnswers = new LinkedList<LinkedHashMap<String, String>>();
int threads = getThreads();
boolean checkGit = checkGit();
int parts = getParts();
for (int i = 0; i < parts; i++) {
LinkedHashMap<String, String> answers = new LinkedHashMap<String, String>();
partAnswers.add(answers);
partBuilder(answers, (i + 1));
}
buildScript(threads, checkGit, partAnswers);
}
private void partBuilder(HashMap<String, String> answers, int partNum)
{
String partName = "part" + partNum;
boolean accepted = false;
do {
System.out.print(partName + ") Executable name: ");
answers.put("exec", in.nextLine());
do {
System.out.print(partName
+ ") Should this program have a time limit (in seconds) [0]: ");
answers.put("limit", in.nextLine());
} while (!isIntegerOrEmpty(answers.get("limit")));
System.out.print(partName + ") Should this program read input from a file []: ");
answers.put("input-file", in.nextLine());
System.out
.print("Do you want to run scripts/programs at various points during testing [n]: ");
String divergent = in.nextLine();
if (!divergent.isEmpty() && possibleYes.contains(divergent)) {
System.out.print("Script to run before building []: ");
answers.put("script-before-building", in.nextLine());
System.out.print("Script to run after building []: ");
answers.put("script-after-building", in.nextLine());
System.out.print("Script to run during execution []: ");
answers.put("script-during-run", in.nextLine());
System.out.print("Script to run after execution []: ");
answers.put("script-after-run", in.nextLine());
System.out.print("Script to run after cleaning []: ");
answers.put("script-after-cleaning", in.nextLine());
}
System.out.print("Enter set of command line arguments []: ");
answers.put("args", parseArgs(in.nextLine()));
System.out.print("Which parts does " + partName + " depend on []: ");
answers.put("dependencies", parseParts(in.nextLine()));
System.out.print("Would you like to compile and test additional drivers [n]: ");
divergent = in.nextLine();
if (!divergent.isEmpty() && possibleYes.contains(divergent)) {
do {
System.out.print("What directory contains these files: ");
answers.put("driver-dir", in.nextLine());
} while (answers.get("driver-dir").isEmpty());
do {
System.out.print("What are the executable names: ");
answers.put("driver-exec", parseNames(in.nextLine()));
} while (answers.get("driver-exec").isEmpty());
}
accepted = acceptSummary(answers);
} while (!accepted);
}
private boolean acceptSummary(HashMap<String, String> answers)
{
System.out.println("====Script summary====");
for (Map.Entry<String, String> entry : answers.entrySet())
System.out.println(entry.getKey() + " : " + entry.getValue());
System.out.println("======================");
System.out.print("Are you sure these parameters are correct [y]: ");
return possibleYes.contains(in.nextLine());
}
private String parseNames(String nextLine)
{
String[] execArr = nextLine.split("(\\ )+|[,;:][,;:\\ ]*");
String names = Arrays.toString(execArr);
return names.substring(1, names.length() - 1);
}
private String parseParts(String nextLine)
{
String parts = "";
if (nextLine.isEmpty())
return parts;
ArrayList<Integer> partsArr = new ArrayList<Integer>();
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(nextLine);
while (m.find())
partsArr.add(Integer.parseInt(m.group()));
parts = Arrays.toString(partsArr.toArray(new Integer[partsArr.size()]));
return parts.substring(1, parts.length() - 1);
}
private String parseArgs(String nextLine)
{
String[] argsArr = nextLine.split("(\\ )*\\|\\|(\\ )*");
StringBuilder args = new StringBuilder();
for (String s : argsArr)
if (!s.isEmpty())
args.append(s + "||");
if (args.length() > 0)
return args.toString().substring(0, args.length() - 2);
else
return "";
}
int getParts()
{
String line;
do {
System.out.print("How many parts: ");
line = in.nextLine();
} while (!isInteger(line));
return Integer.parseInt(line);
}
private boolean isInteger(String line)
{
if (line.isEmpty())
return false;
else
for (Character c : line.toCharArray())
if (!Character.isDigit(c))
return false;
return true;
}
private boolean checkGit()
{
System.out.print("Check git commit log [y]: ");
if (possibleYes.contains(in.nextLine()))
return true;
return false;
}
int getThreads()
{
int threads = (int) Math.round(Runtime.getRuntime().availableProcessors());
String line;
do {
System.out.print("How many threads [" + (threads / 2) + "]: ");
line = in.nextLine();
} while (!isIntegerOrEmpty(line));
int givenThreads = threads + 1;
if (!line.isEmpty())
Integer.parseInt(line);
if (givenThreads <= threads)
return givenThreads;
else
return threads / 2;
}
private boolean isIntegerOrEmpty(String line)
{
for (Character c : line.toCharArray())
if (!Character.isDigit(c))
return false;
return true;
}
public static void main(String[] args)
{
new GraderGenerator();
}
private void buildScript(int threads, boolean checkGit,
LinkedList<LinkedHashMap<String, String>> answerList)
{
File graderFile = new File("Grader.java");
if (graderFile.exists())
if (!graderFile.delete())
System.exit(1);
PrintWriter gw = null;
try {
if (!graderFile.createNewFile())
System.exit(1);
gw = new PrintWriter(new FileOutputStream(graderFile), true);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// Print out the imports
gw.println("import java.io.File;\n" + "import java.io.FileOutputStream;\n"
+ "import java.io.IOException;\n" + "import java.io.PrintStream;\n"
+ "import java.util.Timer;\n" + "import java.util.concurrent.ConcurrentLinkedQueue;\n"
+ "import java.util.concurrent.Executors;\n" + "import java.nio.file.CopyOption;\n"
+ "import java.nio.file.Files;\n" + "import java.nio.file.Path;\n"
+ "import java.nio.file.StandardCopyOption;\n"
+ "import java.util.concurrent.atomic.AtomicInteger;");
// Print out the static, single-threaded portion
gw.println("public class Grader\n" + "{\n"
+ "AtomicInteger counter = new AtomicInteger(0);\n"
+ "public Grader(String root, int threads)\n" + "{\n"
+ "Checks.exec = Executors.newFixedThreadPool(2 * threads + 2);\n"
+ "Checks.tmArr = new Timer[threads];\n" + "Timer[] tmArr = Checks.tmArr;\n"
+ "for (int j = 0; j < tmArr.length; j++)\n" + "tmArr[j] = new Timer(true);\n"
+ "File rootDir = new File(root);\n"
+ "ConcurrentLinkedQueue<File> uniDirs = new ConcurrentLinkedQueue<File>();\n"
+ "for (File f : rootDir.listFiles())\n" + getValidDirectories(answerList) + "\n"
+ "uniDirs.add(f);\n" + "Thread[] workers = new Thread[threads];\n"
+ "for (int i = 0; i < threads; i++) {\n"
+ "workers[i] = new Thread(new GraderWorker(uniDirs, i));\n" + "workers[i].start();\n"
+ "}\n" + "for (Thread worker : workers)\n" + "try {\n" + "worker.join();\n"
+ "} catch (InterruptedException e) {\n" + "e.printStackTrace();\n" + "}\n"
+ "Checks.exec.shutdown();\n" + "}");
// Print out the main method
- gw.println("public static void main(String[] args)\n" + "{\n" + "new GraderMT(\"./\", "
+ gw.println("public static void main(String[] args)\n" + "{\n" + "new Grader(\"./\", "
+ threads + ");\n" + "}");
// Print out the folder delete method
gw.println("private void deleteFolder(File source)\n" + "{\n"
+ "File[] contents = source.listFiles();\n" + "for (File f : contents) {\n"
+ "if (f.getName().equals(\".\") || f.getName().equals(\"..\"))\n" + "continue;\n"
+ "if (f.isDirectory())\n" + "deleteFolder(f);\n" + "else\n" + "f.delete();\n" + "}\n"
+ "source.delete();\n" + "}");
// Print out the symlink method
gw.println("public void symlink(File src, File dest, Checks check)\n" + "{\n"
+ "File[] srcFiles = src.listFiles();\n" + "for (File f : srcFiles) {\n"
+ "if (f.getName().equals(dest.getName()) || f.getName().equals(\"Makefile\"))\n"
+ "continue;\n" + "check.jockeyCommand(dest, \"ln -s ../\" + f.getName(), null);\n"
+ "}\n" + "}");
// Print out the copy folder method
gw.println("public void copyFiles(File src, File dest)\n" + "{\n" + "Path from;\n"
+ "Path to;\n" + "CopyOption[] options =\n"
+ "new CopyOption[] {StandardCopyOption.REPLACE_EXISTING,\n"
+ "StandardCopyOption.COPY_ATTRIBUTES};\n" + "File[] srcFiles = src.listFiles();\n"
+ "for (File f : srcFiles) {\n"
+ "if (f.getName().equals(\".\") || f.getName().equals(\"..\")) {\n" + "continue;\n"
+ "} else if (f.isDirectory()) {\n" + "File newDir = new File(dest, f.getName());\n"
+ "newDir.mkdir();\n" + "copyFiles(f, newDir);\n" + "} else {\n"
+ "from = src.toPath();\n" + "to = new File(dest, f.getName()).toPath();\n" + "try {\n"
+ "Files.copy(from, to, options);\n" + "} catch (IOException e) {\n"
+ "e.printStackTrace();\n" + "}\n" + "}\n" + "}\n" + "}");
// Now for GraderWorker
gw.println("class GraderWorker implements Runnable\n"
+ "{\n"
+ "PrintStream out;\n"
+ "PrintStream err;\n"
+ "int number;\n"
+ "ConcurrentLinkedQueue<File> uniDirs;\n"
+ "public GraderWorker(ConcurrentLinkedQueue<File> queue, int number)\n"
+ "{\n"
+ "uniDirs = queue;\n"
+ "this.number = number;\n"
+ "}\n"
+ "@Override\n"
+ "public void run()\n"
+ "{\n"
+ "File student = null;\n"
+ "while ((student = uniDirs.poll()) != null) {\n"
+ "Checks check = null;\n"
+ "System.out.println(\"Grader \" + number + \": Verifying \" + student.getName() + \"...\");\n"
+ "File results = new File(student, \"GRADE_RESULTS.txt\");\n" + "try {\n"
+ "if (results.isFile())\n" + "results.delete();\n" + "results.createNewFile();\n"
+ "check = new Checks(results, number);\n" + "} catch (IOException e) {\n"
+ "System.err.println(\"Unable to redirect output to file\");\n"
+ "e.printStackTrace();\n" + "}\n"
+ "File summary = new File(student, \"SUMMARY.txt\");\n" + "try {\n"
+ "if (summary.isFile())\n" + "summary.delete();\n" + "summary.createNewFile();\n"
+ "FileOutputStream summaryStream = new FileOutputStream(summary);\n"
+ "out = new PrintStream(summaryStream);\n" + "err = new PrintStream(summaryStream);\n"
+ "} catch (IOException e) {\n"
+ "System.err.println(\"Unable to redirect output to file.\");\n"
+ "e.printStackTrace();\n" + "}");
// Checking git commits
if (checkGit) {
gw.println("boolean goodCommit = check.checkGitCommits(student);\n"
+ "if (goodCommit)\n" + "out.println(student.getName() + \" GIT+\");\n" + "else\n"
+ "err.println(student.getName() + \" GIT-\");");
}
// Set any persistent variables
gw.println("File partDir;");
gw.println("File partDep;");
gw.println("boolean[] badProgram;");
gw.println("boolean cleanWorked;");
gw.println("boolean goodMake;");
// For each part...
int partNum = 1;
String exec;
for (LinkedHashMap<String, String> answer : answerList) {
exec = answer.get("exec");
// Set the current part directory to here
gw.println("partDir = new File(student, \"part" + partNum + "\");");
// Inidicate that we're checking this part
gw.println("check.printMessage(\"\\n" + answer.get("exec") + " verification:\", 1);");
// Pre build script
String script = answer.get("script-before-building");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
// Build any dependencies before hand
String dep = answer.get("dependencies");
if (!dep.isEmpty()) {
gw.println("check.printMessage(\"===Building dependencies for part" + partNum
+ "===\", 1);");
String[] depArr = dep.split(",");
for (String partDep : depArr) {
int num = Integer.parseInt(partDep.trim());
gw.println("partDep = new File(student, \"part" + num + "\");");
gw.println("check.checkMake(partDep, \"" + answerList.get(num - 1).get("exec")
+ "\");");
}
gw.println("check.printMessage(\"===Dependencies built===\", 1);");
}
// Build
gw.println("goodMake = check.checkMake(partDir, \"" + exec + "\");\n"
+ "if (goodMake)\n" + "out.println(student.getName() + \" " + exec
+ ": make+\");\n" + "else\n" + "err.println(student.getName() + \" " + exec
+ ": make-\");");
// Post build script
script = answer.get("script-after-building");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
// Run tests
String args = answer.get("args");
if (args.isEmpty()) {
gw.println(buildCommand(exec, "", answer.get("input-file"), answer.get("limit"))
+ "\n" + "if (badProgram[0])\n" + "err.println(student.getName() + \" " + exec
+ ": memory error-\");\n" + "else\n" + "out.println(student.getName() + \" "
+ exec + ": memory error+\");\n" + "if (badProgram[1])\n"
+ "err.println(student.getName() + \" " + exec + ": leak error-\");\n"
+ "else\n" + "out.println(student.getName() + \" " + exec + ": leak error+\");");
script = answer.get("script-during-run");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
} else {
String[] argsArr = args.split("\\|\\|");
int run = 0;
for (String arg : argsArr) {
gw.println("out.println(\"Test " + (run++) + ":\");");
gw.println(buildCommand(exec, arg, answer.get("input-file"),
answer.get("limit"))
+ "\n"
+ "if (badProgram[0])\n"
+ "err.println(student.getName() + \" "
+ exec
+ ": memory error-\");\n"
+ "else\n"
+ "out.println(student.getName() + \" "
+ exec
+ ": memory error+\");\n"
+ "if (badProgram[1])\n"
+ "err.println(student.getName() + \" "
+ exec
+ ": leak error-\");\n"
+ "else\n"
+ "out.println(student.getName() + \" "
+ exec + ": leak error+\");");
script = answer.get("script-during-run");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
}
}
// Additional drivers
if (answer.get("driver-dir") != null)
runDrivers(gw, answer);
// Post run script
script = answer.get("script-after-run");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
// Clean up
gw.println("cleanWorked = check.checkMakeClean(partDir, \"" + exec + "\");\n"
+ "if (cleanWorked)\n" + "out.println(student.getName() + \" " + exec
+ ": make clean+\");\n" + "else\n" + "err.println(student.getName() + \" " + exec
+ ": make clean-\");");
// Post clean script
script = answer.get("script-after-cleaning");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
partNum++;
}
// Announce that we're done
gw.println("check.shutdown();\n"
+ "System.out.println(\"Grader \" + number + \": done with \"+student.getName()+\".\");");
// The final brackets
gw.println("}\n}\n}\n}");
// Done
gw.close();
}
private void runDrivers(PrintWriter gw, LinkedHashMap<String, String> answer)
{
// Get the driver directory
String dirName = answer.get("driver-dir");
String driverExec = answer.get("driver-exec");
// Run the driver
gw.println("File dest = new File(partDir, \"" + dirName + "\");\n" + "if (dest.exists())\n"
+ "deleteFolder(dest);\n" + "dest.mkdirs();\n" + "symlink(partDir, dest, check);\n"
+ "File src = new File(\"" + dirName + "\");\n" + "copyFiles(src, dest);\n"
+ "goodMake = check.checkMake(dest, \"" + driverExec + "\");\n" + "if (goodMake)\n"
+ "out.println(student.getName() + \" -DRIVER- " + driverExec + ": make+\");\n"
+ "else\n" + "err.println(student.getName() + \" -DRIVER- " + driverExec
+ ": make-\");");
String[] execNames = driverExec.split(",\\ ");
for (String exec : execNames)
gw.println("badProgram = check.testCommand(dest, \"" + exec + "\", null, 0);\n"
+ "if (badProgram[0])\n" + "err.println(student.getName() + \" -DRIVER- " + exec
+ ": memory error-\");\n" + "else\n"
+ "out.println(student.getName() + \" -DRIVER- " + exec + ": memory error+\");\n"
+ "if (badProgram[1])\n" + "err.println(student.getName() + \" -DRIVER- " + exec
+ ": leak error-\");\n" + "else\n" + "out.println(student.getName() + \" -DRIVER- "
+ exec + ": leak error+\");");
gw.println("cleanWorked = check.checkMakeClean(dest, \"" + driverExec + "\");\n"
+ "if (cleanWorked)\n" + "out.println(student.getName() + \" -DRIVER- " + driverExec
+ ": make clean+\");\n" + "else\n" + "err.println(student.getName() + \" -DRIVER- "
+ driverExec + ": make clean-\");");
}
private String buildCommand(String exec, String args, String inputFile, String limit)
{
StringBuilder command =
new StringBuilder("badProgram = check.testCommand(partDir, \"" + exec);
if (!args.isEmpty())
command.append(" " + args + "\",");
else
command.append("\",");
if (!inputFile.isEmpty())
command.append(" new File(\"" + inputFile + "\"),");
else
command.append(" null,");
if (!limit.isEmpty())
command.append(" " + limit + ");");
else
command.append(" 0);");
return command.toString();
}
private String getValidDirectories(LinkedList<LinkedHashMap<String, String>> answerList)
{
StringBuilder dirs =
new StringBuilder(
"if (f.isDirectory() && !f.getName().startsWith(\".\") && !f.getName().startsWith(\"lab\")");
for (LinkedHashMap<String, String> map : answerList) {
String dir = map.get("driver-dir");
if (dir != null)
dirs.append(" && !f.getName().equalsIgnoreCase(\"" + dir + "\")");
}
return dirs.toString() + ")";
}
}
| true | true | private void buildScript(int threads, boolean checkGit,
LinkedList<LinkedHashMap<String, String>> answerList)
{
File graderFile = new File("Grader.java");
if (graderFile.exists())
if (!graderFile.delete())
System.exit(1);
PrintWriter gw = null;
try {
if (!graderFile.createNewFile())
System.exit(1);
gw = new PrintWriter(new FileOutputStream(graderFile), true);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// Print out the imports
gw.println("import java.io.File;\n" + "import java.io.FileOutputStream;\n"
+ "import java.io.IOException;\n" + "import java.io.PrintStream;\n"
+ "import java.util.Timer;\n" + "import java.util.concurrent.ConcurrentLinkedQueue;\n"
+ "import java.util.concurrent.Executors;\n" + "import java.nio.file.CopyOption;\n"
+ "import java.nio.file.Files;\n" + "import java.nio.file.Path;\n"
+ "import java.nio.file.StandardCopyOption;\n"
+ "import java.util.concurrent.atomic.AtomicInteger;");
// Print out the static, single-threaded portion
gw.println("public class Grader\n" + "{\n"
+ "AtomicInteger counter = new AtomicInteger(0);\n"
+ "public Grader(String root, int threads)\n" + "{\n"
+ "Checks.exec = Executors.newFixedThreadPool(2 * threads + 2);\n"
+ "Checks.tmArr = new Timer[threads];\n" + "Timer[] tmArr = Checks.tmArr;\n"
+ "for (int j = 0; j < tmArr.length; j++)\n" + "tmArr[j] = new Timer(true);\n"
+ "File rootDir = new File(root);\n"
+ "ConcurrentLinkedQueue<File> uniDirs = new ConcurrentLinkedQueue<File>();\n"
+ "for (File f : rootDir.listFiles())\n" + getValidDirectories(answerList) + "\n"
+ "uniDirs.add(f);\n" + "Thread[] workers = new Thread[threads];\n"
+ "for (int i = 0; i < threads; i++) {\n"
+ "workers[i] = new Thread(new GraderWorker(uniDirs, i));\n" + "workers[i].start();\n"
+ "}\n" + "for (Thread worker : workers)\n" + "try {\n" + "worker.join();\n"
+ "} catch (InterruptedException e) {\n" + "e.printStackTrace();\n" + "}\n"
+ "Checks.exec.shutdown();\n" + "}");
// Print out the main method
gw.println("public static void main(String[] args)\n" + "{\n" + "new GraderMT(\"./\", "
+ threads + ");\n" + "}");
// Print out the folder delete method
gw.println("private void deleteFolder(File source)\n" + "{\n"
+ "File[] contents = source.listFiles();\n" + "for (File f : contents) {\n"
+ "if (f.getName().equals(\".\") || f.getName().equals(\"..\"))\n" + "continue;\n"
+ "if (f.isDirectory())\n" + "deleteFolder(f);\n" + "else\n" + "f.delete();\n" + "}\n"
+ "source.delete();\n" + "}");
// Print out the symlink method
gw.println("public void symlink(File src, File dest, Checks check)\n" + "{\n"
+ "File[] srcFiles = src.listFiles();\n" + "for (File f : srcFiles) {\n"
+ "if (f.getName().equals(dest.getName()) || f.getName().equals(\"Makefile\"))\n"
+ "continue;\n" + "check.jockeyCommand(dest, \"ln -s ../\" + f.getName(), null);\n"
+ "}\n" + "}");
// Print out the copy folder method
gw.println("public void copyFiles(File src, File dest)\n" + "{\n" + "Path from;\n"
+ "Path to;\n" + "CopyOption[] options =\n"
+ "new CopyOption[] {StandardCopyOption.REPLACE_EXISTING,\n"
+ "StandardCopyOption.COPY_ATTRIBUTES};\n" + "File[] srcFiles = src.listFiles();\n"
+ "for (File f : srcFiles) {\n"
+ "if (f.getName().equals(\".\") || f.getName().equals(\"..\")) {\n" + "continue;\n"
+ "} else if (f.isDirectory()) {\n" + "File newDir = new File(dest, f.getName());\n"
+ "newDir.mkdir();\n" + "copyFiles(f, newDir);\n" + "} else {\n"
+ "from = src.toPath();\n" + "to = new File(dest, f.getName()).toPath();\n" + "try {\n"
+ "Files.copy(from, to, options);\n" + "} catch (IOException e) {\n"
+ "e.printStackTrace();\n" + "}\n" + "}\n" + "}\n" + "}");
// Now for GraderWorker
gw.println("class GraderWorker implements Runnable\n"
+ "{\n"
+ "PrintStream out;\n"
+ "PrintStream err;\n"
+ "int number;\n"
+ "ConcurrentLinkedQueue<File> uniDirs;\n"
+ "public GraderWorker(ConcurrentLinkedQueue<File> queue, int number)\n"
+ "{\n"
+ "uniDirs = queue;\n"
+ "this.number = number;\n"
+ "}\n"
+ "@Override\n"
+ "public void run()\n"
+ "{\n"
+ "File student = null;\n"
+ "while ((student = uniDirs.poll()) != null) {\n"
+ "Checks check = null;\n"
+ "System.out.println(\"Grader \" + number + \": Verifying \" + student.getName() + \"...\");\n"
+ "File results = new File(student, \"GRADE_RESULTS.txt\");\n" + "try {\n"
+ "if (results.isFile())\n" + "results.delete();\n" + "results.createNewFile();\n"
+ "check = new Checks(results, number);\n" + "} catch (IOException e) {\n"
+ "System.err.println(\"Unable to redirect output to file\");\n"
+ "e.printStackTrace();\n" + "}\n"
+ "File summary = new File(student, \"SUMMARY.txt\");\n" + "try {\n"
+ "if (summary.isFile())\n" + "summary.delete();\n" + "summary.createNewFile();\n"
+ "FileOutputStream summaryStream = new FileOutputStream(summary);\n"
+ "out = new PrintStream(summaryStream);\n" + "err = new PrintStream(summaryStream);\n"
+ "} catch (IOException e) {\n"
+ "System.err.println(\"Unable to redirect output to file.\");\n"
+ "e.printStackTrace();\n" + "}");
// Checking git commits
if (checkGit) {
gw.println("boolean goodCommit = check.checkGitCommits(student);\n"
+ "if (goodCommit)\n" + "out.println(student.getName() + \" GIT+\");\n" + "else\n"
+ "err.println(student.getName() + \" GIT-\");");
}
// Set any persistent variables
gw.println("File partDir;");
gw.println("File partDep;");
gw.println("boolean[] badProgram;");
gw.println("boolean cleanWorked;");
gw.println("boolean goodMake;");
// For each part...
int partNum = 1;
String exec;
for (LinkedHashMap<String, String> answer : answerList) {
exec = answer.get("exec");
// Set the current part directory to here
gw.println("partDir = new File(student, \"part" + partNum + "\");");
// Inidicate that we're checking this part
gw.println("check.printMessage(\"\\n" + answer.get("exec") + " verification:\", 1);");
// Pre build script
String script = answer.get("script-before-building");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
// Build any dependencies before hand
String dep = answer.get("dependencies");
if (!dep.isEmpty()) {
gw.println("check.printMessage(\"===Building dependencies for part" + partNum
+ "===\", 1);");
String[] depArr = dep.split(",");
for (String partDep : depArr) {
int num = Integer.parseInt(partDep.trim());
gw.println("partDep = new File(student, \"part" + num + "\");");
gw.println("check.checkMake(partDep, \"" + answerList.get(num - 1).get("exec")
+ "\");");
}
gw.println("check.printMessage(\"===Dependencies built===\", 1);");
}
// Build
gw.println("goodMake = check.checkMake(partDir, \"" + exec + "\");\n"
+ "if (goodMake)\n" + "out.println(student.getName() + \" " + exec
+ ": make+\");\n" + "else\n" + "err.println(student.getName() + \" " + exec
+ ": make-\");");
// Post build script
script = answer.get("script-after-building");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
// Run tests
String args = answer.get("args");
if (args.isEmpty()) {
gw.println(buildCommand(exec, "", answer.get("input-file"), answer.get("limit"))
+ "\n" + "if (badProgram[0])\n" + "err.println(student.getName() + \" " + exec
+ ": memory error-\");\n" + "else\n" + "out.println(student.getName() + \" "
+ exec + ": memory error+\");\n" + "if (badProgram[1])\n"
+ "err.println(student.getName() + \" " + exec + ": leak error-\");\n"
+ "else\n" + "out.println(student.getName() + \" " + exec + ": leak error+\");");
script = answer.get("script-during-run");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
} else {
String[] argsArr = args.split("\\|\\|");
int run = 0;
for (String arg : argsArr) {
gw.println("out.println(\"Test " + (run++) + ":\");");
gw.println(buildCommand(exec, arg, answer.get("input-file"),
answer.get("limit"))
+ "\n"
+ "if (badProgram[0])\n"
+ "err.println(student.getName() + \" "
+ exec
+ ": memory error-\");\n"
+ "else\n"
+ "out.println(student.getName() + \" "
+ exec
+ ": memory error+\");\n"
+ "if (badProgram[1])\n"
+ "err.println(student.getName() + \" "
+ exec
+ ": leak error-\");\n"
+ "else\n"
+ "out.println(student.getName() + \" "
+ exec + ": leak error+\");");
script = answer.get("script-during-run");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
}
}
// Additional drivers
if (answer.get("driver-dir") != null)
runDrivers(gw, answer);
// Post run script
script = answer.get("script-after-run");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
// Clean up
gw.println("cleanWorked = check.checkMakeClean(partDir, \"" + exec + "\");\n"
+ "if (cleanWorked)\n" + "out.println(student.getName() + \" " + exec
+ ": make clean+\");\n" + "else\n" + "err.println(student.getName() + \" " + exec
+ ": make clean-\");");
// Post clean script
script = answer.get("script-after-cleaning");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
partNum++;
}
// Announce that we're done
gw.println("check.shutdown();\n"
+ "System.out.println(\"Grader \" + number + \": done with \"+student.getName()+\".\");");
// The final brackets
gw.println("}\n}\n}\n}");
// Done
gw.close();
}
| private void buildScript(int threads, boolean checkGit,
LinkedList<LinkedHashMap<String, String>> answerList)
{
File graderFile = new File("Grader.java");
if (graderFile.exists())
if (!graderFile.delete())
System.exit(1);
PrintWriter gw = null;
try {
if (!graderFile.createNewFile())
System.exit(1);
gw = new PrintWriter(new FileOutputStream(graderFile), true);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
// Print out the imports
gw.println("import java.io.File;\n" + "import java.io.FileOutputStream;\n"
+ "import java.io.IOException;\n" + "import java.io.PrintStream;\n"
+ "import java.util.Timer;\n" + "import java.util.concurrent.ConcurrentLinkedQueue;\n"
+ "import java.util.concurrent.Executors;\n" + "import java.nio.file.CopyOption;\n"
+ "import java.nio.file.Files;\n" + "import java.nio.file.Path;\n"
+ "import java.nio.file.StandardCopyOption;\n"
+ "import java.util.concurrent.atomic.AtomicInteger;");
// Print out the static, single-threaded portion
gw.println("public class Grader\n" + "{\n"
+ "AtomicInteger counter = new AtomicInteger(0);\n"
+ "public Grader(String root, int threads)\n" + "{\n"
+ "Checks.exec = Executors.newFixedThreadPool(2 * threads + 2);\n"
+ "Checks.tmArr = new Timer[threads];\n" + "Timer[] tmArr = Checks.tmArr;\n"
+ "for (int j = 0; j < tmArr.length; j++)\n" + "tmArr[j] = new Timer(true);\n"
+ "File rootDir = new File(root);\n"
+ "ConcurrentLinkedQueue<File> uniDirs = new ConcurrentLinkedQueue<File>();\n"
+ "for (File f : rootDir.listFiles())\n" + getValidDirectories(answerList) + "\n"
+ "uniDirs.add(f);\n" + "Thread[] workers = new Thread[threads];\n"
+ "for (int i = 0; i < threads; i++) {\n"
+ "workers[i] = new Thread(new GraderWorker(uniDirs, i));\n" + "workers[i].start();\n"
+ "}\n" + "for (Thread worker : workers)\n" + "try {\n" + "worker.join();\n"
+ "} catch (InterruptedException e) {\n" + "e.printStackTrace();\n" + "}\n"
+ "Checks.exec.shutdown();\n" + "}");
// Print out the main method
gw.println("public static void main(String[] args)\n" + "{\n" + "new Grader(\"./\", "
+ threads + ");\n" + "}");
// Print out the folder delete method
gw.println("private void deleteFolder(File source)\n" + "{\n"
+ "File[] contents = source.listFiles();\n" + "for (File f : contents) {\n"
+ "if (f.getName().equals(\".\") || f.getName().equals(\"..\"))\n" + "continue;\n"
+ "if (f.isDirectory())\n" + "deleteFolder(f);\n" + "else\n" + "f.delete();\n" + "}\n"
+ "source.delete();\n" + "}");
// Print out the symlink method
gw.println("public void symlink(File src, File dest, Checks check)\n" + "{\n"
+ "File[] srcFiles = src.listFiles();\n" + "for (File f : srcFiles) {\n"
+ "if (f.getName().equals(dest.getName()) || f.getName().equals(\"Makefile\"))\n"
+ "continue;\n" + "check.jockeyCommand(dest, \"ln -s ../\" + f.getName(), null);\n"
+ "}\n" + "}");
// Print out the copy folder method
gw.println("public void copyFiles(File src, File dest)\n" + "{\n" + "Path from;\n"
+ "Path to;\n" + "CopyOption[] options =\n"
+ "new CopyOption[] {StandardCopyOption.REPLACE_EXISTING,\n"
+ "StandardCopyOption.COPY_ATTRIBUTES};\n" + "File[] srcFiles = src.listFiles();\n"
+ "for (File f : srcFiles) {\n"
+ "if (f.getName().equals(\".\") || f.getName().equals(\"..\")) {\n" + "continue;\n"
+ "} else if (f.isDirectory()) {\n" + "File newDir = new File(dest, f.getName());\n"
+ "newDir.mkdir();\n" + "copyFiles(f, newDir);\n" + "} else {\n"
+ "from = src.toPath();\n" + "to = new File(dest, f.getName()).toPath();\n" + "try {\n"
+ "Files.copy(from, to, options);\n" + "} catch (IOException e) {\n"
+ "e.printStackTrace();\n" + "}\n" + "}\n" + "}\n" + "}");
// Now for GraderWorker
gw.println("class GraderWorker implements Runnable\n"
+ "{\n"
+ "PrintStream out;\n"
+ "PrintStream err;\n"
+ "int number;\n"
+ "ConcurrentLinkedQueue<File> uniDirs;\n"
+ "public GraderWorker(ConcurrentLinkedQueue<File> queue, int number)\n"
+ "{\n"
+ "uniDirs = queue;\n"
+ "this.number = number;\n"
+ "}\n"
+ "@Override\n"
+ "public void run()\n"
+ "{\n"
+ "File student = null;\n"
+ "while ((student = uniDirs.poll()) != null) {\n"
+ "Checks check = null;\n"
+ "System.out.println(\"Grader \" + number + \": Verifying \" + student.getName() + \"...\");\n"
+ "File results = new File(student, \"GRADE_RESULTS.txt\");\n" + "try {\n"
+ "if (results.isFile())\n" + "results.delete();\n" + "results.createNewFile();\n"
+ "check = new Checks(results, number);\n" + "} catch (IOException e) {\n"
+ "System.err.println(\"Unable to redirect output to file\");\n"
+ "e.printStackTrace();\n" + "}\n"
+ "File summary = new File(student, \"SUMMARY.txt\");\n" + "try {\n"
+ "if (summary.isFile())\n" + "summary.delete();\n" + "summary.createNewFile();\n"
+ "FileOutputStream summaryStream = new FileOutputStream(summary);\n"
+ "out = new PrintStream(summaryStream);\n" + "err = new PrintStream(summaryStream);\n"
+ "} catch (IOException e) {\n"
+ "System.err.println(\"Unable to redirect output to file.\");\n"
+ "e.printStackTrace();\n" + "}");
// Checking git commits
if (checkGit) {
gw.println("boolean goodCommit = check.checkGitCommits(student);\n"
+ "if (goodCommit)\n" + "out.println(student.getName() + \" GIT+\");\n" + "else\n"
+ "err.println(student.getName() + \" GIT-\");");
}
// Set any persistent variables
gw.println("File partDir;");
gw.println("File partDep;");
gw.println("boolean[] badProgram;");
gw.println("boolean cleanWorked;");
gw.println("boolean goodMake;");
// For each part...
int partNum = 1;
String exec;
for (LinkedHashMap<String, String> answer : answerList) {
exec = answer.get("exec");
// Set the current part directory to here
gw.println("partDir = new File(student, \"part" + partNum + "\");");
// Inidicate that we're checking this part
gw.println("check.printMessage(\"\\n" + answer.get("exec") + " verification:\", 1);");
// Pre build script
String script = answer.get("script-before-building");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
// Build any dependencies before hand
String dep = answer.get("dependencies");
if (!dep.isEmpty()) {
gw.println("check.printMessage(\"===Building dependencies for part" + partNum
+ "===\", 1);");
String[] depArr = dep.split(",");
for (String partDep : depArr) {
int num = Integer.parseInt(partDep.trim());
gw.println("partDep = new File(student, \"part" + num + "\");");
gw.println("check.checkMake(partDep, \"" + answerList.get(num - 1).get("exec")
+ "\");");
}
gw.println("check.printMessage(\"===Dependencies built===\", 1);");
}
// Build
gw.println("goodMake = check.checkMake(partDir, \"" + exec + "\");\n"
+ "if (goodMake)\n" + "out.println(student.getName() + \" " + exec
+ ": make+\");\n" + "else\n" + "err.println(student.getName() + \" " + exec
+ ": make-\");");
// Post build script
script = answer.get("script-after-building");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
// Run tests
String args = answer.get("args");
if (args.isEmpty()) {
gw.println(buildCommand(exec, "", answer.get("input-file"), answer.get("limit"))
+ "\n" + "if (badProgram[0])\n" + "err.println(student.getName() + \" " + exec
+ ": memory error-\");\n" + "else\n" + "out.println(student.getName() + \" "
+ exec + ": memory error+\");\n" + "if (badProgram[1])\n"
+ "err.println(student.getName() + \" " + exec + ": leak error-\");\n"
+ "else\n" + "out.println(student.getName() + \" " + exec + ": leak error+\");");
script = answer.get("script-during-run");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
} else {
String[] argsArr = args.split("\\|\\|");
int run = 0;
for (String arg : argsArr) {
gw.println("out.println(\"Test " + (run++) + ":\");");
gw.println(buildCommand(exec, arg, answer.get("input-file"),
answer.get("limit"))
+ "\n"
+ "if (badProgram[0])\n"
+ "err.println(student.getName() + \" "
+ exec
+ ": memory error-\");\n"
+ "else\n"
+ "out.println(student.getName() + \" "
+ exec
+ ": memory error+\");\n"
+ "if (badProgram[1])\n"
+ "err.println(student.getName() + \" "
+ exec
+ ": leak error-\");\n"
+ "else\n"
+ "out.println(student.getName() + \" "
+ exec + ": leak error+\");");
script = answer.get("script-during-run");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
}
}
// Additional drivers
if (answer.get("driver-dir") != null)
runDrivers(gw, answer);
// Post run script
script = answer.get("script-after-run");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
// Clean up
gw.println("cleanWorked = check.checkMakeClean(partDir, \"" + exec + "\");\n"
+ "if (cleanWorked)\n" + "out.println(student.getName() + \" " + exec
+ ": make clean+\");\n" + "else\n" + "err.println(student.getName() + \" " + exec
+ ": make clean-\");");
// Post clean script
script = answer.get("script-after-cleaning");
if (script != null && !script.isEmpty()) {
gw.println("runCommand(partDir, \"" + script + "\", null, 0);");
}
partNum++;
}
// Announce that we're done
gw.println("check.shutdown();\n"
+ "System.out.println(\"Grader \" + number + \": done with \"+student.getName()+\".\");");
// The final brackets
gw.println("}\n}\n}\n}");
// Done
gw.close();
}
|
diff --git a/org.caleydo.core/src/org/caleydo/core/io/gui/dataimport/DataImportStatusDialog.java b/org.caleydo.core/src/org/caleydo/core/io/gui/dataimport/DataImportStatusDialog.java
index 4c7acca5d..c3d5af1b3 100644
--- a/org.caleydo.core/src/org/caleydo/core/io/gui/dataimport/DataImportStatusDialog.java
+++ b/org.caleydo.core/src/org/caleydo/core/io/gui/dataimport/DataImportStatusDialog.java
@@ -1,64 +1,68 @@
/*******************************************************************************
* Caleydo - Visualization for Molecular Biology - http://caleydo.org
* Copyright (c) The Caleydo Team. All rights reserved.
* Licensed under the new BSD license, available at http://caleydo.org/license
******************************************************************************/
package org.caleydo.core.io.gui.dataimport;
import java.util.ArrayList;
import java.util.List;
import org.caleydo.core.gui.util.AStatusDialog;
import org.caleydo.core.gui.util.FontUtil;
import org.caleydo.core.util.collection.Pair;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
/**
* @author Christian
*
*/
public class DataImportStatusDialog extends AStatusDialog {
private String fileName;
private List<Pair<String, String>> attributes = new ArrayList<>();
/**
* @param parentShell
*/
public DataImportStatusDialog(Shell parentShell, String title, String fileName) {
super(parentShell, title);
this.fileName = fileName;
}
public void addAttribute(String attribute, String value) {
attributes.add(Pair.make(attribute, value));
}
@Override
protected Control createDialogArea(Composite parent) {
Composite parentComposite = new Composite(parent, SWT.NONE);
parentComposite.setLayout(new GridLayout(2, false));
parentComposite.setLayoutData(new GridData(400, 200));
Label statusLabel = new Label(parentComposite, SWT.NONE | SWT.WRAP);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
gd.widthHint = 400;
statusLabel.setLayoutData(gd);
statusLabel.setText("The file " + fileName + " was imported successfully!");
for (Pair<String, String> attribute : attributes) {
- Label attributeLabel = new Label(parentComposite, SWT.NONE);
+ Label attributeLabel = new Label(parentComposite, SWT.NONE | SWT.WRAP);
+ gd = new GridData(SWT.FILL, SWT.FILL, false, false);
+ gd.widthHint = 320;
+ attributeLabel.setLayoutData(gd);
attributeLabel.setText(attribute.getFirst());
FontUtil.makeBold(attributeLabel);
- Label valueLabel = new Label(parentComposite, SWT.NONE);
+ Label valueLabel = new Label(parentComposite, SWT.RIGHT);
+ valueLabel.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
valueLabel.setText(attribute.getSecond());
}
return super.createDialogArea(parent);
}
}
| false | true | protected Control createDialogArea(Composite parent) {
Composite parentComposite = new Composite(parent, SWT.NONE);
parentComposite.setLayout(new GridLayout(2, false));
parentComposite.setLayoutData(new GridData(400, 200));
Label statusLabel = new Label(parentComposite, SWT.NONE | SWT.WRAP);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
gd.widthHint = 400;
statusLabel.setLayoutData(gd);
statusLabel.setText("The file " + fileName + " was imported successfully!");
for (Pair<String, String> attribute : attributes) {
Label attributeLabel = new Label(parentComposite, SWT.NONE);
attributeLabel.setText(attribute.getFirst());
FontUtil.makeBold(attributeLabel);
Label valueLabel = new Label(parentComposite, SWT.NONE);
valueLabel.setText(attribute.getSecond());
}
return super.createDialogArea(parent);
}
| protected Control createDialogArea(Composite parent) {
Composite parentComposite = new Composite(parent, SWT.NONE);
parentComposite.setLayout(new GridLayout(2, false));
parentComposite.setLayoutData(new GridData(400, 200));
Label statusLabel = new Label(parentComposite, SWT.NONE | SWT.WRAP);
GridData gd = new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1);
gd.widthHint = 400;
statusLabel.setLayoutData(gd);
statusLabel.setText("The file " + fileName + " was imported successfully!");
for (Pair<String, String> attribute : attributes) {
Label attributeLabel = new Label(parentComposite, SWT.NONE | SWT.WRAP);
gd = new GridData(SWT.FILL, SWT.FILL, false, false);
gd.widthHint = 320;
attributeLabel.setLayoutData(gd);
attributeLabel.setText(attribute.getFirst());
FontUtil.makeBold(attributeLabel);
Label valueLabel = new Label(parentComposite, SWT.RIGHT);
valueLabel.setLayoutData(new GridData(SWT.FILL, SWT.BOTTOM, true, false));
valueLabel.setText(attribute.getSecond());
}
return super.createDialogArea(parent);
}
|
diff --git a/src/CalculatorD/GUIOptions.java b/src/CalculatorD/GUIOptions.java
index 406b9a9..95fce6b 100755
--- a/src/CalculatorD/GUIOptions.java
+++ b/src/CalculatorD/GUIOptions.java
@@ -1,207 +1,207 @@
package CalculatorD;
import javax.swing.JTextField;
/**
* Represents a set of options for displaying the Calculator GUI.
* @author Dustin Leavins
*/
public class GUIOptions implements Cloneable{
/**
* Default font size of the display.
*/
public static final int DEFAULT_DISPLAY_FONT_SIZE = 40;
/**
* Default font size of every button.
*/
public static final int DEFAULT_BUTTON_FONT_SIZE = 24;
/**
* Minimum font size for display and buttons.
*/
public static final int MIN_FONT_SIZE = 8;
/**
* Maximum font size for display and Buttons;
*/
public static final int MAX_FONT_SIZE = 72;
/**
* Indicates that the decimal key on the keypad should be used for
* the delete button on the calculator.
*/
public static final boolean USE_DECIMAL_BUTTON_FOR_DELETE = true;
/**
* Indicates that the decimal key on the keypad should be used for
* the decimal button on the calculator; this is the
* behavior of the decimal key.
*/
public static final boolean USE_DECIMAL_BUTTON_FOR_DECIMAL = false;
/**
* Default horizontal alignment of display;
* Equals CENTER_HORIZONTAL_ALIGNMENT.
*/
public static final int DEFAULT_HORIZONTAL_ALIGNMENT = JTextField.CENTER;
/**
* Equals its JTextField equivalent: LEFT.
*/
public static final int LEFT_HORIZONTAL_ALIGNMENT = JTextField.LEFT;
/**
* Equals its JTextField equivalent: CENTER.
*/
public static final int CENTER_HORIZONTAL_ALIGNMENT = JTextField.CENTER;
/**
* Equals its JTextField equivalent: RIGHT.
*/
public static final int RIGHT_HORIZONTAL_ALIGNMENT = JTextField.RIGHT;
private int displayFontSize;
private boolean useDecimalButtonForDelete;
private int horizontalAlignment;
private int buttonFontSize;
/**
* Constructor.
* @param displayFontSize size of the font used to display
* the result of the current calculation
* @param buttonFontSize size of the font used by buttons
* @param horizontalAlignment alignment of the calculation display;
* use the constants provided in <code>GUIOptions</code>
* @param useDecimalButtonForDelete should the decimal key on the
* numpad be used as the delete key in the calculator?
*/
public GUIOptions(int displayFontSize,
int buttonFontSize,
int horizontalAlignment,
boolean useDecimalButtonForDelete) {
// Checking & setting displayFontSize
if (displayFontSize < MIN_FONT_SIZE) {
this.displayFontSize = MIN_FONT_SIZE;
}
else if (displayFontSize > MAX_FONT_SIZE) {
this.displayFontSize = MAX_FONT_SIZE;
}
else {
this.displayFontSize = displayFontSize;
}
// Checking & setting buttonFontSize
if (buttonFontSize < MIN_FONT_SIZE) {
this.buttonFontSize = MIN_FONT_SIZE;
}
else if (buttonFontSize > MAX_FONT_SIZE) {
this.buttonFontSize = MAX_FONT_SIZE;
}
else {
this.buttonFontSize = buttonFontSize;
}
// Checking & setting horizontalAlignment
if (horizontalAlignment == LEFT_HORIZONTAL_ALIGNMENT) {
- horizontalAlignment = LEFT_HORIZONTAL_ALIGNMENT;
+ this.horizontalAlignment = LEFT_HORIZONTAL_ALIGNMENT;
}
else if (horizontalAlignment == RIGHT_HORIZONTAL_ALIGNMENT) {
- horizontalAlignment = RIGHT_HORIZONTAL_ALIGNMENT;
+ this.horizontalAlignment = RIGHT_HORIZONTAL_ALIGNMENT;
}
else {
- horizontalAlignment = CENTER_HORIZONTAL_ALIGNMENT;
+ this.horizontalAlignment = CENTER_HORIZONTAL_ALIGNMENT;
}
// Setting useDecimalButtonForDelete
this.useDecimalButtonForDelete = useDecimalButtonForDelete;
}
/**
* Font size of display, as dictated by <code>this</code>.
* @return font size of display
*/
public int displayFontSize() {
return displayFontSize;
}
/**
* Decimal key setting, as dictated by <code>this</code>.
* @return <code>true</code> if the decimal key will be used for
* delete, <code>false</code> if it will be used as decimal
*/
public boolean useDecimalButtonForDelete() {
return useDecimalButtonForDelete;
}
/**
* Font size of buttons, as dictated by <code>this</code>.
* @return font size of buttons
*/
public int buttonFontSize() {
return buttonFontSize;
}
/**
* Returns the horizontal alignment of the display, as dictated
* by <code>this</code>.
* @return <code>LEFT_HORIZONTAL_ALIGNMENT</code>,
* <code>RIGHT_HORIZONTAL_ALIGNMENT</code>,
* or <code>CENTER_HORIZONTAL_ALIGNMENT </code> depending on alignment
*/
public int horizontalAlignment() {
return horizontalAlignment;
}
/**
* Returns a <code>GUIOptions</code> object loaded with default
* options.
* <p>Default options:</p>
* <table>
* <tr>
* <td>Display Font Size</td>
* <td>40</td>
* </tr>
* <tr>
* <td>Button Font Size</td>
* <td>24</td>
* </tr>
* <tr>
* <td>Horizontal Alignment</td>
* <td>Center</td>
* </tr>
* <tr>
* <td>Use Decimal Button For</td>
* <td>Decimal</td>
* </tr>
* </table>
* @return default <code>GUIOptions</code>
*/
public static GUIOptions defaultOptions() {
return new GUIOptions(DEFAULT_DISPLAY_FONT_SIZE,
DEFAULT_BUTTON_FONT_SIZE,
DEFAULT_HORIZONTAL_ALIGNMENT,
USE_DECIMAL_BUTTON_FOR_DECIMAL);
}
/**
* Overrides <code>Object</code>'s implementation of clone.
* @return clone object
*/
public Object clone(){
GUIOptions cloneOpt = new GUIOptions(this.displayFontSize,
this.buttonFontSize,
this.horizontalAlignment,
this.useDecimalButtonForDelete);
return (Object) cloneOpt;
}
}
| false | true | public GUIOptions(int displayFontSize,
int buttonFontSize,
int horizontalAlignment,
boolean useDecimalButtonForDelete) {
// Checking & setting displayFontSize
if (displayFontSize < MIN_FONT_SIZE) {
this.displayFontSize = MIN_FONT_SIZE;
}
else if (displayFontSize > MAX_FONT_SIZE) {
this.displayFontSize = MAX_FONT_SIZE;
}
else {
this.displayFontSize = displayFontSize;
}
// Checking & setting buttonFontSize
if (buttonFontSize < MIN_FONT_SIZE) {
this.buttonFontSize = MIN_FONT_SIZE;
}
else if (buttonFontSize > MAX_FONT_SIZE) {
this.buttonFontSize = MAX_FONT_SIZE;
}
else {
this.buttonFontSize = buttonFontSize;
}
// Checking & setting horizontalAlignment
if (horizontalAlignment == LEFT_HORIZONTAL_ALIGNMENT) {
horizontalAlignment = LEFT_HORIZONTAL_ALIGNMENT;
}
else if (horizontalAlignment == RIGHT_HORIZONTAL_ALIGNMENT) {
horizontalAlignment = RIGHT_HORIZONTAL_ALIGNMENT;
}
else {
horizontalAlignment = CENTER_HORIZONTAL_ALIGNMENT;
}
// Setting useDecimalButtonForDelete
this.useDecimalButtonForDelete = useDecimalButtonForDelete;
}
| public GUIOptions(int displayFontSize,
int buttonFontSize,
int horizontalAlignment,
boolean useDecimalButtonForDelete) {
// Checking & setting displayFontSize
if (displayFontSize < MIN_FONT_SIZE) {
this.displayFontSize = MIN_FONT_SIZE;
}
else if (displayFontSize > MAX_FONT_SIZE) {
this.displayFontSize = MAX_FONT_SIZE;
}
else {
this.displayFontSize = displayFontSize;
}
// Checking & setting buttonFontSize
if (buttonFontSize < MIN_FONT_SIZE) {
this.buttonFontSize = MIN_FONT_SIZE;
}
else if (buttonFontSize > MAX_FONT_SIZE) {
this.buttonFontSize = MAX_FONT_SIZE;
}
else {
this.buttonFontSize = buttonFontSize;
}
// Checking & setting horizontalAlignment
if (horizontalAlignment == LEFT_HORIZONTAL_ALIGNMENT) {
this.horizontalAlignment = LEFT_HORIZONTAL_ALIGNMENT;
}
else if (horizontalAlignment == RIGHT_HORIZONTAL_ALIGNMENT) {
this.horizontalAlignment = RIGHT_HORIZONTAL_ALIGNMENT;
}
else {
this.horizontalAlignment = CENTER_HORIZONTAL_ALIGNMENT;
}
// Setting useDecimalButtonForDelete
this.useDecimalButtonForDelete = useDecimalButtonForDelete;
}
|
diff --git a/src/DVN-ingest/src/edu/harvard/iq/dvn/ingest/org/thedata/statdataio/metadata/DDIWriter.java b/src/DVN-ingest/src/edu/harvard/iq/dvn/ingest/org/thedata/statdataio/metadata/DDIWriter.java
index a26493ca..777cc891 100644
--- a/src/DVN-ingest/src/edu/harvard/iq/dvn/ingest/org/thedata/statdataio/metadata/DDIWriter.java
+++ b/src/DVN-ingest/src/edu/harvard/iq/dvn/ingest/org/thedata/statdataio/metadata/DDIWriter.java
@@ -1,420 +1,420 @@
/*
* Dataverse Network - A web application to distribute, share and
* analyze quantitative data.
* Copyright (C) 2009
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses
* or write to the Free Software Foundation,Inc., 51 Franklin Street,
* Fifth Floor, Boston, MA 02110-1301 USA
*/
package edu.harvard.iq.dvn.ingest.org.thedata.statdataio.metadata;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
/**
* A writer that renders a <code>SDIOMetadata</code> object in
* <a href="http://www.ddialliance.org/">Data Documentation Initiative
* </a>(DDI) format.
*
* @author Akio Sone at UNC-Odum
*/
public class DDIWriter {
/**
* A <code>SDIOMetadata</code> object to be rendered in DDI format
*
*/
protected SDIOMetadata sdioMetadata;
/**
* The default missing value string ('\u002E').
*/
public String MISSING_VALUE_TOKEN =".";
/**
* The missing value (Long.MAX_VALUE) for a discrete variable
* as <code>String</code>
*/
public String MISSING_VALUE_DISCRETE ="9223372036854775807";
/**
* Sets the value of MISSING_VALUE_TOKEN
* @param userDefinedMissingValue user-selected missing value
*/
public void setMISSING_VALUE_TOKEN(String userDefinedMissingValue) {
this.MISSING_VALUE_TOKEN = userDefinedMissingValue;
}
static {
}
/**
* Constructs a DDIWriter instance with the given <code>SDIOMetadata</code> object.
*
* @param sdioMetadata
*/
public DDIWriter(SDIOMetadata sdioMetadata) {
this.sdioMetadata = sdioMetadata;
// init();
}
/**
* Renders the given <code>SDIOMetadata</code> object as a <code>String</code>
* according to the DDI specification 2.0.
*
* @return an XML representation of the <code>SDIOMetadata</code> object.
*/
public String generateDDI(){
StringBuilder sb = new StringBuilder();
sb.append(generateDDISection1());
//sb.append(generateDDISection2());
sb.append(generateDDISection3());
sb.append(generateDDISection4());
return sb.toString();
}
private String generateDDISection1(){
String defaultEncoding = "UTF-8";
String fileEncoding = (String)sdioMetadata.fileInformation.get("charset");
if(sdioMetadata.fileInformation.get("charset")== null){
fileEncoding ="";
}
String encoding_attr = !fileEncoding.equals("") ?
" encoding=\""+fileEncoding+"\"" :
" encoding=\""+defaultEncoding+"\"";
StringBuilder sb =
new StringBuilder( "<?xml version=\"1.0\"" + encoding_attr +"?>\n");
sb.append("<codeBook xmlns=\"http://www.icpsr.umich.edu/DDI\">\n");
return sb.toString();
}
private String generateDDISection2(){
StringBuilder sb = new StringBuilder(
"<docDscr/>\n"+
"<stdyDscr>\n\t<citation>\n\t\t<titlStmt>\n"+
"\t\t\t<titl/>\n\t\t\t<IDNo agency=\"\"/>\n\t\t</titlStmt>\n"+
"\t</citation>\n</stdyDscr>\n");
return sb.toString();
}
private String generateDDISection3(){
String charset = (String)sdioMetadata.fileInformation.get("charset");
String nobs = sdioMetadata.fileInformation.get("caseQnty").toString();
String nvar = sdioMetadata.fileInformation.get("varQnty").toString();
String mimeType = (String)sdioMetadata.fileInformation.get("mimeType");
//System.out.println("charset="+charset);
//System.out.println("nobs="+nobs);
//System.out.println("nvar="+nvar);
//System.out.println("mimeType="+mimeType);
//String recPrCas = (String)getFileInformation().get("recPrCas");
//String fileType = (String)getFileInformation().get("fileType");
//String fileFormat = (String)getFileInformation().get("fileFormat");
String recPrCasTag = "";
String fileFormatTag ="";
String fileUNF = (String)sdioMetadata.getFileInformation().get("fileUNF");
//System.out.println("fileUNF="+fileUNF);
String fileNoteUNF =
"\t<notes subject=\"Universal Numeric Fingerprint\" level=\"file\" "+
"source=\"archive\" type=\"VDC:UNF\">" + fileUNF + "</notes>\n";
String fileNoteFileType =
"\t<notes subject=\"original file format\" level=\"file\" "+
"source=\"archive\" type=\"VDC:MIME\">" + mimeType + "</notes>\n";
StringBuilder sb =
new StringBuilder("<fileDscr ID=\"file1\" URI=\"\">\n" + "\t<fileTxt>\n"+
"\t\t<dimensns>\n\t\t\t<caseQnty>"+nobs+"</caseQnty>\n"+
"\t\t\t<varQnty>" + nvar +"</varQnty>\n"+
recPrCasTag + "\t\t</dimensns>\n"+
"\t\t<fileType charset=\""+ charset + "\">" + mimeType +"</fileType>\n"+
fileFormatTag+"\t</fileTxt>\n"+
fileNoteUNF+ fileNoteFileType+"</fileDscr>\n");
return sb.toString();
}
private String generateDDISection4(){
// String[] variableName
// String[] variableLabel
//
String varFormatSchema = (String)sdioMetadata.fileInformation.get("varFormat_schema");
String[] sumStatLabels8 =
{"mean", "medn", "mode", "vald", "invd", "min", "max", "stdev"};
StringBuilder sb = new StringBuilder("<dataDscr>\n");
String[] sumStatLabels3 = {"vald", "invd", "mode"};
boolean hasCaseWeightVariable = false;
int caseWeightVariableIndex = 0;
String wgtVarAttr = null;
if ((sdioMetadata.caseWeightVariableName != null) &&
(!sdioMetadata.caseWeightVariableName.equals(""))){
hasCaseWeightVariable = true;
for (int iw = 0; iw < sdioMetadata.variableName.length; iw++){
if (sdioMetadata.variableName[iw].equals(sdioMetadata.caseWeightVariableName)){
caseWeightVariableIndex = iw;
}
}
wgtVarAttr = "wgt-var=\"v1."+ (caseWeightVariableIndex+1) +"\" ";
} else {
wgtVarAttr="";
}
String uncessaryZeros = "([\\+\\-]?[0-9]+)(\\.0*$)";
Pattern pattern = Pattern.compile(uncessaryZeros);
for (int i=0; i<sdioMetadata.variableName.length;i++){
// prepare catStat
String variableNamei = sdioMetadata.variableName[i];
String valueLabelTableName = sdioMetadata.valueLabelMappingTable.get(variableNamei);
// valuLabeli, catStati, missingValuei
List<CategoricalStatistic> mergedCatStatTable =
MetadataHelper.getMergedResult(
sdioMetadata.valueLabelTable.get(valueLabelTableName),
sdioMetadata.categoryStatisticsTable.get(variableNamei),
sdioMetadata.missingValueTable.get(variableNamei)
);
// <var tag
String intrvlType = sdioMetadata.isContinuousVariable()[i]
? "contin": "discrete" ;
String intrvlAttr = "intrvl=\""+intrvlType + "\" " ;
String weightAttr = null;
if (hasCaseWeightVariable) {
if (i == caseWeightVariableIndex){
// weight variable's token
weightAttr = "wgt=\"wgt\" ";
} else {
// non-weight variable's token
weightAttr = wgtVarAttr;
}
} else {
weightAttr = "";
}
String ultimateVariableName = getUtimateVariableName(sdioMetadata.variableName[i]);
sb.append("\t<var ID=\"v1." + (i+1) + "\" name=\"" +
StringEscapeUtils.escapeXml(ultimateVariableName) + "\" "+
intrvlAttr + weightAttr+">\n"); // id counter starst from 1 not 0
sb.append("\t\t<location fileid=\"file1\"/>\n");
// label
if ((sdioMetadata.variableLabel.containsKey(sdioMetadata.variableName[i])) &&
(!sdioMetadata.variableLabel.get(sdioMetadata.variableName[i]).equals(""))) {
sb.append("\t\t<labl level=\"variable\">" +
StringEscapeUtils.escapeXml(
sdioMetadata.variableLabel.get(sdioMetadata.variableName[i]))+"</labl>\n");
}
if((sdioMetadata.invalidDataTable !=null) &&
(sdioMetadata.invalidDataTable.containsKey(sdioMetadata.variableName[i]))){
sb.append(sdioMetadata.invalidDataTable.get(sdioMetadata.variableName[i]).toDDItag());
}
// summaryStatistics
Object[] sumStat = sdioMetadata.summaryStatisticsTable.get(i);
if (sumStat.length == 3){
for (int j=0; j<sumStat.length;j++){
String statistic = (sumStat[j].toString()).equals("NaN")
|| (sumStat[j].toString()).equals("")
- ? MISSING_VALUE_TOKEN : sumStat[j].toString();
+ ? MISSING_VALUE_TOKEN : StringEscapeUtils.escapeXml(sumStat[j].toString());
// sb.append("\t\t<sumStat type=\""+
// sumStatLabels3[j]+"\">"+statistic+"</sumStat>\n");
String wholePart = null;
Matcher matcher = pattern.matcher(statistic);
if (matcher.find()){
wholePart = matcher.group(1);
} else{
wholePart = statistic;
}
sb.append("\t\t<sumStat type=\""+
sumStatLabels3[j]+"\">"+wholePart+"</sumStat>\n");
}
} else if (sumStat.length== 8) {
for (int j=0; j<sumStat.length;j++){
// if (!sdioMetadata.isContinuousVariable()[i]){
// if ((j == 0)|| (j== 7)) {
// continue;
// }
// }
String statistic = (sumStat[j].toString()).equals("NaN")
|| (sumStat[j].toString()).equals("")
? MISSING_VALUE_TOKEN : sumStat[j].toString();
if (!sdioMetadata.isContinuousVariable()[i]){
// discrete case: remove the decimal point
// and the trailing zero(s)
if ((j != 0) && (j!=7)){
String wholePart = null;
Matcher matcher = pattern.matcher(statistic);
if (matcher.find()){
wholePart = matcher.group(1);
} else{
wholePart = statistic;
}
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+wholePart+"</sumStat>\n");
} else {
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+statistic+"</sumStat>\n");
}
} else {
// valid/invalid are integers
if ((j == 3) || (j == 4)){
String wholePart = null;
Matcher matcher = pattern.matcher(statistic);
if (matcher.find()){
wholePart = matcher.group(1);
} else{
wholePart = statistic;
}
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+wholePart+"</sumStat>\n");
} else {
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+statistic+"</sumStat>\n");
}
}
}
}
// cat stat
/*
<catgry missing="N">
<catValu>2</catValu>
<labl level="category">JA,NEBEN 2</labl>
<catStat type="freq">16</catStat>
</catgry>
*/
if ((mergedCatStatTable != null) && (!mergedCatStatTable.isEmpty())){
for (CategoricalStatistic cs: mergedCatStatTable){
// first line
if (cs.isMissingValue() ||
cs.getValue().equals(MISSING_VALUE_DISCRETE) ||
cs.getValue().equals(MISSING_VALUE_TOKEN) ||
cs.getValue().equals("")){
sb.append("\t\t<catgry missing=\"Y\">\n");
} else {
sb.append("\t\t<catgry>\n");
}
// value
String catStatValueString = null;
if (cs.getValue().equals(MISSING_VALUE_DISCRETE)
|| cs.getValue().equals(MISSING_VALUE_TOKEN)
|| cs.getValue().equals("")
){
catStatValueString=MISSING_VALUE_TOKEN;
} else {
catStatValueString= StringEscapeUtils.escapeXml(cs.getValue());
}
sb.append("\t\t\t<catValu>"+catStatValueString+"</catValu>\n");
// label
if ((cs.getLabel()!=null) && (!cs.getLabel().equals(""))){
sb.append("\t\t\t<labl level=\"category\">"+
StringEscapeUtils.escapeXml(cs.getLabel())+"</labl>\n");
}
// frequency
sb.append("\t\t\t<catStat type=\"freq\">"+cs.getFrequency()+"</catStat>\n");
sb.append("\t\t</catgry>\n");
}
}
//System.out.println(StringUtils.join(sumStat,","));
// format
String formatTye = sdioMetadata.isStringVariable()[i] ? "character" : "numeric";
String formatName = null;
String formatCategory = null;
String formatSchema = null;
if ((sdioMetadata.variableFormatName.containsKey(variableNamei)) &&
( (sdioMetadata.variableFormatName.get(variableNamei)!=null)
&& (!sdioMetadata.variableFormatName.get(variableNamei).equals("")))){
formatSchema = "schema=\""+varFormatSchema+"\" ";
formatName= "formatname=\""+sdioMetadata.variableFormatName.get(variableNamei) +"\" ";
formatCategory = "category=\""+sdioMetadata.variableFormatCategory.get(variableNamei) +"\"";
} else {
formatSchema="";
formatName="";
formatCategory ="";
}
sb.append("\t\t<varFormat type=\""+formatTye+"\" "+formatSchema+ formatName+formatCategory+"/>\n");
// note: UNF
sb.append("\t\t<notes subject=\"Universal Numeric Fingerprint\" "+
"level=\"variable\" source=\"archive\" type=\"VDC:UNF\">"+
StringEscapeUtils.escapeXml(sdioMetadata.variableUNF[i])
+"</notes>\n");
// closing
sb.append("\t</var>\n");
}
sb.append("</dataDscr>\n");
sb.append("</codeBook>\n");
return sb.toString();
}
private String getUtimateVariableName(String variableName){
String ultimateVariableName = null;
if ((sdioMetadata.shortToLongVarialbeNameTable != null) &&
(sdioMetadata.shortToLongVarialbeNameTable.containsKey(variableName))){
if((sdioMetadata.shortToLongVarialbeNameTable.get(variableName) !=null) &&
(!sdioMetadata.shortToLongVarialbeNameTable.get(variableName).equals(""))) {
ultimateVariableName = sdioMetadata.shortToLongVarialbeNameTable.get(variableName);
} else {
ultimateVariableName = variableName;
}
} else {
ultimateVariableName = variableName;
}
return ultimateVariableName;
}
}
| true | true | private String generateDDISection4(){
// String[] variableName
// String[] variableLabel
//
String varFormatSchema = (String)sdioMetadata.fileInformation.get("varFormat_schema");
String[] sumStatLabels8 =
{"mean", "medn", "mode", "vald", "invd", "min", "max", "stdev"};
StringBuilder sb = new StringBuilder("<dataDscr>\n");
String[] sumStatLabels3 = {"vald", "invd", "mode"};
boolean hasCaseWeightVariable = false;
int caseWeightVariableIndex = 0;
String wgtVarAttr = null;
if ((sdioMetadata.caseWeightVariableName != null) &&
(!sdioMetadata.caseWeightVariableName.equals(""))){
hasCaseWeightVariable = true;
for (int iw = 0; iw < sdioMetadata.variableName.length; iw++){
if (sdioMetadata.variableName[iw].equals(sdioMetadata.caseWeightVariableName)){
caseWeightVariableIndex = iw;
}
}
wgtVarAttr = "wgt-var=\"v1."+ (caseWeightVariableIndex+1) +"\" ";
} else {
wgtVarAttr="";
}
String uncessaryZeros = "([\\+\\-]?[0-9]+)(\\.0*$)";
Pattern pattern = Pattern.compile(uncessaryZeros);
for (int i=0; i<sdioMetadata.variableName.length;i++){
// prepare catStat
String variableNamei = sdioMetadata.variableName[i];
String valueLabelTableName = sdioMetadata.valueLabelMappingTable.get(variableNamei);
// valuLabeli, catStati, missingValuei
List<CategoricalStatistic> mergedCatStatTable =
MetadataHelper.getMergedResult(
sdioMetadata.valueLabelTable.get(valueLabelTableName),
sdioMetadata.categoryStatisticsTable.get(variableNamei),
sdioMetadata.missingValueTable.get(variableNamei)
);
// <var tag
String intrvlType = sdioMetadata.isContinuousVariable()[i]
? "contin": "discrete" ;
String intrvlAttr = "intrvl=\""+intrvlType + "\" " ;
String weightAttr = null;
if (hasCaseWeightVariable) {
if (i == caseWeightVariableIndex){
// weight variable's token
weightAttr = "wgt=\"wgt\" ";
} else {
// non-weight variable's token
weightAttr = wgtVarAttr;
}
} else {
weightAttr = "";
}
String ultimateVariableName = getUtimateVariableName(sdioMetadata.variableName[i]);
sb.append("\t<var ID=\"v1." + (i+1) + "\" name=\"" +
StringEscapeUtils.escapeXml(ultimateVariableName) + "\" "+
intrvlAttr + weightAttr+">\n"); // id counter starst from 1 not 0
sb.append("\t\t<location fileid=\"file1\"/>\n");
// label
if ((sdioMetadata.variableLabel.containsKey(sdioMetadata.variableName[i])) &&
(!sdioMetadata.variableLabel.get(sdioMetadata.variableName[i]).equals(""))) {
sb.append("\t\t<labl level=\"variable\">" +
StringEscapeUtils.escapeXml(
sdioMetadata.variableLabel.get(sdioMetadata.variableName[i]))+"</labl>\n");
}
if((sdioMetadata.invalidDataTable !=null) &&
(sdioMetadata.invalidDataTable.containsKey(sdioMetadata.variableName[i]))){
sb.append(sdioMetadata.invalidDataTable.get(sdioMetadata.variableName[i]).toDDItag());
}
// summaryStatistics
Object[] sumStat = sdioMetadata.summaryStatisticsTable.get(i);
if (sumStat.length == 3){
for (int j=0; j<sumStat.length;j++){
String statistic = (sumStat[j].toString()).equals("NaN")
|| (sumStat[j].toString()).equals("")
? MISSING_VALUE_TOKEN : sumStat[j].toString();
// sb.append("\t\t<sumStat type=\""+
// sumStatLabels3[j]+"\">"+statistic+"</sumStat>\n");
String wholePart = null;
Matcher matcher = pattern.matcher(statistic);
if (matcher.find()){
wholePart = matcher.group(1);
} else{
wholePart = statistic;
}
sb.append("\t\t<sumStat type=\""+
sumStatLabels3[j]+"\">"+wholePart+"</sumStat>\n");
}
} else if (sumStat.length== 8) {
for (int j=0; j<sumStat.length;j++){
// if (!sdioMetadata.isContinuousVariable()[i]){
// if ((j == 0)|| (j== 7)) {
// continue;
// }
// }
String statistic = (sumStat[j].toString()).equals("NaN")
|| (sumStat[j].toString()).equals("")
? MISSING_VALUE_TOKEN : sumStat[j].toString();
if (!sdioMetadata.isContinuousVariable()[i]){
// discrete case: remove the decimal point
// and the trailing zero(s)
if ((j != 0) && (j!=7)){
String wholePart = null;
Matcher matcher = pattern.matcher(statistic);
if (matcher.find()){
wholePart = matcher.group(1);
} else{
wholePart = statistic;
}
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+wholePart+"</sumStat>\n");
} else {
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+statistic+"</sumStat>\n");
}
} else {
// valid/invalid are integers
if ((j == 3) || (j == 4)){
String wholePart = null;
Matcher matcher = pattern.matcher(statistic);
if (matcher.find()){
wholePart = matcher.group(1);
} else{
wholePart = statistic;
}
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+wholePart+"</sumStat>\n");
} else {
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+statistic+"</sumStat>\n");
}
}
}
}
// cat stat
/*
<catgry missing="N">
<catValu>2</catValu>
<labl level="category">JA,NEBEN 2</labl>
<catStat type="freq">16</catStat>
</catgry>
*/
if ((mergedCatStatTable != null) && (!mergedCatStatTable.isEmpty())){
for (CategoricalStatistic cs: mergedCatStatTable){
// first line
if (cs.isMissingValue() ||
cs.getValue().equals(MISSING_VALUE_DISCRETE) ||
cs.getValue().equals(MISSING_VALUE_TOKEN) ||
cs.getValue().equals("")){
sb.append("\t\t<catgry missing=\"Y\">\n");
} else {
sb.append("\t\t<catgry>\n");
}
// value
String catStatValueString = null;
if (cs.getValue().equals(MISSING_VALUE_DISCRETE)
|| cs.getValue().equals(MISSING_VALUE_TOKEN)
|| cs.getValue().equals("")
){
catStatValueString=MISSING_VALUE_TOKEN;
} else {
catStatValueString= StringEscapeUtils.escapeXml(cs.getValue());
}
sb.append("\t\t\t<catValu>"+catStatValueString+"</catValu>\n");
// label
if ((cs.getLabel()!=null) && (!cs.getLabel().equals(""))){
sb.append("\t\t\t<labl level=\"category\">"+
StringEscapeUtils.escapeXml(cs.getLabel())+"</labl>\n");
}
// frequency
sb.append("\t\t\t<catStat type=\"freq\">"+cs.getFrequency()+"</catStat>\n");
sb.append("\t\t</catgry>\n");
}
}
//System.out.println(StringUtils.join(sumStat,","));
// format
String formatTye = sdioMetadata.isStringVariable()[i] ? "character" : "numeric";
String formatName = null;
String formatCategory = null;
String formatSchema = null;
if ((sdioMetadata.variableFormatName.containsKey(variableNamei)) &&
( (sdioMetadata.variableFormatName.get(variableNamei)!=null)
&& (!sdioMetadata.variableFormatName.get(variableNamei).equals("")))){
formatSchema = "schema=\""+varFormatSchema+"\" ";
formatName= "formatname=\""+sdioMetadata.variableFormatName.get(variableNamei) +"\" ";
formatCategory = "category=\""+sdioMetadata.variableFormatCategory.get(variableNamei) +"\"";
} else {
formatSchema="";
formatName="";
formatCategory ="";
}
sb.append("\t\t<varFormat type=\""+formatTye+"\" "+formatSchema+ formatName+formatCategory+"/>\n");
// note: UNF
sb.append("\t\t<notes subject=\"Universal Numeric Fingerprint\" "+
"level=\"variable\" source=\"archive\" type=\"VDC:UNF\">"+
StringEscapeUtils.escapeXml(sdioMetadata.variableUNF[i])
+"</notes>\n");
// closing
sb.append("\t</var>\n");
}
sb.append("</dataDscr>\n");
sb.append("</codeBook>\n");
return sb.toString();
}
| private String generateDDISection4(){
// String[] variableName
// String[] variableLabel
//
String varFormatSchema = (String)sdioMetadata.fileInformation.get("varFormat_schema");
String[] sumStatLabels8 =
{"mean", "medn", "mode", "vald", "invd", "min", "max", "stdev"};
StringBuilder sb = new StringBuilder("<dataDscr>\n");
String[] sumStatLabels3 = {"vald", "invd", "mode"};
boolean hasCaseWeightVariable = false;
int caseWeightVariableIndex = 0;
String wgtVarAttr = null;
if ((sdioMetadata.caseWeightVariableName != null) &&
(!sdioMetadata.caseWeightVariableName.equals(""))){
hasCaseWeightVariable = true;
for (int iw = 0; iw < sdioMetadata.variableName.length; iw++){
if (sdioMetadata.variableName[iw].equals(sdioMetadata.caseWeightVariableName)){
caseWeightVariableIndex = iw;
}
}
wgtVarAttr = "wgt-var=\"v1."+ (caseWeightVariableIndex+1) +"\" ";
} else {
wgtVarAttr="";
}
String uncessaryZeros = "([\\+\\-]?[0-9]+)(\\.0*$)";
Pattern pattern = Pattern.compile(uncessaryZeros);
for (int i=0; i<sdioMetadata.variableName.length;i++){
// prepare catStat
String variableNamei = sdioMetadata.variableName[i];
String valueLabelTableName = sdioMetadata.valueLabelMappingTable.get(variableNamei);
// valuLabeli, catStati, missingValuei
List<CategoricalStatistic> mergedCatStatTable =
MetadataHelper.getMergedResult(
sdioMetadata.valueLabelTable.get(valueLabelTableName),
sdioMetadata.categoryStatisticsTable.get(variableNamei),
sdioMetadata.missingValueTable.get(variableNamei)
);
// <var tag
String intrvlType = sdioMetadata.isContinuousVariable()[i]
? "contin": "discrete" ;
String intrvlAttr = "intrvl=\""+intrvlType + "\" " ;
String weightAttr = null;
if (hasCaseWeightVariable) {
if (i == caseWeightVariableIndex){
// weight variable's token
weightAttr = "wgt=\"wgt\" ";
} else {
// non-weight variable's token
weightAttr = wgtVarAttr;
}
} else {
weightAttr = "";
}
String ultimateVariableName = getUtimateVariableName(sdioMetadata.variableName[i]);
sb.append("\t<var ID=\"v1." + (i+1) + "\" name=\"" +
StringEscapeUtils.escapeXml(ultimateVariableName) + "\" "+
intrvlAttr + weightAttr+">\n"); // id counter starst from 1 not 0
sb.append("\t\t<location fileid=\"file1\"/>\n");
// label
if ((sdioMetadata.variableLabel.containsKey(sdioMetadata.variableName[i])) &&
(!sdioMetadata.variableLabel.get(sdioMetadata.variableName[i]).equals(""))) {
sb.append("\t\t<labl level=\"variable\">" +
StringEscapeUtils.escapeXml(
sdioMetadata.variableLabel.get(sdioMetadata.variableName[i]))+"</labl>\n");
}
if((sdioMetadata.invalidDataTable !=null) &&
(sdioMetadata.invalidDataTable.containsKey(sdioMetadata.variableName[i]))){
sb.append(sdioMetadata.invalidDataTable.get(sdioMetadata.variableName[i]).toDDItag());
}
// summaryStatistics
Object[] sumStat = sdioMetadata.summaryStatisticsTable.get(i);
if (sumStat.length == 3){
for (int j=0; j<sumStat.length;j++){
String statistic = (sumStat[j].toString()).equals("NaN")
|| (sumStat[j].toString()).equals("")
? MISSING_VALUE_TOKEN : StringEscapeUtils.escapeXml(sumStat[j].toString());
// sb.append("\t\t<sumStat type=\""+
// sumStatLabels3[j]+"\">"+statistic+"</sumStat>\n");
String wholePart = null;
Matcher matcher = pattern.matcher(statistic);
if (matcher.find()){
wholePart = matcher.group(1);
} else{
wholePart = statistic;
}
sb.append("\t\t<sumStat type=\""+
sumStatLabels3[j]+"\">"+wholePart+"</sumStat>\n");
}
} else if (sumStat.length== 8) {
for (int j=0; j<sumStat.length;j++){
// if (!sdioMetadata.isContinuousVariable()[i]){
// if ((j == 0)|| (j== 7)) {
// continue;
// }
// }
String statistic = (sumStat[j].toString()).equals("NaN")
|| (sumStat[j].toString()).equals("")
? MISSING_VALUE_TOKEN : sumStat[j].toString();
if (!sdioMetadata.isContinuousVariable()[i]){
// discrete case: remove the decimal point
// and the trailing zero(s)
if ((j != 0) && (j!=7)){
String wholePart = null;
Matcher matcher = pattern.matcher(statistic);
if (matcher.find()){
wholePart = matcher.group(1);
} else{
wholePart = statistic;
}
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+wholePart+"</sumStat>\n");
} else {
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+statistic+"</sumStat>\n");
}
} else {
// valid/invalid are integers
if ((j == 3) || (j == 4)){
String wholePart = null;
Matcher matcher = pattern.matcher(statistic);
if (matcher.find()){
wholePart = matcher.group(1);
} else{
wholePart = statistic;
}
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+wholePart+"</sumStat>\n");
} else {
sb.append("\t\t<sumStat type=\""+
sumStatLabels8[j]+"\">"+statistic+"</sumStat>\n");
}
}
}
}
// cat stat
/*
<catgry missing="N">
<catValu>2</catValu>
<labl level="category">JA,NEBEN 2</labl>
<catStat type="freq">16</catStat>
</catgry>
*/
if ((mergedCatStatTable != null) && (!mergedCatStatTable.isEmpty())){
for (CategoricalStatistic cs: mergedCatStatTable){
// first line
if (cs.isMissingValue() ||
cs.getValue().equals(MISSING_VALUE_DISCRETE) ||
cs.getValue().equals(MISSING_VALUE_TOKEN) ||
cs.getValue().equals("")){
sb.append("\t\t<catgry missing=\"Y\">\n");
} else {
sb.append("\t\t<catgry>\n");
}
// value
String catStatValueString = null;
if (cs.getValue().equals(MISSING_VALUE_DISCRETE)
|| cs.getValue().equals(MISSING_VALUE_TOKEN)
|| cs.getValue().equals("")
){
catStatValueString=MISSING_VALUE_TOKEN;
} else {
catStatValueString= StringEscapeUtils.escapeXml(cs.getValue());
}
sb.append("\t\t\t<catValu>"+catStatValueString+"</catValu>\n");
// label
if ((cs.getLabel()!=null) && (!cs.getLabel().equals(""))){
sb.append("\t\t\t<labl level=\"category\">"+
StringEscapeUtils.escapeXml(cs.getLabel())+"</labl>\n");
}
// frequency
sb.append("\t\t\t<catStat type=\"freq\">"+cs.getFrequency()+"</catStat>\n");
sb.append("\t\t</catgry>\n");
}
}
//System.out.println(StringUtils.join(sumStat,","));
// format
String formatTye = sdioMetadata.isStringVariable()[i] ? "character" : "numeric";
String formatName = null;
String formatCategory = null;
String formatSchema = null;
if ((sdioMetadata.variableFormatName.containsKey(variableNamei)) &&
( (sdioMetadata.variableFormatName.get(variableNamei)!=null)
&& (!sdioMetadata.variableFormatName.get(variableNamei).equals("")))){
formatSchema = "schema=\""+varFormatSchema+"\" ";
formatName= "formatname=\""+sdioMetadata.variableFormatName.get(variableNamei) +"\" ";
formatCategory = "category=\""+sdioMetadata.variableFormatCategory.get(variableNamei) +"\"";
} else {
formatSchema="";
formatName="";
formatCategory ="";
}
sb.append("\t\t<varFormat type=\""+formatTye+"\" "+formatSchema+ formatName+formatCategory+"/>\n");
// note: UNF
sb.append("\t\t<notes subject=\"Universal Numeric Fingerprint\" "+
"level=\"variable\" source=\"archive\" type=\"VDC:UNF\">"+
StringEscapeUtils.escapeXml(sdioMetadata.variableUNF[i])
+"</notes>\n");
// closing
sb.append("\t</var>\n");
}
sb.append("</dataDscr>\n");
sb.append("</codeBook>\n");
return sb.toString();
}
|
diff --git a/src/org/mozilla/javascript/NativeCall.java b/src/org/mozilla/javascript/NativeCall.java
index d0817072..b196ac3d 100644
--- a/src/org/mozilla/javascript/NativeCall.java
+++ b/src/org/mozilla/javascript/NativeCall.java
@@ -1,154 +1,154 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Bob Jervis
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
/**
* This class implements the activation object.
*
* See ECMA 10.1.6
*
* @see org.mozilla.javascript.Arguments
* @author Norris Boyd
*/
public final class NativeCall extends IdScriptableObject
{
static final long serialVersionUID = -7471457301304454454L;
private static final Object CALL_TAG = new Object();
static void init(Scriptable scope, boolean sealed)
{
NativeCall obj = new NativeCall();
obj.exportAsJSClass(MAX_PROTOTYPE_ID, scope, sealed);
}
NativeCall() { }
NativeCall(NativeFunction function, Scriptable scope, Object[] args)
{
this.function = function;
setParentScope(scope);
// leave prototype null
this.originalArgs = (args == null) ? ScriptRuntime.emptyArgs : args;
// initialize values of arguments
int paramAndVarCount = function.getParamAndVarCount();
int paramCount = function.getParamCount();
if (paramAndVarCount != 0) {
for (int i = 0; i < paramCount; ++i) {
String name = function.getParamOrVarName(i);
Object val = i < args.length ? args[i]
: Undefined.instance;
defineProperty(name, val, PERMANENT);
}
}
- // initialize "arguments" property but only if it was not overriden by
+ // initialize "arguments" property but only if it was not overridden by
// the parameter with the same name
if (!super.has("arguments", this)) {
defineProperty("arguments", new Arguments(this), PERMANENT);
}
if (paramAndVarCount != 0) {
for (int i = paramCount; i < paramAndVarCount; ++i) {
String name = function.getParamOrVarName(i);
if (!super.has(name, this)) {
if (function.getParamOrVarConst(i))
defineProperty(name, Undefined.instance, CONST);
else
defineProperty(name, Undefined.instance, PERMANENT);
}
}
}
}
public String getClassName()
{
return "Call";
}
protected int findPrototypeId(String s)
{
return s.equals("constructor") ? Id_constructor : 0;
}
protected void initPrototypeId(int id)
{
String s;
int arity;
if (id == Id_constructor) {
arity=1; s="constructor";
} else {
throw new IllegalArgumentException(String.valueOf(id));
}
initPrototypeMethod(CALL_TAG, id, s, arity);
}
public Object execIdCall(IdFunctionObject f, Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (!f.hasTag(CALL_TAG)) {
return super.execIdCall(f, cx, scope, thisObj, args);
}
int id = f.methodId();
if (id == Id_constructor) {
if (thisObj != null) {
throw Context.reportRuntimeError1("msg.only.from.new", "Call");
}
ScriptRuntime.checkDeprecated(cx, "Call");
NativeCall result = new NativeCall();
result.setPrototype(getObjectPrototype(scope));
return result;
}
throw new IllegalArgumentException(String.valueOf(id));
}
private static final int
Id_constructor = 1,
MAX_PROTOTYPE_ID = 1;
NativeFunction function;
Object[] originalArgs;
transient NativeCall parentActivationCall;
}
| true | true | NativeCall(NativeFunction function, Scriptable scope, Object[] args)
{
this.function = function;
setParentScope(scope);
// leave prototype null
this.originalArgs = (args == null) ? ScriptRuntime.emptyArgs : args;
// initialize values of arguments
int paramAndVarCount = function.getParamAndVarCount();
int paramCount = function.getParamCount();
if (paramAndVarCount != 0) {
for (int i = 0; i < paramCount; ++i) {
String name = function.getParamOrVarName(i);
Object val = i < args.length ? args[i]
: Undefined.instance;
defineProperty(name, val, PERMANENT);
}
}
// initialize "arguments" property but only if it was not overriden by
// the parameter with the same name
if (!super.has("arguments", this)) {
defineProperty("arguments", new Arguments(this), PERMANENT);
}
if (paramAndVarCount != 0) {
for (int i = paramCount; i < paramAndVarCount; ++i) {
String name = function.getParamOrVarName(i);
if (!super.has(name, this)) {
if (function.getParamOrVarConst(i))
defineProperty(name, Undefined.instance, CONST);
else
defineProperty(name, Undefined.instance, PERMANENT);
}
}
}
}
| NativeCall(NativeFunction function, Scriptable scope, Object[] args)
{
this.function = function;
setParentScope(scope);
// leave prototype null
this.originalArgs = (args == null) ? ScriptRuntime.emptyArgs : args;
// initialize values of arguments
int paramAndVarCount = function.getParamAndVarCount();
int paramCount = function.getParamCount();
if (paramAndVarCount != 0) {
for (int i = 0; i < paramCount; ++i) {
String name = function.getParamOrVarName(i);
Object val = i < args.length ? args[i]
: Undefined.instance;
defineProperty(name, val, PERMANENT);
}
}
// initialize "arguments" property but only if it was not overridden by
// the parameter with the same name
if (!super.has("arguments", this)) {
defineProperty("arguments", new Arguments(this), PERMANENT);
}
if (paramAndVarCount != 0) {
for (int i = paramCount; i < paramAndVarCount; ++i) {
String name = function.getParamOrVarName(i);
if (!super.has(name, this)) {
if (function.getParamOrVarConst(i))
defineProperty(name, Undefined.instance, CONST);
else
defineProperty(name, Undefined.instance, PERMANENT);
}
}
}
}
|
diff --git a/OntoUrlFetcher/src/application/UrlFetcher.java b/OntoUrlFetcher/src/application/UrlFetcher.java
index 64253a3..bcf6a6c 100644
--- a/OntoUrlFetcher/src/application/UrlFetcher.java
+++ b/OntoUrlFetcher/src/application/UrlFetcher.java
@@ -1,101 +1,101 @@
package application;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Calendar;
import org.apache.solr.client.solrj.SolrServerException;
public class UrlFetcher {
/**
* @param args
*/
public static void main(String[] args) {
long sTime = System.currentTimeMillis();
System.out.println("OntoStarUrlFetcher started");
File stopFile = new File(Configuration.stopFile);
File stoppedFile = new File(Configuration.stoppedFile);
File runFile = new File(Configuration.runFile);
UrlMySQLInterface db = UrlMySQLInterface.getinstance();
SolrQueryMaker solr = SolrQueryMaker.getInstance();
System.out.println("Fetching URLs starting from "
+ solr.getSolrStringDate(solr.getDateInMillis()) + ".");
boolean upToDate = false;
long lastDate = solr.getDateInMillis();
if (lastDate >= System.currentTimeMillis()) {
upToDate = true;
}
while (!stopFile.exists() && !upToDate) {
System.out.println("========================= Time: " + getTimestamp(lastDate));
try {
db.insertUrls(solr.getNextUrls());
}
catch (SolrServerException e) {
e.printStackTrace();
}
lastDate = solr.getDateInMillis();
if (lastDate >= System.currentTimeMillis()) {
upToDate = true;
}
}
try {
if (upToDate) {
System.out.println("Fetching done.");
}
else {
System.out.println("Received stop command.");
}
+ db.closeConnection();
if (!runFile.exists()) {
runFile.createNewFile();
}
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(runFile)));
writer.println(SolrQueryMaker.getInstance().getDateInMillis());
writer.close();
- db.closeConnection();
stoppedFile.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Something went wrong during the creation of command files.");
}
catch (SQLException e) {
System.out.println("Cannot close connection.");
e.printStackTrace();
}
System.out.println("OntoStarUrlFetcher stopped.");
long eTime = System.currentTimeMillis();
System.out.println("All done in " + (((double) eTime) - sTime) / 1000 + " seconds.");
sTime = UrlMySQLInterface.sTime;
eTime = UrlMySQLInterface.eTime;
System.out.println("Time to insert URLs: " + (((double) eTime) - sTime) / 1000
+ " seconds.");
System.err.println("\n============================================\nEnd: " + getTimestamp()
+ "\n============================================\n");
}
public static String getTimestamp() {
return getTimestamp(Calendar.getInstance().getTimeInMillis());
}
public static String getTimestamp(long timeInMillis) {
String timestamp = String.format("%tA %tF h%tR", timeInMillis, timeInMillis, timeInMillis);
return timestamp;
}
}
| false | true | public static void main(String[] args) {
long sTime = System.currentTimeMillis();
System.out.println("OntoStarUrlFetcher started");
File stopFile = new File(Configuration.stopFile);
File stoppedFile = new File(Configuration.stoppedFile);
File runFile = new File(Configuration.runFile);
UrlMySQLInterface db = UrlMySQLInterface.getinstance();
SolrQueryMaker solr = SolrQueryMaker.getInstance();
System.out.println("Fetching URLs starting from "
+ solr.getSolrStringDate(solr.getDateInMillis()) + ".");
boolean upToDate = false;
long lastDate = solr.getDateInMillis();
if (lastDate >= System.currentTimeMillis()) {
upToDate = true;
}
while (!stopFile.exists() && !upToDate) {
System.out.println("========================= Time: " + getTimestamp(lastDate));
try {
db.insertUrls(solr.getNextUrls());
}
catch (SolrServerException e) {
e.printStackTrace();
}
lastDate = solr.getDateInMillis();
if (lastDate >= System.currentTimeMillis()) {
upToDate = true;
}
}
try {
if (upToDate) {
System.out.println("Fetching done.");
}
else {
System.out.println("Received stop command.");
}
if (!runFile.exists()) {
runFile.createNewFile();
}
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(runFile)));
writer.println(SolrQueryMaker.getInstance().getDateInMillis());
writer.close();
db.closeConnection();
stoppedFile.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Something went wrong during the creation of command files.");
}
catch (SQLException e) {
System.out.println("Cannot close connection.");
e.printStackTrace();
}
System.out.println("OntoStarUrlFetcher stopped.");
long eTime = System.currentTimeMillis();
System.out.println("All done in " + (((double) eTime) - sTime) / 1000 + " seconds.");
sTime = UrlMySQLInterface.sTime;
eTime = UrlMySQLInterface.eTime;
System.out.println("Time to insert URLs: " + (((double) eTime) - sTime) / 1000
+ " seconds.");
System.err.println("\n============================================\nEnd: " + getTimestamp()
+ "\n============================================\n");
}
| public static void main(String[] args) {
long sTime = System.currentTimeMillis();
System.out.println("OntoStarUrlFetcher started");
File stopFile = new File(Configuration.stopFile);
File stoppedFile = new File(Configuration.stoppedFile);
File runFile = new File(Configuration.runFile);
UrlMySQLInterface db = UrlMySQLInterface.getinstance();
SolrQueryMaker solr = SolrQueryMaker.getInstance();
System.out.println("Fetching URLs starting from "
+ solr.getSolrStringDate(solr.getDateInMillis()) + ".");
boolean upToDate = false;
long lastDate = solr.getDateInMillis();
if (lastDate >= System.currentTimeMillis()) {
upToDate = true;
}
while (!stopFile.exists() && !upToDate) {
System.out.println("========================= Time: " + getTimestamp(lastDate));
try {
db.insertUrls(solr.getNextUrls());
}
catch (SolrServerException e) {
e.printStackTrace();
}
lastDate = solr.getDateInMillis();
if (lastDate >= System.currentTimeMillis()) {
upToDate = true;
}
}
try {
if (upToDate) {
System.out.println("Fetching done.");
}
else {
System.out.println("Received stop command.");
}
db.closeConnection();
if (!runFile.exists()) {
runFile.createNewFile();
}
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(runFile)));
writer.println(SolrQueryMaker.getInstance().getDateInMillis());
writer.close();
stoppedFile.createNewFile();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Something went wrong during the creation of command files.");
}
catch (SQLException e) {
System.out.println("Cannot close connection.");
e.printStackTrace();
}
System.out.println("OntoStarUrlFetcher stopped.");
long eTime = System.currentTimeMillis();
System.out.println("All done in " + (((double) eTime) - sTime) / 1000 + " seconds.");
sTime = UrlMySQLInterface.sTime;
eTime = UrlMySQLInterface.eTime;
System.out.println("Time to insert URLs: " + (((double) eTime) - sTime) / 1000
+ " seconds.");
System.err.println("\n============================================\nEnd: " + getTimestamp()
+ "\n============================================\n");
}
|
diff --git a/vaadin-touchkit-agpl/src/main/java/com/vaadin/addon/touchkit/ui/VerticalComponentGroup.java b/vaadin-touchkit-agpl/src/main/java/com/vaadin/addon/touchkit/ui/VerticalComponentGroup.java
index e27f323..a765972 100644
--- a/vaadin-touchkit-agpl/src/main/java/com/vaadin/addon/touchkit/ui/VerticalComponentGroup.java
+++ b/vaadin-touchkit-agpl/src/main/java/com/vaadin/addon/touchkit/ui/VerticalComponentGroup.java
@@ -1,104 +1,104 @@
package com.vaadin.addon.touchkit.ui;
import java.util.Iterator;
import java.util.LinkedList;
import com.vaadin.addon.touchkit.gwt.client.vaadincomm.VerticalComponentGroupState;
import com.vaadin.ui.AbstractLayout;
import com.vaadin.ui.Component;
/**
* A layout to group controls vertically. Items in a
* {@link VerticalComponentGroup} have by default white background, margins and
* rounded corners.
* <p>
* Captions are rendered on the same row as the component. Relative widths are
* relative to the {@link VerticalComponentGroup} width except if the component
* has a caption, in which case a relative width is relative to the remaining
* available space.
* <p>
* Due to the styling, {@link VerticalComponentGroup} is by default more
* flexible than {@link HorizontalButtonGroup} and it can accommodate many
* components.
*/
@SuppressWarnings("serial")
public class VerticalComponentGroup extends AbstractLayout {
protected LinkedList<Component> components = new LinkedList<Component>();
/**
* Creates a vertical component group.
* <p>
* The default width is 100%.
*/
public VerticalComponentGroup() {
this(null);
}
/**
* Creates a vertical component group that is 100% wide.
*/
public VerticalComponentGroup(String caption) {
getState().caption = caption;
setWidth(null);
}
protected VerticalComponentGroupState getState() {
return (VerticalComponentGroupState) super.getState();
}
@Override
public void addComponent(Component component) {
addComponent(component, -1);
}
public void addComponent (Component component, int index) {
if (components.contains(component)) {
if (components.indexOf(component) != index) {
components.remove(component);
- if (index < components.size()) {
+ if (index >= 0 && index < components.size()) {
components.add(index, component);
} else {
components.add(component);
}
markAsDirty();
}
} else {
if (index >= 0 && index < components.size()) {
components.add(index, component);
} else {
components.add(component);
}
super.addComponent(component);
markAsDirty();
}
}
@Override
public void replaceComponent(Component oldComponent, Component newComponent) {
int index = components.indexOf(oldComponent);
removeComponent(oldComponent);
addComponent(newComponent, index);
}
@Override
public void removeComponent(Component component) {
if (components.contains(component)) {
components.remove(component);
super.removeComponent(component);
markAsDirty();
}
}
@Override
public int getComponentCount() {
return components.size();
}
@Override
@Deprecated
public Iterator<Component> getComponentIterator() {
return components.iterator();
}
}
| true | true | public void addComponent (Component component, int index) {
if (components.contains(component)) {
if (components.indexOf(component) != index) {
components.remove(component);
if (index < components.size()) {
components.add(index, component);
} else {
components.add(component);
}
markAsDirty();
}
} else {
if (index >= 0 && index < components.size()) {
components.add(index, component);
} else {
components.add(component);
}
super.addComponent(component);
markAsDirty();
}
}
| public void addComponent (Component component, int index) {
if (components.contains(component)) {
if (components.indexOf(component) != index) {
components.remove(component);
if (index >= 0 && index < components.size()) {
components.add(index, component);
} else {
components.add(component);
}
markAsDirty();
}
} else {
if (index >= 0 && index < components.size()) {
components.add(index, component);
} else {
components.add(component);
}
super.addComponent(component);
markAsDirty();
}
}
|
diff --git a/src/com/redhat/qe/auto/testng/TestNGUtils.java b/src/com/redhat/qe/auto/testng/TestNGUtils.java
index 43d6b05..aede0b3 100644
--- a/src/com/redhat/qe/auto/testng/TestNGUtils.java
+++ b/src/com/redhat/qe/auto/testng/TestNGUtils.java
@@ -1,24 +1,20 @@
package com.redhat.qe.auto.testng;
import java.util.List;
public class TestNGUtils {
public static Object[][] convertListOfListsTo2dArray(List<List<Object>> list) {
if (list.size() == 0) return new Object[0][0]; // avoid a null pointer exception
//convert list to 2-d array
- Object[][] array = new Object[list.size()][ list.get(0).size()];
+ Object[][] array = new Object[list.size()][];
int i=0;
for (List<Object> item: list){
- int j=0;
- for (Object param: item){
- array[i][j] = param;
- j++;
- }
+ array[i] = item.toArray();
i++;
}
return array;
}
}
| false | true | public static Object[][] convertListOfListsTo2dArray(List<List<Object>> list) {
if (list.size() == 0) return new Object[0][0]; // avoid a null pointer exception
//convert list to 2-d array
Object[][] array = new Object[list.size()][ list.get(0).size()];
int i=0;
for (List<Object> item: list){
int j=0;
for (Object param: item){
array[i][j] = param;
j++;
}
i++;
}
return array;
}
| public static Object[][] convertListOfListsTo2dArray(List<List<Object>> list) {
if (list.size() == 0) return new Object[0][0]; // avoid a null pointer exception
//convert list to 2-d array
Object[][] array = new Object[list.size()][];
int i=0;
for (List<Object> item: list){
array[i] = item.toArray();
i++;
}
return array;
}
|
diff --git a/src/com/ichi2/libanki/Sched.java b/src/com/ichi2/libanki/Sched.java
index a75b20a0..47cd4257 100644
--- a/src/com/ichi2/libanki/Sched.java
+++ b/src/com/ichi2/libanki/Sched.java
@@ -1,2691 +1,2691 @@
/****************************************************************************************
* 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 private 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 private License for more details. *
* *
* You should have received a copy of the GNU General private License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.libanki;
import com.ichi2.anki2.R;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteConstraintException;
import android.graphics.Typeface;
import android.text.SpannableStringBuilder;
import android.text.style.StyleSpan;
import android.util.Log;
import android.util.Pair;
import com.ichi2.anki.AnkiDroidApp;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.TreeSet;
public class Sched {
// whether new cards should be mixed with reviews, or shown first or last
public static final int NEW_CARDS_DISTRIBUTE = 0;
public static final int NEW_CARDS_LAST = 1;
public static final int NEW_CARDS_FIRST = 2;
// new card insertion order
public static final int NEW_CARDS_RANDOM = 0;
public static final int NEW_CARDS_DUE = 1;
// review card sort order
public static final int REV_CARDS_RANDOM = 0;
public static final int REV_CARDS_OLD_FIRST = 1;
public static final int REV_CARDS_NEW_FIRST = 2;
// removal types
public static final int REM_CARD = 0;
public static final int REM_NOTE = 1;
public static final int REM_DECK = 2;
// count display
public static final int COUNT_ANSWERED = 0;
public static final int COUNT_REMAINING = 1;
// media log
public static final int MEDIA_ADD = 0;
public static final int MEDIA_REM = 1;
// dynamic deck order
public static final int DYN_OLDEST = 0;
public static final int DYN_RANDOM = 1;
public static final int DYN_SMALLINT = 2;
public static final int DYN_BIGINT = 3;
public static final int DYN_LAPSES = 4;
public static final int DYN_ADDED = 5;
public static final int DYN_DUE = 6;
// model types
public static final int MODEL_STD = 0;
public static final int MODEL_CLOZE = 1;
private static final String[] REV_ORDER_STRINGS = { "ivl DESC", "ivl" };
private static final int[] FACTOR_ADDITION_VALUES = { -150, 0, 150 };
// not in libanki
public static final int DECK_INFORMATION_NAMES = 0;
public static final int DECK_INFORMATION_SIMPLE_COUNTS = 1;
public static final int DECK_INFORMATION_EXTENDED_COUNTS = 2;
private Collection mCol;
private String mName = "std";
private int mQueueLimit;
private int mReportLimit;
private int mReps;
private boolean mHaveQueues;
private int mToday;
public long mDayCutoff;
private int mNewCount;
private int mLrnCount;
private int mRevCount;
private int mNewCardModulus;
private double[] mEtaCache = new double[] { -1, -1, -1, -1 };
// Queues
private LinkedList<long[]> mNewQueue;
private LinkedList<long[]> mLrnQueue;
private LinkedList<long[]> mLrnDayQueue;
private LinkedList<long[]> mRevQueue;
private LinkedList<Long> mNewDids;
private LinkedList<Long> mLrnDids;
private LinkedList<Long> mRevDids;
private TreeMap<Integer, Integer> mGroupConfs;
private TreeMap<Integer, JSONObject> mConfCache;
private HashMap<Long, Pair<String[], long[]>> mCachedDeckCounts;
/**
* queue types: 0=new/cram, 1=lrn, 2=rev, 3=day lrn, -1=suspended, -2=buried revlog types: 0=lrn, 1=rev, 2=relrn,
* 3=cram positive intervals are in positive revlog intervals are in days (rev), negative in seconds (lrn)
*/
public Sched(Collection col) {
mCol = col;
mQueueLimit = 50;
mReportLimit = 1000;
mReps = 0;
mHaveQueues = false;
_updateCutoff();
// Initialise queues
mNewQueue = new LinkedList<long[]>();
mLrnQueue = new LinkedList<long[]>();
mLrnDayQueue = new LinkedList<long[]>();
mRevQueue = new LinkedList<long[]>();
}
/**
* Pop the next card from the queue. None if finished.
*/
public Card getCard() {
_checkDay();
if (!mHaveQueues) {
reset();
}
Card card = _getCard();
if (card != null) {
mReps += 1;
card.startTimer();
}
return card;
}
/* NOT IN LIBANKI */
public void decrementCounts(Card card) {
int type = card.getQueue();
switch (type) {
case 0:
mNewCount--;
break;
case 1:
mLrnCount -= card.getLeft() / 1000;
break;
case 2:
mRevCount--;
break;
case 3:
mLrnCount--;
break;
}
}
public void reset() {
_updateCutoff();
_resetLrn();
_resetRev();
_resetNew();
mHaveQueues = true;
}
public boolean answerCard(Card card, int ease) {
Log.i(AnkiDroidApp.TAG, "answerCard - ease:" + ease);
boolean isLeech = false;
mCol.markUndo(Collection.UNDO_REVIEW, new Object[]{card});
card.setReps(card.getReps() + 1);
boolean wasNew = (card.getQueue() == 0);
if (wasNew) {
// came from the new queue, move to learning
card.setQueue(1);
// if it was a new card, it's now a learning card
if (card.getType() == 0) {
card.setType(1);
}
// init reps to graduation
card.setLeft(_startingLeft(card));
// dynamic?
if (card.getODid() != 0 && card.getType() == 2) {
if (_resched(card)) {
// reviews get their ivl boosted on first sight
card.setIvl(_dynIvlBoost(card));
card.setODue(mToday + card.getIvl());
}
}
_updateStats(card, "new");
}
if (card.getQueue() == 1 || card.getQueue() == 3) {
_answerLrnCard(card, ease);
if (!wasNew) {
_updateStats(card, "lrn");
}
} else if (card.getQueue() == 2) {
isLeech = _answerRevCard(card, ease);
_updateStats(card, "rev");
} else {
throw new RuntimeException("Invalid queue");
}
_updateStats(card, "time", card.timeTaken());
card.setMod(Utils.intNow());
card.setUsn(mCol.usn());
card.flushSched();
return isLeech;
}
public int[] counts() {
return counts(null);
}
public int[] counts(Card card) {
int[] counts = new int[3];
counts[0] = mNewCount;
counts[1] = mLrnCount;
counts[2] = mRevCount;
if (card != null) {
int idx = countIdx(card);
if (idx == 1) {
counts[1] += card.getLeft() / 1000;
} else {
counts[idx] += 1;
}
}
return counts;
}
/**
* Return counts over next DAYS. Includes today.
*/
public int dueForecast() {
return dueForecast(7);
}
public int dueForecast(int days) {
// TODO:...
return 0;
}
public int countIdx(Card card) {
if (card.getQueue() == 3) {
return 1;
}
return card.getQueue();
}
public int answerButtons(Card card) {
if (card.getODue() != 0) {
// normal review in dyn deck?
if (card.getODid() != 0 && card.getQueue() == 2) {
return 4;
}
JSONObject conf = _lapseConf(card);
try {
if (conf.getJSONArray("delays").length() > 1) {
return 3;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return 2;
} else if (card.getQueue() == 2) {
return 4;
} else {
return 3;
}
}
/**
* Unbury cards when closing.
*/
public void onClose() {
mCol.getDb().execute("UPDATE cards SET queue = type WHERE queue = -2");
}
// /**
// * A very rough estimate of time to review.
// */
// public int eta() {
// Cursor cur = null;
// int cnt = 0;
// int sum = 0;
// try {
// cur = mDb.getDatabase().rawQuery(
// "SELECT count(), sum(taken) FROM (SELECT * FROM revlog " +
// "ORDER BY time DESC LIMIT 10)", null);
// if (cur.moveToFirst()) {
// cnt = cur.getInt(0);
// sum = cur.getInt(1);
// }
// } finally {
// if (cur != null && !cur.isClosed()) {
// cur.close();
// }
// }
// if (cnt == 0) {
// return 0;
// }
// double avg = sum / ((float) cnt);
// int[] c = counts();
// return (int) ((avg * c[0] * 3 + avg * c[1] * 3 + avg * c[2]) / 1000.0);
// }
/**
* Rev/lrn/time daily stats *************************************************
* **********************************************
*/
private void _updateStats(Card card, String type) {
_updateStats(card, type, 1);
}
public void _updateStats(Card card, String type, int cnt) {
String key = type + "Today";
long did = card.getDid();
ArrayList<JSONObject> list = mCol.getDecks().parents(did);
list.add(mCol.getDecks().get(did));
for (JSONObject g : list) {
try {
JSONArray a = g.getJSONArray(key);
// add
a.put(1, a.getInt(1) + cnt);
} catch (JSONException e) {
throw new RuntimeException(e);
}
mCol.getDecks().save(g);
}
}
private void extendLimits(int newc, int rev) {
JSONObject cur = mCol.getDecks().current();
ArrayList<JSONObject> decks = new ArrayList<JSONObject>();
decks.add(cur);
try {
decks.addAll(mCol.getDecks().parents(cur.getLong("id")));
for (long did : mCol.getDecks().children(cur.getLong("id")).values()) {
decks.add(mCol.getDecks().get(did));
}
for (JSONObject g : decks) {
// add
JSONArray ja = g.getJSONArray("newToday");
ja.put(1, ja.getInt(1) - newc);
g.put("newToday", ja);
ja = g.getJSONArray("revToday");
ja.put(1, ja.getInt(1) - rev);
g.put("revToday", ja);
mCol.getDecks().save(g);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private int _walkingCount() {
return _walkingCount(null, null, null);
}
private int _walkingCount(LinkedList<Long> dids) {
return _walkingCount(dids, null, null);
}
private int _walkingCount(Method limFn, Method cntFn) {
return _walkingCount(null, limFn, cntFn);
}
private int _walkingCount(LinkedList<Long> dids, Method limFn, Method cntFn) {
if (dids == null) {
dids = mCol.getDecks().active();
}
int tot = 0;
HashMap<Long, Integer> pcounts = new HashMap<Long, Integer>();
// for each of the active decks
try {
for (long did : dids) {
// get the individual deck's limit
int lim = 0;
// if (limFn != null) {
lim = (Integer) limFn.invoke(Sched.this, mCol.getDecks().get(did));
// }
if (lim == 0) {
continue;
}
// check the parents
ArrayList<JSONObject> parents = mCol.getDecks().parents(did);
for (JSONObject p : parents) {
// add if missing
long id = p.getLong("id");
if (!pcounts.containsKey(id)) {
pcounts.put(id, (Integer) limFn.invoke(Sched.this, p));
}
// take minimum of child and parent
lim = Math.min(pcounts.get(id), lim);
}
// see how many cards we actually have
int cnt = 0;
// if (cntFn != null) {
cnt = (Integer) cntFn.invoke(Sched.this, did, lim);
// }
// if non-zero, decrement from parents counts
for (JSONObject p : parents) {
long id = p.getLong("id");
pcounts.put(id, pcounts.get(id) - cnt);
}
// we may also be a parent
pcounts.put(did, lim - cnt);
// and add to running total
tot += cnt;
}
} catch (JSONException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return tot;
}
/**
* Deck list **************************************************************** *******************************
*/
/** LIBANKI: not in libanki */
public Object[] deckCounts() {
TreeSet<Object[]> decks = deckDueTree(0);
int[] counts = new int[] { 0, 0, 0 };
for (Object[] deck : decks) {
if (((String[]) deck[0]).length == 1) {
counts[0] += (Integer) deck[2];
counts[1] += (Integer) deck[3];
counts[2] += (Integer) deck[4];
}
}
return new Object[] { decks, eta(counts), mCol.cardCount() };
}
public class DeckDueListComparator implements Comparator<JSONObject> {
public int compare(JSONObject o1, JSONObject o2) {
try {
return o1.getString("name").compareTo(o2.getString("name"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
/**
* Returns [deckname, did, rev, lrn, new]
*/
public ArrayList<Object[]> deckDueList(int counts) {
_checkDay();
mCol.getDecks().recoverOrphans();
ArrayList<JSONObject> decks = mCol.getDecks().all();
Collections.sort(decks, new DeckDueListComparator());
HashMap<String, Integer[]> lims = new HashMap<String, Integer[]>();
ArrayList<Object[]> data = new ArrayList<Object[]>();
try {
for (JSONObject deck : decks) {
String p;
String[] parts = deck.getString("name").split("::");
if (parts.length < 2) {
p = "";
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.length - 1; i++) {
sb.append(parts[i]);
if (i < parts.length - 2) {
sb.append("::");
}
}
p = sb.toString();
}
// new
int nlim = _deckNewLimitSingle(deck);
if (p.length() > 0) {
nlim = Math.min(nlim, lims.get(p)[0]);
}
int newC = _newForDeck(deck.getLong("id"), nlim);
// learning
int lrn = _lrnForDeck(deck.getLong("id"));
// reviews
int rlim = _deckRevLimitSingle(deck);
if (p.length() > 0) {
rlim = Math.min(rlim, lims.get(p)[1]);
}
int rev = _revForDeck(deck.getLong("id"), rlim);
// save to list
// LIBANKI: order differs from libanki (here: new, lrn, rev)
data.add(new Object[]{deck.getString("name"), deck.getLong("id"), newC, lrn, rev});
// add deck as a parent
lims.put(deck.getString("name"), new Integer[]{nlim, rlim});
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return data;
}
public TreeSet<Object[]> deckDueTree(int counts) {
return _groupChildren(deckDueList(counts));
}
private TreeSet<Object[]> _groupChildren(ArrayList<Object[]> grps) {
TreeSet<Object[]> set = new TreeSet<Object[]>(new DeckNameCompare());
// first, split the group names into components
for (Object[] g : grps) {
set.add(new Object[] { ((String) g[0]).split("::"), g[1], g[2], g[3], g[4] });
}
return _groupChildrenMain(set);
}
private TreeSet<Object[]> _groupChildrenMain(TreeSet<Object[]> grps) {
return _groupChildrenMain(grps, 0);
}
private TreeSet<Object[]> _groupChildrenMain(TreeSet<Object[]> grps, int depth) {
TreeSet<Object[]> tree = new TreeSet<Object[]>(new DeckNameCompare());
// group and recurse
Iterator<Object[]> it = grps.iterator();
Object[] tmp = null;
while (tmp != null || it.hasNext()) {
Object[] head;
if (tmp != null) {
head = tmp;
tmp = null;
} else {
head = it.next();
}
String[] title = (String[]) head[0];
long did = (Long) head[1];
int newCount = (Integer) head[2];
int lrnCount = (Integer) head[3];
int revCount = (Integer) head[4];
TreeSet<Object[]> children = new TreeSet<Object[]>(new DeckNameCompare());
while (it.hasNext()) {
Object[] o = it.next();
if (((String[])o[0])[depth].equals(title[depth])) {
// add to children
children.add(o);
} else {
// proceed with this as head
tmp = o;
break;
}
}
children = _groupChildrenMain(children, depth + 1);
// tally up children counts
for (Object[] ch : children) {
newCount += (Integer)ch[2];
lrnCount += (Integer)ch[3];
revCount += (Integer)ch[4];
}
tree.add(new Object[] {title, did, newCount, lrnCount, revCount,
children});
}
TreeSet<Object[]> result = new TreeSet<Object[]>(new DeckNameCompare());
for (Object[] t : tree) {
result.add(new Object[]{t[0], t[1], t[2], t[3], t[4]});
result.addAll((TreeSet<Object[]>) t[5]);
}
return result;
}
/**
* Getting the next card ****************************************************
* *******************************************
*/
/**
* Return the next due card, or None.
*/
private Card _getCard() {
// learning card due?
Card c = _getLrnCard();
if (c != null) {
return c;
}
// new first, or time for one?
if (_timeForNewCard()) {
return _getNewCard();
}
// Card due for review?
c = _getRevCard();
if (c != null) {
return c;
}
// day learning card due?
c = _getLrnDayCard();
if (c != null) {
return c;
}
// New cards left?
c = _getNewCard();
if (c != null) {
return c;
}
// collapse or finish
return _getLrnCard(true);
}
//
// /** LIBANKI: not in libanki */
// public boolean removeCardFromQueues(Card card) {
// long id = card.getId();
// Iterator<long[]> i = mNewQueue.iterator();
// while (i.hasNext()) {
// long cid = i.next()[0];
// if (cid == id) {
// i.remove();
// mNewCount -= 1;
// return true;
// }
// }
// i = mLrnQueue.iterator();
// while (i.hasNext()) {
// long cid = i.next()[1];
// if (cid == id) {
// i.remove();
// mLrnCount -= card.getLeft();
// return true;
// }
// }
// i = mLrnDayQueue.iterator();
// while (i.hasNext()) {
// long cid = i.next()[1];
// if (cid == id) {
// i.remove();
// mLrnCount -= card.getLeft();
// return true;
// }
// }
// i = mRevQueue.iterator();
// while (i.hasNext()) {
// long cid = i.next()[0];
// if (cid == id) {
// i.remove();
// mRevCount -= 1;
// return true;
// }
// }
// return false;
// }
/**
* New cards **************************************************************** *******************************
*/
private void _resetNewCount() {
try {
mNewCount = _walkingCount(Sched.class.getDeclaredMethod("_deckNewLimitSingle", JSONObject.class),
Sched.class.getDeclaredMethod("_cntFnNew", long.class, int.class));
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private int _cntFnNew(long did, int lim) {
return mCol.getDb().queryScalar(
"SELECT count() FROM (SELECT 1 FROM cards WHERE did = " + did + " AND queue = 0 LIMIT " + lim + ")");
}
private void _resetNew() {
_resetNewCount();
mNewDids = new LinkedList<Long>(mCol.getDecks().active());
mNewQueue.clear();
_updateNewCardRatio();
}
private boolean _fillNew() {
if (mNewQueue.size() > 0) {
return true;
}
if (mNewCount == 0) {
return false;
}
while (!mNewDids.isEmpty()) {
long did = mNewDids.getFirst();
int lim = Math.min(mQueueLimit, _deckNewLimit(did));
mNewQueue.clear();
Cursor cur = null;
if (lim != 0) {
try {
cur = mCol
.getDb()
.getDatabase()
.rawQuery("SELECT id, due FROM cards WHERE did = " + did + " AND queue = 0 LIMIT " + lim,
null);
while (cur.moveToNext()) {
mNewQueue.add(new long[] { cur.getLong(0), cur.getLong(1) });
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
if (!mNewQueue.isEmpty()) {
return true;
}
}
// nothing left in the deck; move to next
mNewDids.remove();
}
return false;
}
private Card _getNewCard() {
if (!_fillNew()) {
return null;
}
long[] item = mNewQueue.remove();
// move any siblings to the end?
try {
JSONObject conf = mCol.getDecks().confForDid(mNewDids.getFirst());
if (conf.getInt("dyn") != 0 || conf.getJSONObject("new").getBoolean("separate")) {
int n = mNewQueue.size();
while (!mNewQueue.isEmpty() && mNewQueue.getFirst()[1] == item[1]) {
mNewQueue.add(mNewQueue.remove());
n -= 1;
if (n == 0) {
// we only have one fact in the queue; stop rotating
break;
}
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
mNewCount -= 1;
return mCol.getCard(item[0]);
}
private void _updateNewCardRatio() {
try {
if (mCol.getConf().getInt("newSpread") == NEW_CARDS_DISTRIBUTE) {
if (mNewCount != 0) {
mNewCardModulus = (mNewCount + mRevCount) / mNewCount;
// if there are cards to review, ensure modulo >= 2
if (mRevCount != 0) {
mNewCardModulus = Math.max(2, mNewCardModulus);
}
return;
}
}
mNewCardModulus = 0;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* @return True if it's time to display a new card when distributing.
*/
private boolean _timeForNewCard() {
if (mNewCount == 0) {
return false;
}
int spread;
try {
spread = mCol.getConf().getInt("newSpread");
} catch (JSONException e) {
throw new RuntimeException(e);
}
if (spread == NEW_CARDS_LAST) {
return false;
} else if (spread == NEW_CARDS_FIRST) {
return true;
} else if (mNewCardModulus != 0) {
return (mReps != 0 && (mReps % mNewCardModulus == 0));
} else {
return false;
}
}
private int _deckNewLimit(long did) {
return _deckNewLimit(did, null);
}
private int _deckNewLimit(long did, Method fn) {
try {
if (fn == null) {
fn = Sched.class.getDeclaredMethod("_deckNewLimitSingle", JSONObject.class);
}
ArrayList<JSONObject> decks = mCol.getDecks().parents(did);
decks.add(mCol.getDecks().get(did));
int lim = -1;
// for the deck and each of its parents
int rem = 0;
for (JSONObject g : decks) {
rem = (Integer) fn.invoke(Sched.this, g);
if (lim == -1) {
lim = rem;
} else {
lim = Math.min(rem, lim);
}
}
return lim;
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
/* New count for a single deck. */
public int _newForDeck(long did, int lim) {
if (lim == 0) {
return 0;
}
lim = Math.min(lim, mReportLimit);
return mCol.getDb().queryScalar("SELECT count() FROM (SELECT 1 FROM cards WHERE did = " + did + " AND queue = 0 LIMIT " + lim + ")", false);
}
/* Limit for deck without parent limits. */
public int _deckNewLimitSingle(JSONObject g) {
try {
if (g.getInt("dyn") != 0) {
return mReportLimit;
}
JSONObject c = mCol.getDecks().confForDid(g.getLong("id"));
return Math.max(0, c.getJSONObject("new").getInt("perDay") - g.getJSONArray("newToday").getInt(1));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* Learning queues *********************************************************** ************************************
*/
private void _resetLrnCount() {
mLrnCount = _cntFnLrn(_deckLimit());
// day
mLrnCount += (int) mCol.getDb().queryScalar(
"SELECT count() FROM cards WHERE did IN " + _deckLimit() + " AND queue = 3 AND due <= " + mToday
+ " LIMIT " + mReportLimit, false);
}
private int _cntFnLrn(String dids) {
return (int) mCol.getDb().queryScalar(
"SELECT sum(left / 1000) FROM (SELECT left FROM cards WHERE did IN " + dids
+ " AND queue = 1 AND due < " + mDayCutoff + " LIMIT " + mReportLimit + ")", false);
}
private void _resetLrn() {
_resetLrnCount();
mLrnQueue.clear();
mLrnDayQueue.clear();
mLrnDids = mCol.getDecks().active();
}
// sub-day learning
private boolean _fillLrn() {
if (mLrnCount == 0) {
return false;
}
if (!mLrnQueue.isEmpty()) {
return true;
}
Cursor cur = null;
mLrnQueue.clear();
try {
cur = mCol
.getDb()
.getDatabase()
.rawQuery(
"SELECT due, id FROM cards WHERE did IN " + _deckLimit() + " AND queue = 1 AND due < "
+ mDayCutoff + " LIMIT " + mReportLimit, null);
while (cur.moveToNext()) {
mLrnQueue.add(new long[] { cur.getLong(0), cur.getLong(1) });
}
// as it arrives sorted by did first, we need to sort it
Collections.sort(mLrnQueue, new DueComparator());
return !mLrnQueue.isEmpty();
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
private Card _getLrnCard() {
return _getLrnCard(false);
}
private Card _getLrnCard(boolean collapse) {
if (_fillLrn()) {
double cutoff = Utils.now();
if (collapse) {
try {
cutoff += mCol.getConf().getInt("collapseTime");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
if (mLrnQueue.getFirst()[0] < cutoff) {
long id = mLrnQueue.remove()[1];
Card card = mCol.getCard(id);
mLrnCount -= card.getLeft() / 1000;
return card;
}
}
return null;
}
// daily learning
private boolean _fillLrnDay() {
if (mLrnCount == 0) {
return false;
}
if (!mLrnDayQueue.isEmpty()) {
return true;
}
while (mLrnDids.size() > 0) {
long did = mLrnDids.getFirst();
// fill the queue with the current did
mLrnDayQueue.clear();
Cursor cur = null;
try {
cur = mCol
.getDb()
.getDatabase()
.rawQuery(
"SELECT id FROM cards WHERE did = " + did + " AND queue = 3 AND due <= " + mToday
+ " LIMIT " + mQueueLimit, null);
while (cur.moveToNext()) {
mLrnDayQueue.add(new long[] { cur.getLong(0) });
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
if (mLrnDayQueue.size() > 0) {
// order
Random r = new Random();
r.setSeed(mToday);
Collections.shuffle(mLrnDayQueue, r);
// is the current did empty?
if (mLrnDayQueue.size() < mQueueLimit) {
mLrnDids.remove();
}
return true;
}
// nothing left in the deck; move to next
mLrnDids.remove();
}
return false;
}
private Card _getLrnDayCard() {
if (_fillLrnDay()) {
mLrnCount -= 1;
return mCol.getCard(mLrnDayQueue.remove()[0]);
}
return null;
}
/**
* @param ease 1=no, 2=yes, 3=remove
*/
private void _answerLrnCard(Card card, int ease) {
// ease 1=no, 2=yes, 3=remove
JSONObject conf = _lrnConf(card);
int type;
if (card.getODid() != 0) {
type = 3;
} else if (card.getType() == 2) {
type = 2;
} else {
type = 0;
}
boolean leaving = false;
// lrnCount was decremented once when card was fetched
int lastLeft = card.getLeft();
// immediate graduate?
if (ease == 3) {
_rescheduleAsRev(card, conf, true);
leaving = true;
// graduation time?
} else if (ease == 2 && (card.getLeft() % 1000) - 1 <= 0) {
_rescheduleAsRev(card, conf, false);
leaving = true;
} else {
// one step towards graduation
if (ease == 2) {
// decrement real left count and recalculate left today
int left = (card.getLeft() % 1000) - 1;
try {
card.setLeft(_leftToday(conf.getJSONArray("delays"), left) * 1000 + left);
} catch (JSONException e) {
throw new RuntimeException(e);
}
// failed
} else {
card.setLeft(_startingLeft(card));
if (card.getODid() != 0) {
boolean resched = _resched(card);
if (conf.has("mult") && resched) {
// review that's lapsed
try {
card.setIvl(Math.max(1, (int) (card.getIvl() * conf.getDouble("mult"))));
} catch (JSONException e) {
throw new RuntimeException(e);
}
} else {
// new card; no ivl adjustment
// pass
}
if (resched) {
card.setODue(mToday + 1);
}
}
}
int delay = _delayForGrade(conf, card.getLeft());
if (card.getDue() < Utils.now()) {
// not collapsed; add some randomness
delay *= (1 + (new Random().nextInt(25) / 100));
}
// TODO: check, if type for second due is correct
card.setDue((int) (Utils.now() + delay));
if (card.getDue() < mDayCutoff) {
mLrnCount += card.getLeft() / 1000;
// if the queue is not empty and there's nothing else to do, make
// sure we don't put it at the head of the queue and end up showing
// it twice in a row
card.setQueue(1);
if (!mLrnQueue.isEmpty() && mRevCount == 0 && mNewCount == 0) {
long smallestDue = mLrnQueue.getFirst()[0];
card.setDue(Math.max(card.getDue(), smallestDue + 1));
}
_sortIntoLrn(card.getDue(), card.getId());
} else {
// the card is due in one or more days, so we need to use the day learn queue
long ahead = ((card.getDue() - mDayCutoff) / 86400) + 1;
card.setDue(mToday + ahead);
card.setQueue(3);
}
}
_logLrn(card, ease, conf, leaving, type, lastLeft);
}
/**
* Sorts a card into the lrn queue LIBANKI: not in libanki
*/
private void _sortIntoLrn(long due, long id) {
Iterator i = mLrnQueue.listIterator();
int idx = 0;
while (i.hasNext()) {
if (((long[]) i.next())[0] > due) {
break;
} else {
idx++;
}
}
mLrnQueue.add(idx, new long[] { due, id });
}
private int _delayForGrade(JSONObject conf, int left) {
left = left % 1000;
try {
double delay;
JSONArray ja = conf.getJSONArray("delays");
int len = ja.length();
try {
delay = ja.getDouble(len - left);
} catch (JSONException e) {
delay = ja.getDouble(0);
}
return (int) (delay * 60.0);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private JSONObject _lrnConf(Card card) {
if (card.getType() == 2) {
return _lapseConf(card);
} else {
return _newConf(card);
}
}
private void _rescheduleAsRev(Card card, JSONObject conf, boolean early) {
boolean lapse = (card.getType() == 2);
if (lapse) {
if (_resched(card)) {
card.setDue(Math.max(mToday + 1, card.getODue()));
} else {
card.setDue(card.getODue());
}
card.setODue(0);
} else {
_rescheduleNew(card, conf, early);
}
card.setQueue(2);
card.setType(2);
// if we were dynamic, graduating means moving back to the old deck
boolean resched = _resched(card);
if (card.getODid() != 0) {
card.setDid(card.getODid());
card.setODue(0);
card.setODid(0);
// if rescheduling is off, it needs to be set back to a new card
if (!resched && !lapse) {
card.setType(0);
card.setQueue(card.getType());
card.setDue(mCol.nextID("pos"));
}
}
}
private int _startingLeft(Card card) {
try {
JSONObject conf = _lrnConf(card);
int tot = conf.getJSONArray("delays").length();
int tod = _leftToday(conf.getJSONArray("delays"), tot);
return tot + tod * 1000;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/* the number of steps that can be completed by the day cutoff */
private int _leftToday(JSONArray delays, int left) {
return _leftToday(delays, left, 0);
}
private int _leftToday(JSONArray delays, int left, long now) {
if (now == 0) {
now = Utils.intNow();
}
int ok = 0;
int offset = Math.min(left, delays.length());
for (int i = 0; i < offset; i++) {
try {
now += (int) (delays.getDouble(delays.length() - offset + i) * 60.0);
} catch (JSONException e) {
throw new RuntimeException(e);
}
if (now > mDayCutoff) {
break;
}
ok = i;
}
return ok + 1;
}
private int _graduatingIvl(Card card, JSONObject conf, boolean early) {
return _graduatingIvl(card, conf, early, true);
}
private int _graduatingIvl(Card card, JSONObject conf, boolean early, boolean adj) {
if (card.getType() == 2) {
// lapsed card being relearnt
if (card.getODid() != 0) {
try {
if (conf.getBoolean("resched")) {
return _dynIvlBoost(card);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
return card.getIvl();
}
int ideal;
JSONArray ja;
try {
ja = conf.getJSONArray("ints");
if (!early) {
// graduate
ideal = ja.getInt(0);
} else {
ideal = ja.getInt(1);
}
if (adj) {
return _adjRevIvl(card, ideal);
} else {
return ideal;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/* Reschedule a new card that's graduated for the first time. */
private void _rescheduleNew(Card card, JSONObject conf, boolean early) {
card.setIvl(_graduatingIvl(card, conf, early));
card.setDue(mToday + card.getIvl());
try {
card.setFactor(conf.getInt("initialFactor"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private void _logLrn(Card card, int ease, JSONObject conf, boolean leaving, int type, int lastLeft) {
int lastIvl = -(_delayForGrade(conf, lastLeft));
int ivl = leaving ? card.getIvl() : -(_delayForGrade(conf, card.getLeft()));
log(card.getId(), mCol.usn(), ease, ivl, lastIvl, card.getFactor(), card.timeTaken(), type);
}
private void log(long id, int usn, int ease, int ivl, int lastIvl, int factor, int timeTaken, int type) {
try {
mCol.getDb().execute("INSERT INTO revlog VALUES (?,?,?,?,?,?,?,?,?)",
new Object[] { Utils.now() * 1000, id, usn, ease, ivl, lastIvl, factor, timeTaken, type });
} catch (SQLiteConstraintException e) {
try {
Thread.sleep(10);
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
log(id, usn, ease, ivl, lastIvl, factor, timeTaken, type);
}
}
public void removeFailed() {
removeFailed(null);
}
private void removeFailed(long[] ids) {
removeFailed(ids, false);
}
private void removeFailed(boolean expiredOnly) {
removeFailed(null, expiredOnly);
}
/**
* Remove failed cards from the learning queue.
*/
private void removeFailed(long[] ids, boolean expiredOnly) {
String extra;
if (ids != null && ids.length > 0) {
extra = " AND id IN " + Utils.ids2str(ids);
} else {
// benchmarks indicate it's about 10x faster to search all decks with the index than scan the table
extra = " AND did IN " + Utils.ids2str(mCol.getDecks().allIds());
}
if (expiredOnly) {
extra += " AND odue <= " + mToday;
}
boolean mod = mCol.getDb().getMod();
mCol.getDb().execute(
String.format(Locale.US, "update cards set " + "due = odue, queue = 2, mod = %d, usn = %d, odue = 0 "
+ "where queue = 1 and type = 2 %s", Utils.intNow(), mCol.usn(), extra));
if (expiredOnly) {
// we don't want to bump the mod time when removing expired
mCol.getDb().setMod(mod);
}
}
private int _lrnForDeck(long did) {
try {
return mCol.getDb().queryScalar(
"SELECT sum(left / 1000) FROM (SELECT left FROM cards WHERE did = " + did
+ " AND queue = 1 AND due < " + (Utils.intNow() + mCol.getConf().getInt("collapseTime"))
+ " LIMIT " + mReportLimit + ")", false);
} catch (SQLException e) {
throw new RuntimeException(e);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* Reviews ****************************************************************** *****************************
*/
private int _deckRevLimit(long did) {
try {
return _deckNewLimit(did, Sched.class.getDeclaredMethod("_deckRevLimitSingle", JSONObject.class));
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private int _deckRevLimitSingle(JSONObject d) {
try {
if (d.getInt("dyn") != 0) {
return mReportLimit;
}
JSONObject c = mCol.getDecks().confForDid(d.getLong("id"));
return Math.max(0, c.getJSONObject("rev").getInt("perDay") - d.getJSONArray("revToday").getInt(1));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public int _revForDeck(long did, int lim) {
lim = Math.min(lim, mReportLimit);
return mCol.getDb().queryScalar("SELECT count() FROM (SELECT 1 FROM cards WHERE did = " + did + " AND queue = 2 and due <= " + mToday + " LIMIT " + lim + ")", false);
}
private void _resetRevCount() {
try {
mRevCount = _walkingCount(Sched.class.getDeclaredMethod("_deckRevLimitSingle", JSONObject.class),
Sched.class.getDeclaredMethod("_cntFnRev", long.class, int.class));
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
private int _cntFnRev(long did, int lim) {
return mCol.getDb().queryScalar(
"SELECT count() FROM (SELECT id FROM cards WHERE did = " + did + " AND queue = 2 and due <= " + mToday
+ " LIMIT " + lim + ")");
}
private void _resetRev() {
_resetRevCount();
mRevQueue.clear();
mRevDids = mCol.getDecks().active();
}
private boolean _fillRev() {
if (!mRevQueue.isEmpty()) {
return true;
}
if (mRevCount == 0) {
return false;
}
while (mRevDids.size() > 0) {
long did = mRevDids.getFirst();
int lim = Math.min(mQueueLimit, _deckRevLimit(did));
mRevQueue.clear();
Cursor cur = null;
if (lim != 0) {
// fill the queue with the current did
try {
cur = mCol
.getDb()
.getDatabase()
.rawQuery(
"SELECT id FROM cards WHERE did = " + did + " AND queue = 2 AND due <= " + mToday
+ " LIMIT " + lim, null);
while (cur.moveToNext()) {
mRevQueue.add(new long[] { cur.getLong(0) });
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
if (!mRevQueue.isEmpty()) {
// ordering
try {
if (mCol.getDecks().get(did).getInt("dyn") != 0) {
// dynamic decks need due order preserved
} else {
Random r = new Random();
r.setSeed(mToday);
Collections.shuffle(mRevQueue, r);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
// is the current did empty?
if (mRevQueue.size() < lim) {
mRevDids.remove();
}
return true;
}
}
// nothing left in the deck; move to next
mRevDids.remove();
}
return false;
}
private Card _getRevCard() {
if (_fillRev()) {
mRevCount -= 1;
return mCol.getCard(mRevQueue.remove()[0]);
} else {
return null;
}
}
/**
* Answering a review card **************************************************
* *********************************************
*/
private boolean _answerRevCard(Card card, int ease) {
int delay = 0;
boolean leech = false;
if (ease == 1) {
Pair<Integer, Boolean> res = _rescheduleLapse(card);
delay = res.first;
leech = res.second;
} else {
_rescheduleRev(card, ease);
}
_logRev(card, ease, delay);
return leech;
}
private Pair<Integer, Boolean> _rescheduleLapse(Card card) {
JSONObject conf;
try {
conf = _lapseConf(card);
card.setLastIvl(card.getIvl());
if (_resched(card)) {
card.setLapses(card.getLapses() + 1);
card.setIvl(_nextLapseIvl(card, conf));
card.setFactor(Math.max(1300, card.getFactor() - 200));
card.setDue(mToday + card.getIvl());
}
// if suspended as a leech, nothing to do
int delay = 0;
if (_checkLeech(card, conf) && card.getQueue() == -1) {
return new Pair<Integer, Boolean>(delay, true);
}
// if no relearning steps, nothing to do
if (conf.getJSONArray("delays").length() == 0) {
return new Pair<Integer, Boolean>(delay, false);
}
// record rev due date for later
if (card.getODue() == 0) {
card.setODue(card.getDue());
}
delay = _delayForGrade(conf, 0);
card.setDue((long) (delay + Utils.now()));
// queue 1
if (card.getDue() < mDayCutoff) {
int left = conf.getJSONArray("delays").length();
card.setLeft(left + _leftToday(conf.getJSONArray("delays"), left) * 1000);
mLrnCount += card.getLeft() / 1000;
card.setQueue(1);
_sortIntoLrn(card.getDue(), card.getId());
return new Pair<Integer, Boolean>(delay, false);
} else {
// day learn queue
long ahead = ((card.getDue() - mDayCutoff) / 86400) + 1;
card.setDue(mToday + ahead);
card.setQueue(3);
}
return new Pair<Integer, Boolean>(delay, true);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private int _nextLapseIvl(Card card, JSONObject conf) {
try {
return (int) (card.getIvl() * conf.getDouble("mult")) + 1;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private void _rescheduleRev(Card card, int ease) {
// update interval
card.setLastIvl(card.getIvl());
if (_resched(card)) {
_updateRevIvl(card, ease);
// then the rest
card.setFactor(Math.max(1300, card.getFactor() + FACTOR_ADDITION_VALUES[ease - 2]));
card.setDue(mToday + card.getIvl());
} else {
card.setDue(card.getODue());
}
if (card.getODid() != 0) {
card.setDid(card.getODid());
card.setODid(0);
card.setODue(0);
}
}
private void _logRev(Card card, int ease, int delay) {
log(card.getId(), mCol.usn(), ease, ((delay != 0) ? (-delay) : card.getIvl()), card.getLastIvl(),
card.getFactor(), card.timeTaken(), 1);
}
/**
* Interval management ******************************************************
* *****************************************
*/
/**
* Ideal next interval for CARD, given EASE.
*/
private int _nextRevIvl(Card card, int ease) {
long delay = _daysLate(card);
double interval = 0;
JSONObject conf = _revConf(card);
double fct = card.getFactor() / 1000.0;
if (ease == 2) {
interval = (card.getIvl() + delay / 4) * 1.2;
} else if (ease == 3) {
interval = (card.getIvl() + delay / 2) * fct;
} else if (ease == 4) {
try {
interval = (card.getIvl() + delay) * fct * conf.getDouble("ease4");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
// apply interval factor adjustment
interval = _ivlWithFactor(conf, interval);
// must be at least one day greater than previous interval; two if easy
int intinterval = Math.max(card.getIvl() + (ease == 4 ? 2 : 1), (int) interval);
// interval capped?
try {
return Math.min(intinterval, conf.getInt("maxIvl"));
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private double _ivlWithFactor(JSONObject conf, double ivl) {
try {
return ivl * conf.getDouble("ivlFct");
} catch (JSONException e) {
return 1;
}
}
/**
* Number of days later than scheduled.
*/
private long _daysLate(Card card) {
long due = card.getODid() != 0 ? card.getODue() : card.getDue();
return Math.max(0, mToday - due);
}
/**
* Update CARD's interval, trying to avoid siblings.
*/
private void _updateRevIvl(Card card, int ease) {
int idealIvl = _nextRevIvl(card, ease);
card.setIvl(_adjRevIvl(card, idealIvl));
}
/**
* Given IDEALIVL, return an IVL away from siblings.
*/
private int _adjRevIvl(Card card, int idealIvl) {
int idealDue = mToday + idealIvl;
JSONObject conf;
try {
conf = _revConf(card);
// find sibling positions
ArrayList<Integer> dues = mCol.getDb()
.queryColumn(
Integer.class,
"SELECT due FROM cards WHERE nid = " + card.getNid() + " AND type = 2 AND id != "
+ card.getId(), 0);
if (dues.size() == 0 || !dues.contains(idealDue)) {
return idealIvl;
} else {
int leeway = Math.max(conf.getInt("minSpace"), (int) (idealIvl * conf.getDouble("fuzz")));
int fudge = 0;
// do we have any room to adjust the interval?
if (leeway != 0) {
// loop through possible due dates for an empty one
for (int diff = 1; diff < leeway + 1; diff++) {
// ensure we're due at least tomorrow
if ((idealIvl - diff >= 1) && !dues.contains(idealDue - diff)) {
fudge = -diff;
break;
} else if (!dues.contains(idealDue + diff)) {
fudge = diff;
break;
}
}
}
return idealIvl + fudge;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* Dynamic deck handling ******************************************************************
* *****************************
*/
/* Rebuild a dynamic deck. */
public void rebuildDyn() {
rebuildDyn(0);
}
public List<Long> rebuildDyn(long did) {
if (did == 0) {
did = mCol.getDecks().selected();
}
JSONObject deck = mCol.getDecks().get(did);
try {
if (deck.getInt("dyn") == 0) {
Log.e(AnkiDroidApp.TAG, "error: deck is not a dynamic deck");
return null;
}
} catch (JSONException e1) {
throw new RuntimeException(e1);
}
// move any existing cards back first, then fill
emptyDyn(did);
List<Long> ids = _fillDyn(deck);
if (ids.isEmpty()) {
return null;
}
// and change to our new deck
mCol.getDecks().select(did);
return ids;
}
private List<Long> _fillDyn(JSONObject deck) {
JSONArray terms;
List<Long> ids;
try {
terms = deck.getJSONArray("terms").getJSONArray(0);
String search = terms.getString(0);
int limit = terms.getInt(1);
int order = terms.getInt(2);
String orderlimit = _dynOrder(order, limit);
search += " -is:suspended -deck:filtered";
ids = mCol.findCards(search, orderlimit);
if (ids.isEmpty()) {
return ids;
}
// move the cards over
_moveToDyn(deck.getLong("id"), ids);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return ids;
}
public void emptyDyn(long did) {
emptyDyn(did, null);
}
public void emptyDyn(long did, String lim) {
if (lim == null) {
lim = "did = " + did;
}
// move out of cram queue
mCol.getDb().execute(
"UPDATE cards SET did = odid, queue = (CASE WHEN type = 1 THEN 0 "
+ "ELSE type END), type = (CASE WHEN type = 1 THEN 0 ELSE type END), "
+ "due = odue, odue = 0, odid = 0, usn = ?, mod = ? where " + lim,
new Object[] { mCol.usn(), Utils.intNow() });
}
public void remFromDyn(long[] cids) {
emptyDyn(0, "id IN " + Utils.ids2str(cids) + " AND odid");
}
/**
* Generates the required SQL for order by and limit clauses, for dynamic decks.
*
* @param o deck["order"]
* @param l deck["limit"]
* @return The generated SQL to be suffixed to "select ... from ... order by "
*/
private String _dynOrder(int o, int l) {
String t;
switch (o) {
case DYN_OLDEST:
t = "c.mod";
break;
case DYN_RANDOM:
t = "random()";
break;
case DYN_SMALLINT:
t = "ivl";
break;
case DYN_BIGINT:
t = "ivl desc";
break;
case DYN_LAPSES:
t = "lapses desc";
break;
case DYN_ADDED:
t = "n.id";
break;
case DYN_DUE:
t = "c.due";
break;
default:
throw new RuntimeException("Sched._dynOrder: Unexpected order for dynamic deck " + o);
}
return t + " limit " + l;
}
private void _moveToDyn(long did, List<Long> ids) {
ArrayList<Object[]> data = new ArrayList<Object[]>();
long t = Utils.intNow();
int u = mCol.usn();
for (long c = 0; c < ids.size(); c++) {
// start at -100000 so that reviews are all due
data.add(new Object[] { did, -100000 + c, t, u, ids.get((int) c) });
}
// due reviews stay in the review queue. careful: can't use "odid or did", as sqlite converts to boolean
String queue = String.format(Locale.US,
"(CASE WHEN type = 2 AND (CASE WHEN odue THEN odue <= %d ELSE due <= %d END) THEN 2 ELSE 0 END)",
mToday, mToday);
mCol.getDb().executeMany(
String.format(Locale.US, "UPDATE cards SET " + "odid = (CASE WHEN odid THEN odid ELSE did END), "
+ "odue = (CASE WHEN odue THEN odue ELSE due END), "
+ "did = ?, queue = %s, due = ?, mod = ?, usn = ? WHERE id = ?", queue), data);
}
private int _dynIvlBoost(Card card) {
if (card.getODid() == 0 || card.getType() != 2 || card.getFactor() == 0) {
Log.e(AnkiDroidApp.TAG, "error: deck is not a dynamic deck");
return 0;
}
long elapsed = card.getIvl() - (card.getODue() - mToday);
double factor = ((card.getFactor() / 1000.0) + 1.2) / 2.0;
int ivl = Math.max(1, Math.max(card.getIvl(), (int) (elapsed * factor)));
JSONObject conf = _revConf(card);
try {
return Math.min(conf.getInt("maxIvl"), ivl);
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* Leeches ****************************************************************** *****************************
*/
/** Leech handler. True if card was a leech. */
private boolean _checkLeech(Card card, JSONObject conf) {
int lf;
try {
lf = conf.getInt("leechFails");
if (lf == 0) {
return false;
}
// if over threshold or every half threshold reps after that
if (card.getLapses() >= lf && (card.getLapses() - lf) % Math.max(lf / 2, 1) == 0) {
// add a leech tag
Note n = card.note();
n.addTag("leech");
n.flush();
// handle
if (conf.getInt("leechAction") == 0) {
// if it has an old due, remove it from cram/relearning
if (card.getODue() != 0) {
card.setDue(card.getODue());
}
if (card.getODid() != 0) {
card.setDid(card.getODid());
}
card.setODue(0);
card.setODid(0);
card.setQueue(-1);
}
return true;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
return false;
}
/** LIBANKI: not in libanki */
public boolean leechActionSuspend(Card card) {
JSONObject conf;
try {
conf = _cardConf(card).getJSONObject("lapse");
if (conf.getInt("leechAction") == 0) {
return true;
} else {
return false;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* Tools ******************************************************************** ***************************
*/
public JSONObject _cardConf(Card card) {
return mCol.getDecks().confForDid(card.getDid());
}
private JSONObject _newConf(Card card) {
try {
JSONObject conf = _cardConf(card);
if (card.getODid() == 0) {
return conf.getJSONObject("new");
}
// dynamic deck; override some attributes, use original deck for others
JSONObject oconf = mCol.getDecks().confForDid(card.getODid());
JSONArray delays = conf.optJSONArray("delays");
if (delays == null) {
delays = oconf.getJSONObject("new").getJSONArray("delays");
}
JSONObject dict = new JSONObject();
// original deck
dict.put("ints", oconf.getJSONObject("new").getJSONArray("ints"));
dict.put("initialFactor", oconf.getJSONObject("new").getInt("initialFactor"));
// overrides
dict.put("delays", delays);
dict.put("separate", conf.getBoolean("separate"));
dict.put("order", NEW_CARDS_DUE);
dict.put("perDay", mReportLimit);
return dict;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private JSONObject _lapseConf(Card card) {
try {
JSONObject conf = _cardConf(card);
// normal deck
if (card.getODid() == 0) {
return conf.getJSONObject("lapse");
}
// dynamic deck; override some attributes, use original deck for others
JSONObject oconf = mCol.getDecks().confForDid(card.getODid());
JSONArray delays = conf.optJSONArray("delays");
if (delays == null) {
delays = oconf.getJSONObject("lapse").getJSONArray("delays");
}
JSONObject dict = new JSONObject();
// original deck
dict.put("minInt", oconf.getJSONObject("lapse").getInt("minInt"));
dict.put("leechFails", oconf.getJSONObject("lapse").getInt("leechFails"));
dict.put("leechAction", oconf.getJSONObject("lapse").getInt("leechAction"));
dict.put("mult", oconf.getJSONObject("lapse").getDouble("mult"));
// overrides
dict.put("delays", delays);
dict.put("resched", conf.getBoolean("resched"));
return dict;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private JSONObject _revConf(Card card) {
try {
JSONObject conf = _cardConf(card);
if (card.getODid() == 0) {
return conf.getJSONObject("rev");
}
// dynamic deck
return mCol.getDecks().confForDid(card.getODid()).getJSONObject("rev");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
public String _deckLimit() {
return Utils.ids2str(mCol.getDecks().active());
}
private boolean _resched(Card card) {
JSONObject conf = _cardConf(card);
try {
if (conf.getInt("dyn") == 0) {
return true;
}
return conf.getBoolean("resched");
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* Daily cutoff ************************************************************* **********************************
*/
public void _updateCutoff() {
// days since col created
mToday = (int) ((Utils.now() - mCol.getCrt()) / 86400);
// end of day cutoff
mDayCutoff = mCol.getCrt() + ((mToday + 1) * 86400);
// this differs from libanki: updates all decks
for (JSONObject d : mCol.getDecks().all()) {
update(d);
}
// update all daily counts, but don't save decks to prevent needless conflicts. we'll save on card answer
// instead
for (JSONObject deck : mCol.getDecks().all()) {
update(deck);
}
}
private void update(JSONObject g) {
for (String t : new String[] { "new", "rev", "lrn", "time" }) {
String k = t + "Today";
try {
if (g.getJSONArray(k).getInt(0) != mToday) {
JSONArray ja = new JSONArray();
ja.put(mToday);
ja.put(0);
g.put(k, ja);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
}
public boolean _checkDay() {
// check if the day has rolled over
if (Utils.now() > mDayCutoff) {
reset();
return true;
}
return false;
}
/**
* Deck finished state ******************************************************
* *****************************************
*/
public CharSequence finishedMsg(Context context) {
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append(context.getString(R.string.studyoptions_congrats_finished));
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
sb.setSpan(boldSpan, 0, sb.length(), 0);
sb.append(_nextDueMsg(context));
// sb.append("\n\n");
// sb.append(_tomorrowDueMsg(context));
return sb;
}
// public String _tomorrowDueMsg(Context context) {
// int newCards = 12;// deck.getSched().newTomorrow();
// int revCards = 1;// deck.getSched().revTomorrow() +
// int eta = 0; // TODO
// Resources res = context.getResources();
// String newCardsText = res.getQuantityString(
// R.plurals.studyoptions_congrats_new_cards, newCards, newCards);
// String etaText = res.getQuantityString(
// R.plurals.studyoptions_congrats_eta, eta, eta);
// return res.getQuantityString(R.plurals.studyoptions_congrats_message,
// revCards, revCards, newCardsText, etaText);
// }
public String _nextDueMsg(Context context) {
StringBuilder sb = new StringBuilder();
if (revDue()) {
sb.append("\n\n");
sb.append(context.getString(R.string.studyoptions_congrats_more_rev));
}
if (newDue()) {
sb.append("\n\n");
sb.append(context.getString(R.string.studyoptions_congrats_more_new));
}
return sb.toString();
}
// /**
// * Number of rev/lrn cards due tomorrow.
// */
// public int revTomorrow() {
// TODO: _walkingCount...
// return mCol.getDb().queryScalar(
// "SELECT count() FROM cards WHERE type > 0 AND queue != -1 AND due = "
// + (mDayCutoff + 86400) + " AND did IN " + _deckLimit());
// }
/** true if there are any rev cards due. */
public boolean revDue() {
return mCol.getDb()
.queryScalar(
"SELECT 1 FROM cards WHERE did IN " + _deckLimit() + " AND queue = 2 AND due <= " + mToday
+ " LIMIT 1", false) != 0;
}
/** true if there are any new cards due. */
public boolean newDue() {
return mCol.getDb().queryScalar("SELECT 1 FROM cards WHERE did IN " + _deckLimit() + " AND queue = 0 LIMIT 1",
false) != 0;
}
/**
* Next time reports ********************************************************
* ***************************************
*/
/**
* Return the next interval for CARD as a string.
*/
public String nextIvlStr(Card card, int ease) {
return nextIvlStr(card, ease, false);
}
public String nextIvlStr(Card card, int ease, boolean _short) {
int ivl = nextIvl(card, ease);
if (ivl == 0) {
return "";
}
return Utils.fmtTimeSpan(ivl, _short);
}
/**
* Return the next interval for CARD, in seconds.
*/
public int nextIvl(Card card, int ease) {
try {
if (card.getQueue() == 0 || card.getQueue() == 1 || card.getQueue() == 3) {
return _nextLrnIvl(card, ease);
} else if (ease == 1) {
// lapsed
JSONObject conf = _lapseConf(card);
if (conf.getJSONArray("delays").length() > 0) {
return (int) (conf.getJSONArray("delays").getDouble(0) * 60.0);
}
return _nextLapseIvl(card, conf) * 86400;
} else {
// review
return _nextRevIvl(card, ease) * 86400;
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
private int _nextLrnIvl(Card card, int ease) {
// this isn't easily extracted from the learn code
if (card.getQueue() == 0) {
card.setLeft(_startingLeft(card));
}
JSONObject conf = _lrnConf(card);
try {
if (ease == 1) {
// fail
return _delayForGrade(conf, conf.getJSONArray("delays").length());
} else if (ease == 3) {
// early removal
if (!_resched(card)) {
return 0;
}
return _graduatingIvl(card, conf, true, false) * 86400;
} else {
int left = card.getLeft() % 1000 - 1;
if (left <= 0) {
// graduate
if (!_resched(card)) {
return 0;
}
return _graduatingIvl(card, conf, false, false) * 86400;
} else {
return _delayForGrade(conf, left);
}
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/**
* Suspending *************************************************************** ********************************
*/
/**
* Suspend cards.
*/
public void suspendCards(long[] ids) {
remFromDyn(ids);
removeFailed(ids);
mCol.getDb().execute(
"UPDATE cards SET queue = -1, mod = " + Utils.intNow() + ", usn = " + mCol.usn() + " WHERE id IN "
+ Utils.ids2str(ids));
}
/**
* Unsuspend cards
*/
public void unsuspendCards(long[] ids) {
mCol.getDb().execute(
"UPDATE cards SET queue = type, mod = " + Utils.intNow() + ", usn = " + mCol.usn()
+ " WHERE queue = -1 AND id IN " + Utils.ids2str(ids));
}
/**
* Bury all cards for note until next session.
*/
public void buryNote(long nid) {
mCol.setDirty();
long[] cids = Utils.arrayList2array(mCol.getDb().queryColumn(Long.class,
"SELECT id FROM cards WHERE nid = " + nid, 0));
remFromDyn(cids);
removeFailed(cids);
mCol.getDb().execute("UPDATE cards SET queue = -2 WHERE nid = " + nid);
}
/**
* Counts ******************************************************************* ****************************
*/
/** LIBANKI: not in libanki */
public int cardCount() {
return cardCount(_deckLimit());
}
public int cardCount(String dids) {
return mCol.getDb().queryScalar("SELECT count() FROM cards WHERE did IN " + dids, false);
}
/** LIBANKI: not in libanki */
public int newCount() {
return newCount(_deckLimit());
}
public int newCount(String dids) {
return mCol.getDb().queryScalar("SELECT count() FROM cards WHERE type = 0 AND did IN " + dids, false);
}
/** LIBANKI: not in libanki */
public int matureCount() {
return matureCount(_deckLimit());
}
public int matureCount(String dids) {
return mCol.getDb().queryScalar("SELECT count() FROM cards WHERE type = 2 AND ivl >= 21 AND did IN " + dids,
false);
}
/** returns today's progress
*
* @param counts (if empty, cached version will be used if any)
* @param card
* @return [progressCurrentDeck, progressAllDecks, leftCards, eta]
*/
public float[] progressToday(TreeSet<Object[]> counts, Card card, boolean eta) {
try {
int doneCurrent = 0;
int[] leftCurrent = new int[]{0, 0, 0};
String[] cs = new String[]{"new", "lrn", "rev"};
long currentDid = 0;
// refresh deck progresses with fresh counts if necessary
if (counts != null || mCachedDeckCounts == null) {
if (mCachedDeckCounts == null) {
mCachedDeckCounts = new HashMap<Long, Pair<String[], long[]>>();
}
mCachedDeckCounts.clear();
if (counts == null) {
// reload counts
counts = (TreeSet<Object[]>)deckCounts()[0];
}
- int done = 0;
for (Object[] d : counts) {
+ int done = 0;
JSONObject deck = mCol.getDecks().get((Long) d[1]);
for (String s : cs) {
done += deck.getJSONArray(s + "Today").getInt(1);
}
mCachedDeckCounts.put((Long)d[1], new Pair<String[], long[]> ((String[])d[0], new long[]{done, (Integer)d[2], (Integer)d[3], (Integer)d[4]}));
}
}
// current selected deck
if (card != null) {
JSONObject deck = mCol.getDecks().current();
currentDid = deck.getLong("id");
for (String s : cs) {
doneCurrent += deck.getJSONArray(s + "Today").getInt(1);
}
int idx = countIdx(card);
leftCurrent = new int[]{ mNewCount + (idx == 1 ? 0 : 1), mLrnCount + (idx == 1 ? card.getLeft() / 1000 : 0), mRevCount + (idx == 1 ? 0 : 1)};
}
int doneAll = 0;
int[] leftAll = new int[]{0, 0, 0};
for (Map.Entry<Long, Pair<String[], long[]>> d : mCachedDeckCounts.entrySet()) {
boolean exclude = d.getKey() == currentDid; // || mCol.getDecks().isDyn(d.getKey());
if (d.getValue().first.length == 1) {
if (exclude) {
// don't count cached version of current deck
continue;
}
long[] c = d.getValue().second;
doneAll += c[0];
leftAll[0] += c[1];
leftAll[1] += c[2];
leftAll[2] += c[3];
} else if (exclude) {
// exclude cached values for current deck in order to avoid double count
long[] c = d.getValue().second;
doneAll -= c[0];
leftAll[0] -= c[1];
leftAll[1] -= c[2];
leftAll[2] -= c[3];
}
}
doneAll += doneCurrent;
leftAll[0] += leftCurrent[0];
leftAll[1] += leftCurrent[1];
leftAll[2] += leftCurrent[2];
int totalAll = doneAll + leftAll[0] + leftAll[1] + leftAll[2];
int totalCurrent = doneCurrent + leftCurrent[0] + leftCurrent[1] + leftCurrent[2];
float progressCurrent = -1;
if (totalCurrent != 0) {
progressCurrent = (float) doneCurrent / (float) totalCurrent;
}
float progressTotal = -1;
if (totalAll != 0) {
progressTotal = (float) doneAll / (float) totalAll;
}
return new float[]{ progressCurrent, progressTotal, totalAll - doneAll, eta ? eta(leftAll, false) : -1};
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
/** LIBANKI: not in libanki */
public int eta(int[] counts) {
return eta(counts, true);
}
/** estimates remaining time for learning (based on last seven days) */
public int eta(int[] counts, boolean reload) {
double revYesRate;
double revTime;
double lrnYesRate;
double lrnTime;
if (reload || mEtaCache[0] == -1) {
Cursor cur = null;
try {
cur = mCol
.getDb()
.getDatabase()
.rawQuery(
"SELECT avg(CASE WHEN ease > 1 THEN 1 ELSE 0 END), avg(time) FROM revlog WHERE type = 1 AND id > "
+ ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000), null);
if (!cur.moveToFirst()) {
return -1;
}
revYesRate = cur.getDouble(0);
revTime = cur.getDouble(1);
cur = mCol
.getDb()
.getDatabase()
.rawQuery(
"SELECT avg(CASE WHEN ease = 3 THEN 1 ELSE 0 END), avg(time) FROM revlog WHERE type != 1 AND id > "
+ ((mCol.getSched().getDayCutoff() - (7 * 86400)) * 1000), null);
if (!cur.moveToFirst()) {
return -1;
}
lrnYesRate = cur.getDouble(0);
lrnTime = cur.getDouble(1);
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
mEtaCache[0] = revYesRate;
mEtaCache[1] = revTime;
mEtaCache[2] = lrnYesRate;
mEtaCache[3] = lrnTime;
} else {
revYesRate = mEtaCache[0];
revTime = mEtaCache[1];
lrnYesRate = mEtaCache[2];
lrnTime = mEtaCache[3];
}
// rev cards
double eta = revTime * counts[2];
// lrn cards
double factor = Math.min(1 / (1 - lrnYesRate), 10);
double lrnAnswers = (counts[0] + counts[1] + counts[2] * (1 - revYesRate)) * factor;
eta += lrnAnswers * lrnTime;
return (int) (eta / 60000);
}
//
// /**
// * Time spent learning today, in seconds.
// */
// public int timeToday(int fid) {
// return (int)
// mDb.queryScalar("SELECT sum(taken / 1000.0) FROM revlog WHERE time > 1000 * "
// + (mDayCutoff - 86400));
// // TODO: check for 0?
// }
//
//
// /**
// * Number of cards answered today.
// */
// public int repsToday(int fid) {
// return (int) mDb.queryScalar("SELECT count() FROM revlog WHERE time > " +
// (mDayCutoff - 86400));
// }
//
//
// /**
// * Dynamic indices
// ***********************************************************************************************
// */
//
// private void updateDynamicIndices() {
// // Log.i(AnkiDroidApp.TAG, "updateDynamicIndices - Updating indices...");
// // // determine required columns
// // if (mDeck.getQconf().getInt("revOrder")) {
// //
// // }
// // HashMap<String, String> indices = new HashMap<String, String>();
// // indices.put("intervalDesc", "(queue, interval desc, factId, due)");
// // indices.put("intervalAsc", "(queue, interval, factId, due)");
// // indices.put("randomOrder", "(queue, factId, ordinal, due)");
// // // new cards are sorted by due, not combinedDue, so that even if
// // // they are spaced, they retain their original sort order
// // indices.put("dueAsc", "(queue, due, factId, due)");
// // indices.put("dueDesc", "(queue, due desc, factId, due)");
// //
// // ArrayList<String> required = new ArrayList<String>();
// // if (mRevCardOrder == REV_CARDS_OLD_FIRST) {
// // required.add("intervalDesc");
// // }
// // if (mRevCardOrder == REV_CARDS_NEW_FIRST) {
// // required.add("intervalAsc");
// // }
// // if (mRevCardOrder == REV_CARDS_RANDOM) {
// // required.add("randomOrder");
// // }
// // if (mRevCardOrder == REV_CARDS_DUE_FIRST || mNewCardOrder ==
// NEW_CARDS_OLD_FIRST
// // || mNewCardOrder == NEW_CARDS_RANDOM) {
// // required.add("dueAsc");
// // }
// // if (mNewCardOrder == NEW_CARDS_NEW_FIRST) {
// // required.add("dueDesc");
// // }
// //
// // // Add/delete
// // boolean analyze = false;
// // Set<Entry<String, String>> entries = indices.entrySet();
// // Iterator<Entry<String, String>> iter = entries.iterator();
// // String indexName = null;
// // while (iter.hasNext()) {
// // Entry<String, String> entry = iter.next();
// // indexName = "ix_cards_" + entry.getKey();
// // if (required.contains(entry.getKey())) {
// // Cursor cursor = null;
// // try {
// // cursor = getDB().getDatabase().rawQuery(
// // "SELECT 1 FROM sqlite_master WHERE name = '" + indexName + "'", null);
// // if ((!cursor.moveToNext()) || (cursor.getInt(0) != 1)) {
// // getDB().execute("CREATE INDEX " + indexName +
// " ON cards " + entry.getValue());
// // analyze = true;
// // }
// // } finally {
// // if (cursor != null) {
// // cursor.close();
// // }
// // }
// // } else {
// // getDB().execute("DROP INDEX IF EXISTS " + indexName);
// // }
// // }
// // if (analyze) {
// // getDB().execute("ANALYZE");
// // }
// }
/**
* Resetting **************************************************************** *******************************
*/
/** Put cards at the end of the new queue. */
public void forgetCards(long[] ids) {
mCol.getDb().execute("update cards set type=0,queue=0,ivl=0 where id in " + Utils.ids2str(ids));
int pmax = mCol.getDb().queryScalar("SELECT max(due) FROM cards WHERE type=0", false);
// takes care of mod + usn
sortCards(ids, pmax + 1);
}
/**
* Put cards in review queue with a new interval in days (min, max).
*
* @param ids The list of card ids to be affected
* @param imin the minimum interval (inclusive)
* @param imax The maximum interval (inclusive)
*/
public void reschedCards(long[] ids, int imin, int imax) {
ArrayList<Object[]> d = new ArrayList<Object[]>();
int t = mToday;
long mod = Utils.intNow();
Random rnd = new Random();
for (long id : ids) {
int r = rnd.nextInt(imax - imin + 1) + imin;
d.add(new Object[] { Math.max(1, r), r + t, mCol.usn(), mod, 2500, id });
}
mCol.getDb().executeMany(
"update cards set type=2,queue=2,ivl=?,due=?, " + "usn=?, mod=?, factor=? where id=? and odid=0", d);
}
/**
* Repositioning new cards **************************************************
* *********************************************
*/
public void sortCards(long[] cids, int start) {
sortCards(cids, start, 1, false, false);
}
public void sortCards(long[] cids, int start, int step, boolean shuffle, boolean shift) {
String scids = Utils.ids2str(cids);
long now = Utils.intNow();
ArrayList<Long> nids = mCol.getDb().queryColumn(Long.class,
"SELECT DISTINCT nid FROM cards WHERE type = 0 AND id IN " + scids + " ORDER BY nid", 0);
if (nids.size() == 0) {
// no new cards
return;
}
// determine nid ordering
HashMap<Long, Long> due = new HashMap<Long, Long>();
if (shuffle) {
Collections.shuffle(nids);
}
for (int c = 0; c < nids.size(); c++) {
due.put(nids.get(c), (long) (start + c * step));
}
int high = start + step * (nids.size() - 1);
// shift
if (shift) {
int low = mCol.getDb().queryScalar(
"SELECT min(due) FROM cards WHERE due >= " + start + " AND type = 0 AND id NOT IN " + scids, false);
if (low != 0) {
int shiftby = high - low + 1;
mCol.getDb().execute(
"UPDATE cards SET mod = " + now + ", usn = " + mCol.usn() + ", due = due + " + shiftby
+ " WHERE id NOT IN " + scids + " AND due >= " + low + " AND queue = 0");
}
}
// reorder cards
ArrayList<Object[]> d = new ArrayList<Object[]>();
Cursor cur = null;
try {
cur = mCol.getDb().getDatabase()
.rawQuery("SELECT id, nid FROM cards WHERE type = 0 AND id IN " + scids, null);
while (cur.moveToNext()) {
long nid = cur.getLong(1);
d.add(new Object[] { due.get(nid), now, mCol.usn(), cur.getLong(0) });
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
mCol.getDb().executeMany("UPDATE cards SET due = ?, mod = ?, usn = ? WHERE id = ?", d);
}
public void randomizeCards(long did) {
List<Long> cids = mCol.getDb().queryColumn(Long.class, "select id from cards where did = " + did, 0);
sortCards(Utils.toPrimitive(cids), 1, 1, true, false);
}
public void orderCards(long did) {
List<Long> cids = mCol.getDb().queryColumn(Long.class, "select id from cards where did = " + did, 0);
sortCards(Utils.toPrimitive(cids), 1, 1, false, false);
}
// resortconf
/**
* ************************************************************************* **********************
*/
public String getName() {
return mName;
}
public int getToday() {
return mToday;
}
public void setToday(int today) {
mToday = today;
}
public long getDayCutoff() {
return mDayCutoff;
}
public Collection getCol() {
return mCol;
}
public int getNewCount() {
return mNewCount;
}
// Needed for tests
public LinkedList<long[]> getNewQueue() {
return mNewQueue;
}
private class DeckNameCompare implements Comparator<Object[]> {
@Override
public int compare(Object[] lhs, Object[] rhs) {
String[] o1 = (String[]) lhs[0];
String[] o2 = (String[]) rhs[0];
for (int i = 0; i < Math.min(o1.length, o2.length); i++) {
int result = o1[i].compareToIgnoreCase(o2[i]);
if (result != 0) {
return result;
}
}
if (o1.length < o2.length) {
return -1;
} else if (o1.length > o2.length) {
return 1;
} else {
return 0;
}
}
}
private class DueComparator implements Comparator<long[]> {
@Override
public int compare(long[] lhs, long[] rhs) {
return new Long(lhs[0]).compareTo(rhs[0]);
}
}
}
| false | true | public float[] progressToday(TreeSet<Object[]> counts, Card card, boolean eta) {
try {
int doneCurrent = 0;
int[] leftCurrent = new int[]{0, 0, 0};
String[] cs = new String[]{"new", "lrn", "rev"};
long currentDid = 0;
// refresh deck progresses with fresh counts if necessary
if (counts != null || mCachedDeckCounts == null) {
if (mCachedDeckCounts == null) {
mCachedDeckCounts = new HashMap<Long, Pair<String[], long[]>>();
}
mCachedDeckCounts.clear();
if (counts == null) {
// reload counts
counts = (TreeSet<Object[]>)deckCounts()[0];
}
int done = 0;
for (Object[] d : counts) {
JSONObject deck = mCol.getDecks().get((Long) d[1]);
for (String s : cs) {
done += deck.getJSONArray(s + "Today").getInt(1);
}
mCachedDeckCounts.put((Long)d[1], new Pair<String[], long[]> ((String[])d[0], new long[]{done, (Integer)d[2], (Integer)d[3], (Integer)d[4]}));
}
}
// current selected deck
if (card != null) {
JSONObject deck = mCol.getDecks().current();
currentDid = deck.getLong("id");
for (String s : cs) {
doneCurrent += deck.getJSONArray(s + "Today").getInt(1);
}
int idx = countIdx(card);
leftCurrent = new int[]{ mNewCount + (idx == 1 ? 0 : 1), mLrnCount + (idx == 1 ? card.getLeft() / 1000 : 0), mRevCount + (idx == 1 ? 0 : 1)};
}
int doneAll = 0;
int[] leftAll = new int[]{0, 0, 0};
for (Map.Entry<Long, Pair<String[], long[]>> d : mCachedDeckCounts.entrySet()) {
boolean exclude = d.getKey() == currentDid; // || mCol.getDecks().isDyn(d.getKey());
if (d.getValue().first.length == 1) {
if (exclude) {
// don't count cached version of current deck
continue;
}
long[] c = d.getValue().second;
doneAll += c[0];
leftAll[0] += c[1];
leftAll[1] += c[2];
leftAll[2] += c[3];
} else if (exclude) {
// exclude cached values for current deck in order to avoid double count
long[] c = d.getValue().second;
doneAll -= c[0];
leftAll[0] -= c[1];
leftAll[1] -= c[2];
leftAll[2] -= c[3];
}
}
doneAll += doneCurrent;
leftAll[0] += leftCurrent[0];
leftAll[1] += leftCurrent[1];
leftAll[2] += leftCurrent[2];
int totalAll = doneAll + leftAll[0] + leftAll[1] + leftAll[2];
int totalCurrent = doneCurrent + leftCurrent[0] + leftCurrent[1] + leftCurrent[2];
float progressCurrent = -1;
if (totalCurrent != 0) {
progressCurrent = (float) doneCurrent / (float) totalCurrent;
}
float progressTotal = -1;
if (totalAll != 0) {
progressTotal = (float) doneAll / (float) totalAll;
}
return new float[]{ progressCurrent, progressTotal, totalAll - doneAll, eta ? eta(leftAll, false) : -1};
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
| public float[] progressToday(TreeSet<Object[]> counts, Card card, boolean eta) {
try {
int doneCurrent = 0;
int[] leftCurrent = new int[]{0, 0, 0};
String[] cs = new String[]{"new", "lrn", "rev"};
long currentDid = 0;
// refresh deck progresses with fresh counts if necessary
if (counts != null || mCachedDeckCounts == null) {
if (mCachedDeckCounts == null) {
mCachedDeckCounts = new HashMap<Long, Pair<String[], long[]>>();
}
mCachedDeckCounts.clear();
if (counts == null) {
// reload counts
counts = (TreeSet<Object[]>)deckCounts()[0];
}
for (Object[] d : counts) {
int done = 0;
JSONObject deck = mCol.getDecks().get((Long) d[1]);
for (String s : cs) {
done += deck.getJSONArray(s + "Today").getInt(1);
}
mCachedDeckCounts.put((Long)d[1], new Pair<String[], long[]> ((String[])d[0], new long[]{done, (Integer)d[2], (Integer)d[3], (Integer)d[4]}));
}
}
// current selected deck
if (card != null) {
JSONObject deck = mCol.getDecks().current();
currentDid = deck.getLong("id");
for (String s : cs) {
doneCurrent += deck.getJSONArray(s + "Today").getInt(1);
}
int idx = countIdx(card);
leftCurrent = new int[]{ mNewCount + (idx == 1 ? 0 : 1), mLrnCount + (idx == 1 ? card.getLeft() / 1000 : 0), mRevCount + (idx == 1 ? 0 : 1)};
}
int doneAll = 0;
int[] leftAll = new int[]{0, 0, 0};
for (Map.Entry<Long, Pair<String[], long[]>> d : mCachedDeckCounts.entrySet()) {
boolean exclude = d.getKey() == currentDid; // || mCol.getDecks().isDyn(d.getKey());
if (d.getValue().first.length == 1) {
if (exclude) {
// don't count cached version of current deck
continue;
}
long[] c = d.getValue().second;
doneAll += c[0];
leftAll[0] += c[1];
leftAll[1] += c[2];
leftAll[2] += c[3];
} else if (exclude) {
// exclude cached values for current deck in order to avoid double count
long[] c = d.getValue().second;
doneAll -= c[0];
leftAll[0] -= c[1];
leftAll[1] -= c[2];
leftAll[2] -= c[3];
}
}
doneAll += doneCurrent;
leftAll[0] += leftCurrent[0];
leftAll[1] += leftCurrent[1];
leftAll[2] += leftCurrent[2];
int totalAll = doneAll + leftAll[0] + leftAll[1] + leftAll[2];
int totalCurrent = doneCurrent + leftCurrent[0] + leftCurrent[1] + leftCurrent[2];
float progressCurrent = -1;
if (totalCurrent != 0) {
progressCurrent = (float) doneCurrent / (float) totalCurrent;
}
float progressTotal = -1;
if (totalAll != 0) {
progressTotal = (float) doneAll / (float) totalAll;
}
return new float[]{ progressCurrent, progressTotal, totalAll - doneAll, eta ? eta(leftAll, false) : -1};
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/com/android/contacts/list/DefaultContactListAdapter.java b/src/com/android/contacts/list/DefaultContactListAdapter.java
index bb49027df..007af6ce9 100644
--- a/src/com/android/contacts/list/DefaultContactListAdapter.java
+++ b/src/com/android/contacts/list/DefaultContactListAdapter.java
@@ -1,255 +1,259 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.list;
import com.android.contacts.preference.ContactsPreferences;
import android.content.ContentUris;
import android.content.Context;
import android.content.CursorLoader;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.net.Uri.Builder;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.GroupMembership;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.Directory;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.SearchSnippetColumns;
import android.text.TextUtils;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
/**
* A cursor adapter for the {@link ContactsContract.Contacts#CONTENT_TYPE} content type.
*/
public class DefaultContactListAdapter extends ContactListAdapter {
public static final char SNIPPET_START_MATCH = '\u0001';
public static final char SNIPPET_END_MATCH = '\u0001';
public static final String SNIPPET_ELLIPSIS = "\u2026";
public static final int SNIPPET_MAX_TOKENS = 5;
public static final String SNIPPET_ARGS = SNIPPET_START_MATCH + "," + SNIPPET_END_MATCH + ","
+ SNIPPET_ELLIPSIS + "," + SNIPPET_MAX_TOKENS;
public DefaultContactListAdapter(Context context) {
super(context);
}
@Override
public void configureLoader(CursorLoader loader, long directoryId) {
ContactListFilter filter = getFilter();
if (isSearchMode()) {
String query = getQueryString();
if (query == null) {
query = "";
}
query = query.trim();
if (TextUtils.isEmpty(query)) {
// Regardless of the directory, we don't want anything returned,
// so let's just send a "nothing" query to the local directory.
loader.setUri(Contacts.CONTENT_URI);
loader.setProjection(PROJECTION_CONTACT);
loader.setSelection("0");
} else {
Builder builder = Contacts.CONTENT_FILTER_URI.buildUpon();
builder.appendPath(query); // Builder will encode the query
builder.appendQueryParameter(ContactsContract.DIRECTORY_PARAM_KEY,
String.valueOf(directoryId));
if (directoryId != Directory.DEFAULT && directoryId != Directory.LOCAL_INVISIBLE) {
builder.appendQueryParameter(ContactsContract.LIMIT_PARAM_KEY,
String.valueOf(getDirectoryResultLimit()));
}
builder.appendQueryParameter(SearchSnippetColumns.SNIPPET_ARGS_PARAM_KEY,
SNIPPET_ARGS);
loader.setUri(builder.build());
loader.setProjection(FILTER_PROJECTION);
}
} else {
configureUri(loader, directoryId, filter);
configureProjection(loader, directoryId, filter);
configureSelection(loader, directoryId, filter);
}
String sortOrder;
if (getSortOrder() == ContactsContract.Preferences.SORT_ORDER_PRIMARY) {
sortOrder = Contacts.SORT_KEY_PRIMARY;
} else {
sortOrder = Contacts.SORT_KEY_ALTERNATIVE;
}
loader.setSortOrder(sortOrder);
}
protected void configureUri(CursorLoader loader, long directoryId, ContactListFilter filter) {
Uri uri = Contacts.CONTENT_URI;
if (filter != null) {
if (filter.filterType == ContactListFilter.FILTER_TYPE_GROUP) {
uri = Data.CONTENT_URI;
} else if (filter.filterType == ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
String lookupKey = getSelectedContactLookupKey();
if (lookupKey != null) {
uri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);
} else {
uri = ContentUris.withAppendedId(Contacts.CONTENT_URI, getSelectedContactId());
}
}
}
if (directoryId == Directory.DEFAULT && isSectionHeaderDisplayEnabled()) {
uri = buildSectionIndexerUri(uri);
}
// The "All accounts" filter is the same as the entire contents of Directory.DEFAULT
if (filter != null
&& filter.filterType != ContactListFilter.FILTER_TYPE_CUSTOM
&& filter.filterType != ContactListFilter.FILTER_TYPE_SINGLE_CONTACT) {
uri = uri.buildUpon().appendQueryParameter(
ContactsContract.DIRECTORY_PARAM_KEY, String.valueOf(Directory.DEFAULT))
.build();
}
// Include the user's personal profile.
if (shouldIncludeProfile()) {
uri = includeProfileEntry(uri);
}
loader.setUri(uri);
}
protected void configureProjection(
CursorLoader loader, long directoryId, ContactListFilter filter) {
if (filter != null && filter.filterType == ContactListFilter.FILTER_TYPE_GROUP) {
loader.setProjection(PROJECTION_DATA);
} else {
loader.setProjection(PROJECTION_CONTACT);
}
}
private void configureSelection(
CursorLoader loader, long directoryId, ContactListFilter filter) {
if (filter == null) {
return;
}
if (directoryId != Directory.DEFAULT) {
return;
}
StringBuilder selection = new StringBuilder();
List<String> selectionArgs = new ArrayList<String>();
switch (filter.filterType) {
case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: {
// We have already added directory=0 to the URI, which takes care of this
// filter
break;
}
case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: {
// We have already added the lookup key to the URI, which takes care of this
// filter
break;
}
case ContactListFilter.FILTER_TYPE_STARRED: {
selection.append(Contacts.STARRED + "!=0");
break;
}
case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: {
selection.append(Contacts.HAS_PHONE_NUMBER + "=1");
break;
}
case ContactListFilter.FILTER_TYPE_CUSTOM: {
selection.append(Contacts.IN_VISIBLE_GROUP + "=1");
if (isCustomFilterForPhoneNumbersOnly()) {
selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1");
}
break;
}
case ContactListFilter.FILTER_TYPE_ACCOUNT: {
- // TODO: avoid the use of private API
+ // TODO (stopship): avoid the use of private API
selection.append(
Contacts._ID + " IN ("
+ "SELECT DISTINCT " + RawContacts.CONTACT_ID
+ " FROM raw_contacts"
+ " WHERE " + RawContacts.ACCOUNT_TYPE + "=?"
+ " AND " + RawContacts.ACCOUNT_NAME + "=?");
selectionArgs.add(filter.accountType);
selectionArgs.add(filter.accountName);
if (filter.dataSet != null) {
selection.append(" AND " + RawContacts.DATA_SET + "=?");
selectionArgs.add(filter.dataSet);
} else {
selection.append(" AND " + RawContacts.DATA_SET + " IS NULL");
}
- selection.append(" OR " + Contacts.IS_USER_PROFILE + "=1)");
+ // TODO (stopship): And also this private API, which is even worse
+ selection.append(") OR " + Contacts._ID + "=(" +
+ "SELECT contact_id " +
+ "FROM raw_contacts rc inner join accounts a" +
+ " ON a.profile_raw_contact_id = rc._id)");
break;
}
case ContactListFilter.FILTER_TYPE_GROUP: {
selection.append(Data.MIMETYPE + "=?"
+ " AND " + GroupMembership.GROUP_ROW_ID + "=?");
selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE);
selectionArgs.add(String.valueOf(filter.groupId));
break;
}
}
loader.setSelection(selection.toString());
loader.setSelectionArgs(selectionArgs.toArray(new String[0]));
}
@Override
protected void bindView(View itemView, int partition, Cursor cursor, int position) {
final ContactListItemView view = (ContactListItemView)itemView;
view.setHighlightedPrefix(isSearchMode() ? getUpperCaseQueryString() : null);
if (isSelectionVisible()) {
view.setActivated(isSelectedContact(partition, cursor));
}
bindSectionHeaderAndDivider(view, position, cursor);
if (isQuickContactEnabled()) {
bindQuickContact(view, partition, cursor,
CONTACT_PHOTO_ID_COLUMN_INDEX, CONTACT_ID_COLUMN_INDEX,
CONTACT_LOOKUP_KEY_COLUMN_INDEX);
} else {
bindPhoto(view, partition, cursor);
}
bindName(view, cursor);
bindPresenceAndStatusMessage(view, cursor);
if (isSearchMode()) {
bindSearchSnippet(view, cursor);
} else {
view.setSnippet(null);
}
}
private boolean isCustomFilterForPhoneNumbersOnly() {
// TODO: this flag should not be stored in shared prefs. It needs to be in the db.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
return prefs.getBoolean(ContactsPreferences.PREF_DISPLAY_ONLY_PHONES,
ContactsPreferences.PREF_DISPLAY_ONLY_PHONES_DEFAULT);
}
}
| false | true | private void configureSelection(
CursorLoader loader, long directoryId, ContactListFilter filter) {
if (filter == null) {
return;
}
if (directoryId != Directory.DEFAULT) {
return;
}
StringBuilder selection = new StringBuilder();
List<String> selectionArgs = new ArrayList<String>();
switch (filter.filterType) {
case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: {
// We have already added directory=0 to the URI, which takes care of this
// filter
break;
}
case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: {
// We have already added the lookup key to the URI, which takes care of this
// filter
break;
}
case ContactListFilter.FILTER_TYPE_STARRED: {
selection.append(Contacts.STARRED + "!=0");
break;
}
case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: {
selection.append(Contacts.HAS_PHONE_NUMBER + "=1");
break;
}
case ContactListFilter.FILTER_TYPE_CUSTOM: {
selection.append(Contacts.IN_VISIBLE_GROUP + "=1");
if (isCustomFilterForPhoneNumbersOnly()) {
selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1");
}
break;
}
case ContactListFilter.FILTER_TYPE_ACCOUNT: {
// TODO: avoid the use of private API
selection.append(
Contacts._ID + " IN ("
+ "SELECT DISTINCT " + RawContacts.CONTACT_ID
+ " FROM raw_contacts"
+ " WHERE " + RawContacts.ACCOUNT_TYPE + "=?"
+ " AND " + RawContacts.ACCOUNT_NAME + "=?");
selectionArgs.add(filter.accountType);
selectionArgs.add(filter.accountName);
if (filter.dataSet != null) {
selection.append(" AND " + RawContacts.DATA_SET + "=?");
selectionArgs.add(filter.dataSet);
} else {
selection.append(" AND " + RawContacts.DATA_SET + " IS NULL");
}
selection.append(" OR " + Contacts.IS_USER_PROFILE + "=1)");
break;
}
case ContactListFilter.FILTER_TYPE_GROUP: {
selection.append(Data.MIMETYPE + "=?"
+ " AND " + GroupMembership.GROUP_ROW_ID + "=?");
selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE);
selectionArgs.add(String.valueOf(filter.groupId));
break;
}
}
loader.setSelection(selection.toString());
loader.setSelectionArgs(selectionArgs.toArray(new String[0]));
}
| private void configureSelection(
CursorLoader loader, long directoryId, ContactListFilter filter) {
if (filter == null) {
return;
}
if (directoryId != Directory.DEFAULT) {
return;
}
StringBuilder selection = new StringBuilder();
List<String> selectionArgs = new ArrayList<String>();
switch (filter.filterType) {
case ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS: {
// We have already added directory=0 to the URI, which takes care of this
// filter
break;
}
case ContactListFilter.FILTER_TYPE_SINGLE_CONTACT: {
// We have already added the lookup key to the URI, which takes care of this
// filter
break;
}
case ContactListFilter.FILTER_TYPE_STARRED: {
selection.append(Contacts.STARRED + "!=0");
break;
}
case ContactListFilter.FILTER_TYPE_WITH_PHONE_NUMBERS_ONLY: {
selection.append(Contacts.HAS_PHONE_NUMBER + "=1");
break;
}
case ContactListFilter.FILTER_TYPE_CUSTOM: {
selection.append(Contacts.IN_VISIBLE_GROUP + "=1");
if (isCustomFilterForPhoneNumbersOnly()) {
selection.append(" AND " + Contacts.HAS_PHONE_NUMBER + "=1");
}
break;
}
case ContactListFilter.FILTER_TYPE_ACCOUNT: {
// TODO (stopship): avoid the use of private API
selection.append(
Contacts._ID + " IN ("
+ "SELECT DISTINCT " + RawContacts.CONTACT_ID
+ " FROM raw_contacts"
+ " WHERE " + RawContacts.ACCOUNT_TYPE + "=?"
+ " AND " + RawContacts.ACCOUNT_NAME + "=?");
selectionArgs.add(filter.accountType);
selectionArgs.add(filter.accountName);
if (filter.dataSet != null) {
selection.append(" AND " + RawContacts.DATA_SET + "=?");
selectionArgs.add(filter.dataSet);
} else {
selection.append(" AND " + RawContacts.DATA_SET + " IS NULL");
}
// TODO (stopship): And also this private API, which is even worse
selection.append(") OR " + Contacts._ID + "=(" +
"SELECT contact_id " +
"FROM raw_contacts rc inner join accounts a" +
" ON a.profile_raw_contact_id = rc._id)");
break;
}
case ContactListFilter.FILTER_TYPE_GROUP: {
selection.append(Data.MIMETYPE + "=?"
+ " AND " + GroupMembership.GROUP_ROW_ID + "=?");
selectionArgs.add(GroupMembership.CONTENT_ITEM_TYPE);
selectionArgs.add(String.valueOf(filter.groupId));
break;
}
}
loader.setSelection(selection.toString());
loader.setSelectionArgs(selectionArgs.toArray(new String[0]));
}
|
diff --git a/src/sai_cas/servlet/CrossMatchServlet.java b/src/sai_cas/servlet/CrossMatchServlet.java
index dffa79e..ca11135 100644
--- a/src/sai_cas/servlet/CrossMatchServlet.java
+++ b/src/sai_cas/servlet/CrossMatchServlet.java
@@ -1,287 +1,287 @@
package sai_cas.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.File;
import java.util.List;
import java.util.Calendar;
import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.*;
import sai_cas.VOTABLEFile.VOTABLE;
import sai_cas.VOTABLEFile.Votable;
import sai_cas.VOTABLEFile.VotableException;
import sai_cas.db.*;
import sai_cas.output.CSVQueryResultsOutputter;
import sai_cas.output.QueryResultsOutputter;
import sai_cas.output.VOTableQueryResultsOutputter;
import sai_cas.vo.*;
public class CrossMatchServlet extends HttpServlet {
static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("sai_cas.CrossMatchServlet");
public enum formats {VOTABLE, CSV};
public class CrossMatchServletException extends Exception
{
CrossMatchServletException()
{
super();
}
CrossMatchServletException(String s)
{
super(s);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
PrintWriter out = response.getWriter();
String cat = null, tab = null, radString = null, raColumn = null,
decColumn = null, formatString = null;
formats format;
List<FileItem> fileItemList = null;
FileItemFactory factory = new DiskFileItemFactory();
try
{
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setSizeMax(50000000);
/* Request size <= 50Mb */
fileItemList = sfu.parseRequest(request);
}
catch (FileUploadException e)
{
throw new ServletException(e.getMessage());
/* Nothing ...*/
}
FileItem fi = null;
for (FileItem fi0: fileItemList)
{
if (fi0.getFieldName().equals("file"))//(!fi0.isFormField())
{
fi = fi0;
}
if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField())
{
tab = fi0.getString();
}
if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField())
{
cat = fi0.getString();
}
if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField())
{
radString = fi0.getString();
}
if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField())
{
raColumn = fi0.getString();
}
if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField())
{
decColumn = fi0.getString();
}
if (fi0.getFieldName().equals("format"))//(!fi0.isFormField())
{
formatString = fi0.getString();
}
}
if ((formatString==null)||(formatString.equalsIgnoreCase("votable")))
{
format = formats.VOTABLE;
}
else if (formatString.equalsIgnoreCase("CSV"))
{
format = formats.CSV;
}
else
{
format = formats.VOTABLE;
}
QueryResultsOutputter qro = null;
CSVQueryResultsOutputter csvqro = null;
VOTableQueryResultsOutputter voqro = null;
switch (format)
{
case CSV:
response.setContentType("text/csv");
csvqro = new CSVQueryResultsOutputter();
qro = csvqro;
break;
case VOTABLE:
response.setContentType("text/xml");
voqro = new VOTableQueryResultsOutputter();
qro = voqro;
break;
}
File uploadedFile = null;
Connection conn = null;
DBInterface dbi = null;
try
{
double rad = 0;
rad = Double.parseDouble(radString);
if (fi == null)
{
throw new ServletException("File should be specified" + fileItemList.size() );
}
long size = fi.getSize();
if (size > 10000000)
{
throw new CrossMatchServletException("File is too big");
}
if (size == 0)
{
throw new CrossMatchServletException("File must not be empty");
}
if (format.equals(formats.CSV))
{
if ((raColumn==null)||(decColumn==null))
{
throw new CrossMatchServletException("When you use the CSV format, you must specify which columns contain RA and DEC");
}
}
uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/"));
try
{
fi.write(uploadedFile);
}
catch (Exception e)
{
throw new CrossMatchServletException("Error in writing your data in the temporary file");
}
logger.debug("File written");
- String userPasswd = dbi.getDefaultTempDBUserPasswd();
+ String[] userPasswd = dbi.getDefaultTempDBUserPasswd();
String tempUser = userPasswd[0];
String tempPasswd = userPasswd[1];
conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd);
dbi = new DBInterface(conn,tempUser);
Votable vot = null;
switch (format)
{
case CSV:
vot = Votable.getVOTableFromCSV(uploadedFile);
if ((!vot.checkColumnExistance(raColumn)) ||
(!vot.checkColumnExistance(decColumn)))
{
throw new CrossMatchServletException("The column names specified as RA and DEC should be present in the CSV file");
}
break;
case VOTABLE:
vot = new Votable (uploadedFile);
break;
}
String userDataSchema = dbi.getUserDataSchemaName();
String tableName = vot.insertDataToDB(dbi,userDataSchema);
dbi.analyze(userDataSchema, tableName);
String[] raDecArray = dbi.getRaDecColumns(cat, tab);
String[] raDecArray1 = null;
switch(format)
{
case VOTABLE:
raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema,
tableName);
if (raDecArray1 == null)
{
throw new CrossMatchServletException( "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch");
}
break;
case CSV:
raDecArray1 = new String[2];
raDecArray1[0] = raColumn;
raDecArray1[1] = decColumn;
}
response.setHeader("Content-Disposition",
"attachment; filename=" + cat + "_" +
fi.getName() + "_" + String.valueOf(rad) + ".dat");
dbi.executeQuery("select * from " + userDataSchema + "." + tableName +
" AS a LEFT JOIN " + cat + "." + tab + " AS b "+
"ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+
raDecArray[0]+",b."+raDecArray[1]+","+rad+")");
if (format.equals(formats.VOTABLE))
{
voqro.setResource(cat + "_" + fi.getName() );
voqro.setResourceDescription("This is the table obtained by "+
"crossmatching the table "+cat+"."+tab + " with the " +
"user supplied table from the file " + fi.getName()+"\n"+
"Radius of the crossmatch: "+rad+"deg");
voqro.setTable("main" );
}
qro.print(out,dbi);
}
catch (VotableException e)
{
qro.printError(out, "Error occured: "+ e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)");
}
catch (NumberFormatException e)
{
qro.printError(out, "Error occured: " + e.getMessage());
}
catch (CrossMatchServletException e)
{
qro.printError(out, "Error occured: " + e.getMessage());
}
catch (DBException e)
{
logger.error("DBException " + e);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw);
}
catch (SQLException e)
{
logger.error("SQLException "+e);
StringWriter sw =new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
qro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw);
}
finally
{
DBInterface.close(dbi,conn,false);
/* Always rollback */
try
{
uploadedFile.delete();
}
catch (Exception e)
{
}
}
}
}
| true | true | public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
PrintWriter out = response.getWriter();
String cat = null, tab = null, radString = null, raColumn = null,
decColumn = null, formatString = null;
formats format;
List<FileItem> fileItemList = null;
FileItemFactory factory = new DiskFileItemFactory();
try
{
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setSizeMax(50000000);
/* Request size <= 50Mb */
fileItemList = sfu.parseRequest(request);
}
catch (FileUploadException e)
{
throw new ServletException(e.getMessage());
/* Nothing ...*/
}
FileItem fi = null;
for (FileItem fi0: fileItemList)
{
if (fi0.getFieldName().equals("file"))//(!fi0.isFormField())
{
fi = fi0;
}
if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField())
{
tab = fi0.getString();
}
if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField())
{
cat = fi0.getString();
}
if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField())
{
radString = fi0.getString();
}
if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField())
{
raColumn = fi0.getString();
}
if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField())
{
decColumn = fi0.getString();
}
if (fi0.getFieldName().equals("format"))//(!fi0.isFormField())
{
formatString = fi0.getString();
}
}
if ((formatString==null)||(formatString.equalsIgnoreCase("votable")))
{
format = formats.VOTABLE;
}
else if (formatString.equalsIgnoreCase("CSV"))
{
format = formats.CSV;
}
else
{
format = formats.VOTABLE;
}
QueryResultsOutputter qro = null;
CSVQueryResultsOutputter csvqro = null;
VOTableQueryResultsOutputter voqro = null;
switch (format)
{
case CSV:
response.setContentType("text/csv");
csvqro = new CSVQueryResultsOutputter();
qro = csvqro;
break;
case VOTABLE:
response.setContentType("text/xml");
voqro = new VOTableQueryResultsOutputter();
qro = voqro;
break;
}
File uploadedFile = null;
Connection conn = null;
DBInterface dbi = null;
try
{
double rad = 0;
rad = Double.parseDouble(radString);
if (fi == null)
{
throw new ServletException("File should be specified" + fileItemList.size() );
}
long size = fi.getSize();
if (size > 10000000)
{
throw new CrossMatchServletException("File is too big");
}
if (size == 0)
{
throw new CrossMatchServletException("File must not be empty");
}
if (format.equals(formats.CSV))
{
if ((raColumn==null)||(decColumn==null))
{
throw new CrossMatchServletException("When you use the CSV format, you must specify which columns contain RA and DEC");
}
}
uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/"));
try
{
fi.write(uploadedFile);
}
catch (Exception e)
{
throw new CrossMatchServletException("Error in writing your data in the temporary file");
}
logger.debug("File written");
String userPasswd = dbi.getDefaultTempDBUserPasswd();
String tempUser = userPasswd[0];
String tempPasswd = userPasswd[1];
conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd);
dbi = new DBInterface(conn,tempUser);
Votable vot = null;
switch (format)
{
case CSV:
vot = Votable.getVOTableFromCSV(uploadedFile);
if ((!vot.checkColumnExistance(raColumn)) ||
(!vot.checkColumnExistance(decColumn)))
{
throw new CrossMatchServletException("The column names specified as RA and DEC should be present in the CSV file");
}
break;
case VOTABLE:
vot = new Votable (uploadedFile);
break;
}
String userDataSchema = dbi.getUserDataSchemaName();
String tableName = vot.insertDataToDB(dbi,userDataSchema);
dbi.analyze(userDataSchema, tableName);
String[] raDecArray = dbi.getRaDecColumns(cat, tab);
String[] raDecArray1 = null;
switch(format)
{
case VOTABLE:
raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema,
tableName);
if (raDecArray1 == null)
{
throw new CrossMatchServletException( "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch");
}
break;
case CSV:
raDecArray1 = new String[2];
raDecArray1[0] = raColumn;
raDecArray1[1] = decColumn;
}
response.setHeader("Content-Disposition",
"attachment; filename=" + cat + "_" +
fi.getName() + "_" + String.valueOf(rad) + ".dat");
dbi.executeQuery("select * from " + userDataSchema + "." + tableName +
" AS a LEFT JOIN " + cat + "." + tab + " AS b "+
"ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+
raDecArray[0]+",b."+raDecArray[1]+","+rad+")");
if (format.equals(formats.VOTABLE))
{
voqro.setResource(cat + "_" + fi.getName() );
voqro.setResourceDescription("This is the table obtained by "+
"crossmatching the table "+cat+"."+tab + " with the " +
"user supplied table from the file " + fi.getName()+"\n"+
"Radius of the crossmatch: "+rad+"deg");
voqro.setTable("main" );
}
qro.print(out,dbi);
}
catch (VotableException e)
{
qro.printError(out, "Error occured: "+ e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)");
}
catch (NumberFormatException e)
{
qro.printError(out, "Error occured: " + e.getMessage());
}
catch (CrossMatchServletException e)
{
qro.printError(out, "Error occured: " + e.getMessage());
}
catch (DBException e)
{
logger.error("DBException " + e);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw);
}
catch (SQLException e)
{
logger.error("SQLException "+e);
StringWriter sw =new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
qro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw);
}
finally
{
DBInterface.close(dbi,conn,false);
/* Always rollback */
try
{
uploadedFile.delete();
}
catch (Exception e)
{
}
}
}
| public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
PrintWriter out = response.getWriter();
String cat = null, tab = null, radString = null, raColumn = null,
decColumn = null, formatString = null;
formats format;
List<FileItem> fileItemList = null;
FileItemFactory factory = new DiskFileItemFactory();
try
{
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setSizeMax(50000000);
/* Request size <= 50Mb */
fileItemList = sfu.parseRequest(request);
}
catch (FileUploadException e)
{
throw new ServletException(e.getMessage());
/* Nothing ...*/
}
FileItem fi = null;
for (FileItem fi0: fileItemList)
{
if (fi0.getFieldName().equals("file"))//(!fi0.isFormField())
{
fi = fi0;
}
if (fi0.getFieldName().equals("tab"))//(!fi0.isFormField())
{
tab = fi0.getString();
}
if (fi0.getFieldName().equals("cat"))//(!fi0.isFormField())
{
cat = fi0.getString();
}
if (fi0.getFieldName().equals("rad"))//(!fi0.isFormField())
{
radString = fi0.getString();
}
if (fi0.getFieldName().equals("racol"))//(!fi0.isFormField())
{
raColumn = fi0.getString();
}
if (fi0.getFieldName().equals("deccol"))//(!fi0.isFormField())
{
decColumn = fi0.getString();
}
if (fi0.getFieldName().equals("format"))//(!fi0.isFormField())
{
formatString = fi0.getString();
}
}
if ((formatString==null)||(formatString.equalsIgnoreCase("votable")))
{
format = formats.VOTABLE;
}
else if (formatString.equalsIgnoreCase("CSV"))
{
format = formats.CSV;
}
else
{
format = formats.VOTABLE;
}
QueryResultsOutputter qro = null;
CSVQueryResultsOutputter csvqro = null;
VOTableQueryResultsOutputter voqro = null;
switch (format)
{
case CSV:
response.setContentType("text/csv");
csvqro = new CSVQueryResultsOutputter();
qro = csvqro;
break;
case VOTABLE:
response.setContentType("text/xml");
voqro = new VOTableQueryResultsOutputter();
qro = voqro;
break;
}
File uploadedFile = null;
Connection conn = null;
DBInterface dbi = null;
try
{
double rad = 0;
rad = Double.parseDouble(radString);
if (fi == null)
{
throw new ServletException("File should be specified" + fileItemList.size() );
}
long size = fi.getSize();
if (size > 10000000)
{
throw new CrossMatchServletException("File is too big");
}
if (size == 0)
{
throw new CrossMatchServletException("File must not be empty");
}
if (format.equals(formats.CSV))
{
if ((raColumn==null)||(decColumn==null))
{
throw new CrossMatchServletException("When you use the CSV format, you must specify which columns contain RA and DEC");
}
}
uploadedFile = File.createTempFile("crossmatch",".dat",new File("/tmp/"));
try
{
fi.write(uploadedFile);
}
catch (Exception e)
{
throw new CrossMatchServletException("Error in writing your data in the temporary file");
}
logger.debug("File written");
String[] userPasswd = dbi.getDefaultTempDBUserPasswd();
String tempUser = userPasswd[0];
String tempPasswd = userPasswd[1];
conn = DBConnection.getPooledPerUserConnection(tempUser, tempPasswd);
dbi = new DBInterface(conn,tempUser);
Votable vot = null;
switch (format)
{
case CSV:
vot = Votable.getVOTableFromCSV(uploadedFile);
if ((!vot.checkColumnExistance(raColumn)) ||
(!vot.checkColumnExistance(decColumn)))
{
throw new CrossMatchServletException("The column names specified as RA and DEC should be present in the CSV file");
}
break;
case VOTABLE:
vot = new Votable (uploadedFile);
break;
}
String userDataSchema = dbi.getUserDataSchemaName();
String tableName = vot.insertDataToDB(dbi,userDataSchema);
dbi.analyze(userDataSchema, tableName);
String[] raDecArray = dbi.getRaDecColumns(cat, tab);
String[] raDecArray1 = null;
switch(format)
{
case VOTABLE:
raDecArray1 = dbi.getRaDecColumnsFromUCD(userDataSchema,
tableName);
if (raDecArray1 == null)
{
throw new CrossMatchServletException( "Error occured: " + "You must have the columns in the table having the UCD of alpha or delta ('POS_EQ_RA_MAIN', 'POS_EQ_DEC_MAIN') to do the crossmatch");
}
break;
case CSV:
raDecArray1 = new String[2];
raDecArray1[0] = raColumn;
raDecArray1[1] = decColumn;
}
response.setHeader("Content-Disposition",
"attachment; filename=" + cat + "_" +
fi.getName() + "_" + String.valueOf(rad) + ".dat");
dbi.executeQuery("select * from " + userDataSchema + "." + tableName +
" AS a LEFT JOIN " + cat + "." + tab + " AS b "+
"ON q3c_join(a."+raDecArray1[0]+",a."+raDecArray1[1]+",b."+
raDecArray[0]+",b."+raDecArray[1]+","+rad+")");
if (format.equals(formats.VOTABLE))
{
voqro.setResource(cat + "_" + fi.getName() );
voqro.setResourceDescription("This is the table obtained by "+
"crossmatching the table "+cat+"."+tab + " with the " +
"user supplied table from the file " + fi.getName()+"\n"+
"Radius of the crossmatch: "+rad+"deg");
voqro.setTable("main" );
}
qro.print(out,dbi);
}
catch (VotableException e)
{
qro.printError(out, "Error occured: "+ e.getMessage() + "Cannot read the VOTable, probably it is not well formed (remember that you must have 'xmlns=\"http://www.ivoa.net/xml/VOTable/v1.1\"' in the VOTABLE tag)");
}
catch (NumberFormatException e)
{
qro.printError(out, "Error occured: " + e.getMessage());
}
catch (CrossMatchServletException e)
{
qro.printError(out, "Error occured: " + e.getMessage());
}
catch (DBException e)
{
logger.error("DBException " + e);
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
qro.printError(out, "Error occured: " + e + "\nCause: " + e.getCause() + "\nTrace: " + sw);
}
catch (SQLException e)
{
logger.error("SQLException "+e);
StringWriter sw =new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
qro.printError(out, "Error occured: " + e +"\nCause: " +e.getCause()+"\nTrace: "+sw);
}
finally
{
DBInterface.close(dbi,conn,false);
/* Always rollback */
try
{
uploadedFile.delete();
}
catch (Exception e)
{
}
}
}
|
diff --git a/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java b/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
index 29c4756380..2a77d06f64 100644
--- a/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
+++ b/drools-analytics/src/test/java/org/drools/analytics/ConsequenceTest.java
@@ -1,63 +1,63 @@
package org.drools.analytics;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.drools.StatelessSession;
import org.drools.analytics.components.AnalyticsRule;
import org.drools.analytics.dao.AnalyticsDataFactory;
import org.drools.analytics.dao.AnalyticsResult;
import org.drools.analytics.report.components.AnalyticsMessage;
import org.drools.analytics.report.components.AnalyticsMessageBase;
import org.drools.base.RuleNameMatchesAgendaFilter;
/**
*
* @author Toni Rikkola
*
*/
public class ConsequenceTest extends TestBase {
public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
- AnalyticsDataFactory.getAnalyticsData();
+ AnalyticsDataFactory.clearAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
}
| true | true | public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
AnalyticsDataFactory.getAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
| public void testMissingConsequence() throws Exception {
StatelessSession session = getStatelessSession(this.getClass()
.getResourceAsStream("Consequence.drl"));
session.setAgendaFilter(new RuleNameMatchesAgendaFilter(
"No action - possibly commented out"));
AnalyticsDataFactory.clearAnalyticsData();
Collection<? extends Object> testData = getTestData(this.getClass()
.getResourceAsStream("ConsequenceTest.drl"));
AnalyticsDataFactory.clearAnalyticsResult();
AnalyticsResult result = AnalyticsDataFactory.getAnalyticsResult();
session.setGlobal("result", result);
session.executeWithResults(testData);
Iterator<AnalyticsMessageBase> iter = result.getBySeverity(
AnalyticsMessageBase.Severity.WARNING).iterator();
Set<String> rulesThatHadErrors = new HashSet<String>();
while (iter.hasNext()) {
Object o = (Object) iter.next();
if (o instanceof AnalyticsMessage) {
AnalyticsRule rule = (AnalyticsRule) ((AnalyticsMessage) o)
.getFaulty();
rulesThatHadErrors.add(rule.getRuleName());
}
}
assertFalse(rulesThatHadErrors.contains("Has a consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 1"));
assertTrue(rulesThatHadErrors.remove("Missing consequence 2"));
if (!rulesThatHadErrors.isEmpty()) {
for (String string : rulesThatHadErrors) {
fail("Rule " + string + " caused an error.");
}
}
}
|
diff --git a/portal-core/src/test/java/org/devproof/portal/core/module/user/page/RegisterPageTest.java b/portal-core/src/test/java/org/devproof/portal/core/module/user/page/RegisterPageTest.java
index ba157ee8..ce6097c3 100644
--- a/portal-core/src/test/java/org/devproof/portal/core/module/user/page/RegisterPageTest.java
+++ b/portal-core/src/test/java/org/devproof/portal/core/module/user/page/RegisterPageTest.java
@@ -1,82 +1,82 @@
/*
* Copyright 2009-2010 Carsten Hufe devproof.org
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.devproof.portal.core.module.user.page;
import org.apache.wicket.Page;
import org.apache.wicket.util.tester.FormTester;
import org.apache.wicket.util.tester.WicketTester;
import org.devproof.portal.core.app.PortalSession;
import org.devproof.portal.core.module.common.page.MessagePage;
import org.devproof.portal.core.module.right.entity.Right;
import org.devproof.portal.test.MockContextLoader;
import org.devproof.portal.test.PortalTestUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.servlet.ServletContext;
/**
* @author Carsten Hufe
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = MockContextLoader.class,
locations = {"classpath:/org/devproof/portal/core/test-datasource.xml" })
public class RegisterPageTest {
@Autowired
private ServletContext servletContext;
private WicketTester tester;
@Before
public void setUp() throws Exception {
tester = PortalTestUtil.createWicketTester(servletContext);
}
@After
public void tearDown() throws Exception {
PortalTestUtil.destroy(tester);
}
@Test
public void testRenderDefaultPage() {
tester.startPage(RegisterPage.class);
tester.assertRenderedPage(RegisterPage.class);
}
@Test
public void testRegistration() {
Page page = tester.startPage(RegisterPage.class);
tester.assertRenderedPage(RegisterPage.class);
PortalSession.get().getRights().add(new Right("captcha.disabled"));
FormTester ft = tester.newFormTester("form");
- ft.setValue("username", "peterpan");
+ ft.setValue("username", "peterpan123");
ft.setValue("firstname", "mike");
ft.setValue("lastname", "jack");
ft.setValue("email", "[email protected]");
ft.setValue("birthday", "1981-10-13");
ft.setValue("password1", "testing");
ft.setValue("password2", "testing");
ft.setValue("termsOfUse", true);
tester.executeAjaxEvent("form:registerButton", "onclick");
tester.assertNoErrorMessage();
tester.assertRenderedPage(MessagePage.class);
tester.assertContains(page.getString("confirm.email"));
}
}
| true | true | public void testRegistration() {
Page page = tester.startPage(RegisterPage.class);
tester.assertRenderedPage(RegisterPage.class);
PortalSession.get().getRights().add(new Right("captcha.disabled"));
FormTester ft = tester.newFormTester("form");
ft.setValue("username", "peterpan");
ft.setValue("firstname", "mike");
ft.setValue("lastname", "jack");
ft.setValue("email", "[email protected]");
ft.setValue("birthday", "1981-10-13");
ft.setValue("password1", "testing");
ft.setValue("password2", "testing");
ft.setValue("termsOfUse", true);
tester.executeAjaxEvent("form:registerButton", "onclick");
tester.assertNoErrorMessage();
tester.assertRenderedPage(MessagePage.class);
tester.assertContains(page.getString("confirm.email"));
}
| public void testRegistration() {
Page page = tester.startPage(RegisterPage.class);
tester.assertRenderedPage(RegisterPage.class);
PortalSession.get().getRights().add(new Right("captcha.disabled"));
FormTester ft = tester.newFormTester("form");
ft.setValue("username", "peterpan123");
ft.setValue("firstname", "mike");
ft.setValue("lastname", "jack");
ft.setValue("email", "[email protected]");
ft.setValue("birthday", "1981-10-13");
ft.setValue("password1", "testing");
ft.setValue("password2", "testing");
ft.setValue("termsOfUse", true);
tester.executeAjaxEvent("form:registerButton", "onclick");
tester.assertNoErrorMessage();
tester.assertRenderedPage(MessagePage.class);
tester.assertContains(page.getString("confirm.email"));
}
|
diff --git a/src/org/python/modules/operator.java b/src/org/python/modules/operator.java
index 7d9e3480..542b8f34 100644
--- a/src/org/python/modules/operator.java
+++ b/src/org/python/modules/operator.java
@@ -1,396 +1,396 @@
// Copyright (c) Corporation for National Research Initiatives
package org.python.modules;
import org.python.core.*;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
class OperatorFunctions extends PyBuiltinFunctionSet
{
public OperatorFunctions(String name, int index, int argcount) {
this(name, index, argcount, argcount);
}
public OperatorFunctions(String name, int index, int minargs, int maxargs)
{
super(name, index, minargs, maxargs);
}
public PyObject __call__(PyObject arg1) {
switch (index) {
case 10: return arg1.__abs__();
case 11: return arg1.__invert__();
case 12: return arg1.__neg__();
case 13: return arg1.__not__();
case 14: return arg1.__pos__();
case 15: return Py.newBoolean(arg1.__nonzero__());
case 16: return Py.newBoolean(arg1.isCallable());
case 17: return Py.newBoolean(arg1.isMappingType());
case 18: return Py.newBoolean(arg1.isNumberType());
case 19: return Py.newBoolean(arg1.isSequenceType());
case 32: return arg1.__invert__();
case 52: return arg1.__index__();
default:
throw info.unexpectedCall(1, false);
}
}
public PyObject __call__(PyObject arg1, PyObject arg2) {
switch (index) {
case 0: return arg1._add(arg2);
case 1: return arg1._and(arg2);
case 2: return arg1._div(arg2);
case 3: return arg1._lshift(arg2);
case 4: return arg1._mod(arg2);
case 5: return arg1._mul(arg2);
case 6: return arg1._or(arg2);
case 7: return arg1._rshift(arg2);
case 8: return arg1._sub(arg2);
case 9: return arg1._xor(arg2);
case 20: return Py.newBoolean(arg1.__contains__(arg2));
case 21:
arg1.__delitem__(arg2);
return Py.None;
case 23: return arg1.__getitem__(arg2);
case 27: return arg1._ge(arg2);
case 28: return arg1._le(arg2);
case 29: return arg1._eq(arg2);
case 30: return arg1._floordiv(arg2);
case 31: return arg1._gt(arg2);
case 33: return arg1._lt(arg2);
case 34: return arg1._ne(arg2);
case 35: return arg1._truediv(arg2);
case 36: return arg1._pow(arg2);
case 37: return arg1._is(arg2);
case 38: return arg1._isnot(arg2);
case 39: return arg1._iadd(arg2);
case 40: return arg1._iand(arg2);
case 41: return arg1._idiv(arg2);
case 42: return arg1._ifloordiv(arg2);
case 43: return arg1._ilshift(arg2);
case 44: return arg1._imod(arg2);
case 45: return arg1._imul(arg2);
case 46: return arg1._ior(arg2);
case 47: return arg1._ipow(arg2);
case 48: return arg1._irshift(arg2);
case 49: return arg1._isub(arg2);
case 50: return arg1._itruediv(arg2);
case 51: return arg1._ixor(arg2);
default:
throw info.unexpectedCall(2, false);
}
}
public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) {
switch (index) {
case 22: arg1.__delslice__(arg2.__index__(), arg3.__index__()); return Py.None;
case 24: return arg1.__getslice__(arg2.__index__(), arg3.__index__());
case 25: arg1.__setitem__(arg2, arg3); return Py.None;
default:
throw info.unexpectedCall(3, false);
}
}
public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3,
PyObject arg4)
{
switch (index) {
case 26:
arg1.__setslice__(arg2.__index__(), arg3.__index__(), arg4);
return Py.None;
default:
throw info.unexpectedCall(4, false);
}
}
}
public class operator implements ClassDictInit
{
public static PyString __doc__ = new PyString(
"Operator interface.\n"+
"\n"+
"This module exports a set of functions implemented in C "+
"corresponding\n"+
"to the intrinsic operators of Python. For example, "+
"operator.add(x, y)\n"+
"is equivalent to the expression x+y. The function names "+
"are those\n"+
"used for special class methods; variants without leading "+
"and trailing\n"+
"'__' are also provided for convenience.\n"
);
public static void classDictInit(PyObject dict) throws PyIgnoreMethodTag {
dict.__setitem__("__add__", new OperatorFunctions("__add__", 0, 2));
dict.__setitem__("add", new OperatorFunctions("add", 0, 2));
dict.__setitem__("__concat__",
new OperatorFunctions("__concat__", 0, 2));
dict.__setitem__("concat", new OperatorFunctions("concat", 0, 2));
dict.__setitem__("__and__", new OperatorFunctions("__and__", 1, 2));
dict.__setitem__("and_", new OperatorFunctions("and_", 1, 2));
dict.__setitem__("__div__", new OperatorFunctions("__div__", 2, 2));
dict.__setitem__("div", new OperatorFunctions("div", 2, 2));
dict.__setitem__("__lshift__",
new OperatorFunctions("__lshift__", 3, 2));
dict.__setitem__("lshift", new OperatorFunctions("lshift", 3, 2));
dict.__setitem__("__mod__", new OperatorFunctions("__mod__", 4, 2));
dict.__setitem__("mod", new OperatorFunctions("mod", 4, 2));
dict.__setitem__("__mul__", new OperatorFunctions("__mul__", 5, 2));
dict.__setitem__("mul", new OperatorFunctions("mul", 5, 2));
dict.__setitem__("__repeat__",
new OperatorFunctions("__repeat__", 5, 2));
dict.__setitem__("repeat", new OperatorFunctions("repeat", 5, 2));
dict.__setitem__("__or__", new OperatorFunctions("__or__", 6, 2));
dict.__setitem__("or_", new OperatorFunctions("or_", 6, 2));
dict.__setitem__("__rshift__",
new OperatorFunctions("__rshift__", 7, 2));
dict.__setitem__("rshift", new OperatorFunctions("rshift", 7, 2));
dict.__setitem__("__sub__", new OperatorFunctions("__sub__", 8, 2));
dict.__setitem__("sub", new OperatorFunctions("sub", 8, 2));
dict.__setitem__("__xor__", new OperatorFunctions("__xor__", 9, 2));
dict.__setitem__("xor", new OperatorFunctions("xor", 9, 2));
dict.__setitem__("__abs__", new OperatorFunctions("__abs__", 10, 1));
dict.__setitem__("abs", new OperatorFunctions("abs", 10, 1));
dict.__setitem__("__inv__", new OperatorFunctions("__inv__", 11, 1));
dict.__setitem__("inv", new OperatorFunctions("inv", 11, 1));
dict.__setitem__("__neg__", new OperatorFunctions("__neg__", 12, 1));
dict.__setitem__("neg", new OperatorFunctions("neg", 12, 1));
dict.__setitem__("__not__", new OperatorFunctions("__not__", 13, 1));
dict.__setitem__("not_", new OperatorFunctions("not_", 13, 1));
dict.__setitem__("__pos__", new OperatorFunctions("__pos__", 14, 1));
dict.__setitem__("pos", new OperatorFunctions("pos", 14, 1));
dict.__setitem__("truth", new OperatorFunctions("truth", 15, 1));
dict.__setitem__("isCallable",
new OperatorFunctions("isCallable", 16, 1));
dict.__setitem__("isMappingType",
new OperatorFunctions("isMappingType", 17, 1));
dict.__setitem__("isNumberType",
new OperatorFunctions("isNumberType", 18, 1));
dict.__setitem__("isSequenceType",
new OperatorFunctions("isSequenceType", 19, 1));
dict.__setitem__("contains",
new OperatorFunctions("contains", 20, 2));
dict.__setitem__("__contains__",
new OperatorFunctions("__contains__", 20, 2));
dict.__setitem__("sequenceIncludes",
new OperatorFunctions("sequenceIncludes", 20, 2));
dict.__setitem__("__delitem__",
new OperatorFunctions("__delitem__", 21, 2));
dict.__setitem__("delitem", new OperatorFunctions("delitem", 21, 2));
dict.__setitem__("__delslice__",
new OperatorFunctions("__delslice__", 22, 3));
dict.__setitem__("delslice",
new OperatorFunctions("delslice", 22, 3));
dict.__setitem__("__getitem__",
new OperatorFunctions("__getitem__", 23, 2));
dict.__setitem__("getitem", new OperatorFunctions("getitem", 23, 2));
dict.__setitem__("__getslice__",
new OperatorFunctions("__getslice__", 24, 3));
dict.__setitem__("getslice",
new OperatorFunctions("getslice", 24, 3));
dict.__setitem__("__setitem__",
new OperatorFunctions("__setitem__", 25, 3));
dict.__setitem__("setitem", new OperatorFunctions("setitem", 25, 3));
dict.__setitem__("__setslice__",
new OperatorFunctions("__setslice__", 26, 4));
dict.__setitem__("setslice",
new OperatorFunctions("setslice", 26, 4));
dict.__setitem__("ge", new OperatorFunctions("ge", 27, 2));
dict.__setitem__("__ge__", new OperatorFunctions("__ge__", 27, 2));
dict.__setitem__("le", new OperatorFunctions("le", 28, 2));
dict.__setitem__("__le__", new OperatorFunctions("__le__", 28, 2));
dict.__setitem__("eq", new OperatorFunctions("eq", 29, 2));
dict.__setitem__("__eq__", new OperatorFunctions("__eq__", 29, 2));
dict.__setitem__("floordiv",
new OperatorFunctions("floordiv", 30, 2));
dict.__setitem__("__floordiv__",
new OperatorFunctions("__floordiv__", 30, 2));
dict.__setitem__("gt", new OperatorFunctions("gt", 31, 2));
dict.__setitem__("__gt__", new OperatorFunctions("__gt__", 31, 2));
dict.__setitem__("invert", new OperatorFunctions("invert", 32, 1));
dict.__setitem__("__invert__",
new OperatorFunctions("__invert__", 32, 1));
dict.__setitem__("lt", new OperatorFunctions("lt", 33, 2));
dict.__setitem__("__lt__", new OperatorFunctions("__lt__", 33, 2));
dict.__setitem__("ne", new OperatorFunctions("ne", 34, 2));
dict.__setitem__("__ne__", new OperatorFunctions("__ne__", 34, 2));
dict.__setitem__("truediv", new OperatorFunctions("truediv", 35, 2));
dict.__setitem__("__truediv__",
new OperatorFunctions("__truediv__", 35, 2));
dict.__setitem__("pow", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("__pow__", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("is_", new OperatorFunctions("is_", 37, 2));
dict.__setitem__("is_not", new OperatorFunctions("is_not", 38, 2));
dict.__setitem__("__iadd__", new OperatorFunctions("__iadd__", 39, 2));
dict.__setitem__("iadd", new OperatorFunctions("iadd", 39, 2));
dict.__setitem__("__iconcat__", new OperatorFunctions("__iconcat__", 39, 2));
dict.__setitem__("iconcat", new OperatorFunctions("iconcat", 39, 2));
dict.__setitem__("__iand__", new OperatorFunctions("__iand__", 40, 2));
dict.__setitem__("iand", new OperatorFunctions("iand", 40, 2));
dict.__setitem__("__idiv__", new OperatorFunctions("__idiv__", 41, 2));
dict.__setitem__("idiv", new OperatorFunctions("idiv", 41, 2));
dict.__setitem__("__ifloordiv__", new OperatorFunctions("__ifloordiv__", 42, 2));
dict.__setitem__("ifloordiv", new OperatorFunctions("ifloordiv", 42, 2));
dict.__setitem__("__ilshift__", new OperatorFunctions("__ilshift__", 43, 2));
dict.__setitem__("ilshift", new OperatorFunctions("ilshift", 43, 2));
dict.__setitem__("__imod__", new OperatorFunctions("__imod__", 44, 2));
dict.__setitem__("imod", new OperatorFunctions("imod", 44, 2));
dict.__setitem__("__imul__", new OperatorFunctions("__imul__", 45, 2));
dict.__setitem__("imul", new OperatorFunctions("imul", 45, 2));
dict.__setitem__("__irepeat__", new OperatorFunctions("__irepeat__", 45, 2));
dict.__setitem__("irepeat", new OperatorFunctions("irepeat", 45, 2));
dict.__setitem__("__ior__", new OperatorFunctions("__ior__", 46, 2));
dict.__setitem__("ior", new OperatorFunctions("ior", 46, 2));
dict.__setitem__("__ipow__", new OperatorFunctions("__ipow__", 47, 2));
dict.__setitem__("ipow", new OperatorFunctions("ipow", 47, 2));
dict.__setitem__("__irshift__", new OperatorFunctions("__irshift__", 48, 2));
dict.__setitem__("irshift", new OperatorFunctions("irshift", 48, 2));
dict.__setitem__("__isub__", new OperatorFunctions("__isub__", 49, 2));
dict.__setitem__("isub", new OperatorFunctions("isub", 49, 2));
dict.__setitem__("__itruediv__", new OperatorFunctions("__itruediv__", 50, 2));
dict.__setitem__("itruediv", new OperatorFunctions("itruediv", 50, 2));
dict.__setitem__("__ixor__", new OperatorFunctions("__ixor__", 51, 2));
dict.__setitem__("ixor", new OperatorFunctions("ixor", 51, 2));
- dict.__setitem__("__index__", new OperatorFunctions("__ixor__", 52, 1));
- dict.__setitem__("index", new OperatorFunctions("ixor", 52, 1));
+ dict.__setitem__("__index__", new OperatorFunctions("__index__", 52, 1));
+ dict.__setitem__("index", new OperatorFunctions("index", 52, 1));
dict.__setitem__("attrgetter", PyAttrGetter.TYPE);
dict.__setitem__("itemgetter", PyItemGetter.TYPE);
}
public static int countOf(PyObject seq, PyObject item) {
int count = 0;
for (PyObject tmp : seq.asIterable()) {
if (item._eq(tmp).__nonzero__()) {
count++;
}
}
return count;
}
public static int indexOf(PyObject seq, PyObject item) {
int i = 0;
PyObject iter = seq.__iter__();
for (PyObject tmp = null; (tmp = iter.__iternext__()) != null; i++) {
if (item._eq(tmp).__nonzero__()) {
return i;
}
}
throw Py.ValueError("sequence.index(x): x not in list");
}
/**
* The attrgetter type.
*/
// XXX: not subclassable
@ExposedType(name = "operator.attrgetter")
static class PyAttrGetter extends PyObject {
public static final PyType TYPE = PyType.fromClass(PyAttrGetter.class);
public PyObject[] attrs;
public PyAttrGetter(PyObject[] attrs) {
this.attrs = attrs;
}
@ExposedNew
final static PyObject attrgetter___new__(PyNewWrapper new_, boolean init, PyType subtype,
PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("attrgetter", args, keywords, "attr");
ap.noKeywords();
ap.getPyObject(0);
return new PyAttrGetter(args);
}
@Override
public PyObject __call__(PyObject[] args, String[] keywords) {
return attrgetter___call__(args, keywords);
}
@ExposedMethod
final PyObject attrgetter___call__(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("attrgetter", args, Py.NoKeywords, "obj");
PyObject obj = ap.getPyObject(0);
if (attrs.length == 1) {
return getattr(obj, attrs[0]);
}
PyObject[] result = new PyObject[attrs.length];
int i = 0;
for (PyObject attr : attrs) {
result[i++] = getattr(obj, attr);
}
return new PyTuple(result);
}
private PyObject getattr(PyObject obj, PyObject name) {
// XXX: We should probably have a PyObject.__getattr__(PyObject) that does
// this. This is different than __builtin__.getattr (in how it handles
// exceptions)
String nameStr;
if (name instanceof PyUnicode) {
nameStr = ((PyUnicode)name).encode();
} else if (name instanceof PyString) {
nameStr = name.asString();
} else {
throw Py.TypeError(String.format("attribute name must be string, not '%.200s'",
name.getType().fastGetName()));
}
return obj.__getattr__(nameStr.intern());
}
}
/**
* The itemgetter type.
*/
// XXX: not subclassable
@ExposedType(name = "operator.itemgetter")
static class PyItemGetter extends PyObject {
public static final PyType TYPE = PyType.fromClass(PyItemGetter.class);
public PyObject[] items;
public PyItemGetter(PyObject[] items) {
this.items = items;
}
@ExposedNew
final static PyObject itemgetter___new__(PyNewWrapper new_, boolean init, PyType subtype,
PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("itemgetter", args, keywords, "attr");
ap.noKeywords();
ap.getPyObject(0);
return new PyItemGetter(args);
}
@Override
public PyObject __call__(PyObject[] args, String[] keywords) {
return itemgetter___call__(args, keywords);
}
@ExposedMethod
final PyObject itemgetter___call__(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("itemgetter", args, Py.NoKeywords, "obj");
PyObject obj = ap.getPyObject(0);
if (items.length == 1) {
return obj.__getitem__(items[0]);
}
PyObject[] result = new PyObject[items.length];
int i = 0;
for (PyObject item : items) {
result[i++] = obj.__getitem__(item);
}
return new PyTuple(result);
}
}
}
| true | true | public static void classDictInit(PyObject dict) throws PyIgnoreMethodTag {
dict.__setitem__("__add__", new OperatorFunctions("__add__", 0, 2));
dict.__setitem__("add", new OperatorFunctions("add", 0, 2));
dict.__setitem__("__concat__",
new OperatorFunctions("__concat__", 0, 2));
dict.__setitem__("concat", new OperatorFunctions("concat", 0, 2));
dict.__setitem__("__and__", new OperatorFunctions("__and__", 1, 2));
dict.__setitem__("and_", new OperatorFunctions("and_", 1, 2));
dict.__setitem__("__div__", new OperatorFunctions("__div__", 2, 2));
dict.__setitem__("div", new OperatorFunctions("div", 2, 2));
dict.__setitem__("__lshift__",
new OperatorFunctions("__lshift__", 3, 2));
dict.__setitem__("lshift", new OperatorFunctions("lshift", 3, 2));
dict.__setitem__("__mod__", new OperatorFunctions("__mod__", 4, 2));
dict.__setitem__("mod", new OperatorFunctions("mod", 4, 2));
dict.__setitem__("__mul__", new OperatorFunctions("__mul__", 5, 2));
dict.__setitem__("mul", new OperatorFunctions("mul", 5, 2));
dict.__setitem__("__repeat__",
new OperatorFunctions("__repeat__", 5, 2));
dict.__setitem__("repeat", new OperatorFunctions("repeat", 5, 2));
dict.__setitem__("__or__", new OperatorFunctions("__or__", 6, 2));
dict.__setitem__("or_", new OperatorFunctions("or_", 6, 2));
dict.__setitem__("__rshift__",
new OperatorFunctions("__rshift__", 7, 2));
dict.__setitem__("rshift", new OperatorFunctions("rshift", 7, 2));
dict.__setitem__("__sub__", new OperatorFunctions("__sub__", 8, 2));
dict.__setitem__("sub", new OperatorFunctions("sub", 8, 2));
dict.__setitem__("__xor__", new OperatorFunctions("__xor__", 9, 2));
dict.__setitem__("xor", new OperatorFunctions("xor", 9, 2));
dict.__setitem__("__abs__", new OperatorFunctions("__abs__", 10, 1));
dict.__setitem__("abs", new OperatorFunctions("abs", 10, 1));
dict.__setitem__("__inv__", new OperatorFunctions("__inv__", 11, 1));
dict.__setitem__("inv", new OperatorFunctions("inv", 11, 1));
dict.__setitem__("__neg__", new OperatorFunctions("__neg__", 12, 1));
dict.__setitem__("neg", new OperatorFunctions("neg", 12, 1));
dict.__setitem__("__not__", new OperatorFunctions("__not__", 13, 1));
dict.__setitem__("not_", new OperatorFunctions("not_", 13, 1));
dict.__setitem__("__pos__", new OperatorFunctions("__pos__", 14, 1));
dict.__setitem__("pos", new OperatorFunctions("pos", 14, 1));
dict.__setitem__("truth", new OperatorFunctions("truth", 15, 1));
dict.__setitem__("isCallable",
new OperatorFunctions("isCallable", 16, 1));
dict.__setitem__("isMappingType",
new OperatorFunctions("isMappingType", 17, 1));
dict.__setitem__("isNumberType",
new OperatorFunctions("isNumberType", 18, 1));
dict.__setitem__("isSequenceType",
new OperatorFunctions("isSequenceType", 19, 1));
dict.__setitem__("contains",
new OperatorFunctions("contains", 20, 2));
dict.__setitem__("__contains__",
new OperatorFunctions("__contains__", 20, 2));
dict.__setitem__("sequenceIncludes",
new OperatorFunctions("sequenceIncludes", 20, 2));
dict.__setitem__("__delitem__",
new OperatorFunctions("__delitem__", 21, 2));
dict.__setitem__("delitem", new OperatorFunctions("delitem", 21, 2));
dict.__setitem__("__delslice__",
new OperatorFunctions("__delslice__", 22, 3));
dict.__setitem__("delslice",
new OperatorFunctions("delslice", 22, 3));
dict.__setitem__("__getitem__",
new OperatorFunctions("__getitem__", 23, 2));
dict.__setitem__("getitem", new OperatorFunctions("getitem", 23, 2));
dict.__setitem__("__getslice__",
new OperatorFunctions("__getslice__", 24, 3));
dict.__setitem__("getslice",
new OperatorFunctions("getslice", 24, 3));
dict.__setitem__("__setitem__",
new OperatorFunctions("__setitem__", 25, 3));
dict.__setitem__("setitem", new OperatorFunctions("setitem", 25, 3));
dict.__setitem__("__setslice__",
new OperatorFunctions("__setslice__", 26, 4));
dict.__setitem__("setslice",
new OperatorFunctions("setslice", 26, 4));
dict.__setitem__("ge", new OperatorFunctions("ge", 27, 2));
dict.__setitem__("__ge__", new OperatorFunctions("__ge__", 27, 2));
dict.__setitem__("le", new OperatorFunctions("le", 28, 2));
dict.__setitem__("__le__", new OperatorFunctions("__le__", 28, 2));
dict.__setitem__("eq", new OperatorFunctions("eq", 29, 2));
dict.__setitem__("__eq__", new OperatorFunctions("__eq__", 29, 2));
dict.__setitem__("floordiv",
new OperatorFunctions("floordiv", 30, 2));
dict.__setitem__("__floordiv__",
new OperatorFunctions("__floordiv__", 30, 2));
dict.__setitem__("gt", new OperatorFunctions("gt", 31, 2));
dict.__setitem__("__gt__", new OperatorFunctions("__gt__", 31, 2));
dict.__setitem__("invert", new OperatorFunctions("invert", 32, 1));
dict.__setitem__("__invert__",
new OperatorFunctions("__invert__", 32, 1));
dict.__setitem__("lt", new OperatorFunctions("lt", 33, 2));
dict.__setitem__("__lt__", new OperatorFunctions("__lt__", 33, 2));
dict.__setitem__("ne", new OperatorFunctions("ne", 34, 2));
dict.__setitem__("__ne__", new OperatorFunctions("__ne__", 34, 2));
dict.__setitem__("truediv", new OperatorFunctions("truediv", 35, 2));
dict.__setitem__("__truediv__",
new OperatorFunctions("__truediv__", 35, 2));
dict.__setitem__("pow", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("__pow__", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("is_", new OperatorFunctions("is_", 37, 2));
dict.__setitem__("is_not", new OperatorFunctions("is_not", 38, 2));
dict.__setitem__("__iadd__", new OperatorFunctions("__iadd__", 39, 2));
dict.__setitem__("iadd", new OperatorFunctions("iadd", 39, 2));
dict.__setitem__("__iconcat__", new OperatorFunctions("__iconcat__", 39, 2));
dict.__setitem__("iconcat", new OperatorFunctions("iconcat", 39, 2));
dict.__setitem__("__iand__", new OperatorFunctions("__iand__", 40, 2));
dict.__setitem__("iand", new OperatorFunctions("iand", 40, 2));
dict.__setitem__("__idiv__", new OperatorFunctions("__idiv__", 41, 2));
dict.__setitem__("idiv", new OperatorFunctions("idiv", 41, 2));
dict.__setitem__("__ifloordiv__", new OperatorFunctions("__ifloordiv__", 42, 2));
dict.__setitem__("ifloordiv", new OperatorFunctions("ifloordiv", 42, 2));
dict.__setitem__("__ilshift__", new OperatorFunctions("__ilshift__", 43, 2));
dict.__setitem__("ilshift", new OperatorFunctions("ilshift", 43, 2));
dict.__setitem__("__imod__", new OperatorFunctions("__imod__", 44, 2));
dict.__setitem__("imod", new OperatorFunctions("imod", 44, 2));
dict.__setitem__("__imul__", new OperatorFunctions("__imul__", 45, 2));
dict.__setitem__("imul", new OperatorFunctions("imul", 45, 2));
dict.__setitem__("__irepeat__", new OperatorFunctions("__irepeat__", 45, 2));
dict.__setitem__("irepeat", new OperatorFunctions("irepeat", 45, 2));
dict.__setitem__("__ior__", new OperatorFunctions("__ior__", 46, 2));
dict.__setitem__("ior", new OperatorFunctions("ior", 46, 2));
dict.__setitem__("__ipow__", new OperatorFunctions("__ipow__", 47, 2));
dict.__setitem__("ipow", new OperatorFunctions("ipow", 47, 2));
dict.__setitem__("__irshift__", new OperatorFunctions("__irshift__", 48, 2));
dict.__setitem__("irshift", new OperatorFunctions("irshift", 48, 2));
dict.__setitem__("__isub__", new OperatorFunctions("__isub__", 49, 2));
dict.__setitem__("isub", new OperatorFunctions("isub", 49, 2));
dict.__setitem__("__itruediv__", new OperatorFunctions("__itruediv__", 50, 2));
dict.__setitem__("itruediv", new OperatorFunctions("itruediv", 50, 2));
dict.__setitem__("__ixor__", new OperatorFunctions("__ixor__", 51, 2));
dict.__setitem__("ixor", new OperatorFunctions("ixor", 51, 2));
dict.__setitem__("__index__", new OperatorFunctions("__ixor__", 52, 1));
dict.__setitem__("index", new OperatorFunctions("ixor", 52, 1));
dict.__setitem__("attrgetter", PyAttrGetter.TYPE);
dict.__setitem__("itemgetter", PyItemGetter.TYPE);
}
| public static void classDictInit(PyObject dict) throws PyIgnoreMethodTag {
dict.__setitem__("__add__", new OperatorFunctions("__add__", 0, 2));
dict.__setitem__("add", new OperatorFunctions("add", 0, 2));
dict.__setitem__("__concat__",
new OperatorFunctions("__concat__", 0, 2));
dict.__setitem__("concat", new OperatorFunctions("concat", 0, 2));
dict.__setitem__("__and__", new OperatorFunctions("__and__", 1, 2));
dict.__setitem__("and_", new OperatorFunctions("and_", 1, 2));
dict.__setitem__("__div__", new OperatorFunctions("__div__", 2, 2));
dict.__setitem__("div", new OperatorFunctions("div", 2, 2));
dict.__setitem__("__lshift__",
new OperatorFunctions("__lshift__", 3, 2));
dict.__setitem__("lshift", new OperatorFunctions("lshift", 3, 2));
dict.__setitem__("__mod__", new OperatorFunctions("__mod__", 4, 2));
dict.__setitem__("mod", new OperatorFunctions("mod", 4, 2));
dict.__setitem__("__mul__", new OperatorFunctions("__mul__", 5, 2));
dict.__setitem__("mul", new OperatorFunctions("mul", 5, 2));
dict.__setitem__("__repeat__",
new OperatorFunctions("__repeat__", 5, 2));
dict.__setitem__("repeat", new OperatorFunctions("repeat", 5, 2));
dict.__setitem__("__or__", new OperatorFunctions("__or__", 6, 2));
dict.__setitem__("or_", new OperatorFunctions("or_", 6, 2));
dict.__setitem__("__rshift__",
new OperatorFunctions("__rshift__", 7, 2));
dict.__setitem__("rshift", new OperatorFunctions("rshift", 7, 2));
dict.__setitem__("__sub__", new OperatorFunctions("__sub__", 8, 2));
dict.__setitem__("sub", new OperatorFunctions("sub", 8, 2));
dict.__setitem__("__xor__", new OperatorFunctions("__xor__", 9, 2));
dict.__setitem__("xor", new OperatorFunctions("xor", 9, 2));
dict.__setitem__("__abs__", new OperatorFunctions("__abs__", 10, 1));
dict.__setitem__("abs", new OperatorFunctions("abs", 10, 1));
dict.__setitem__("__inv__", new OperatorFunctions("__inv__", 11, 1));
dict.__setitem__("inv", new OperatorFunctions("inv", 11, 1));
dict.__setitem__("__neg__", new OperatorFunctions("__neg__", 12, 1));
dict.__setitem__("neg", new OperatorFunctions("neg", 12, 1));
dict.__setitem__("__not__", new OperatorFunctions("__not__", 13, 1));
dict.__setitem__("not_", new OperatorFunctions("not_", 13, 1));
dict.__setitem__("__pos__", new OperatorFunctions("__pos__", 14, 1));
dict.__setitem__("pos", new OperatorFunctions("pos", 14, 1));
dict.__setitem__("truth", new OperatorFunctions("truth", 15, 1));
dict.__setitem__("isCallable",
new OperatorFunctions("isCallable", 16, 1));
dict.__setitem__("isMappingType",
new OperatorFunctions("isMappingType", 17, 1));
dict.__setitem__("isNumberType",
new OperatorFunctions("isNumberType", 18, 1));
dict.__setitem__("isSequenceType",
new OperatorFunctions("isSequenceType", 19, 1));
dict.__setitem__("contains",
new OperatorFunctions("contains", 20, 2));
dict.__setitem__("__contains__",
new OperatorFunctions("__contains__", 20, 2));
dict.__setitem__("sequenceIncludes",
new OperatorFunctions("sequenceIncludes", 20, 2));
dict.__setitem__("__delitem__",
new OperatorFunctions("__delitem__", 21, 2));
dict.__setitem__("delitem", new OperatorFunctions("delitem", 21, 2));
dict.__setitem__("__delslice__",
new OperatorFunctions("__delslice__", 22, 3));
dict.__setitem__("delslice",
new OperatorFunctions("delslice", 22, 3));
dict.__setitem__("__getitem__",
new OperatorFunctions("__getitem__", 23, 2));
dict.__setitem__("getitem", new OperatorFunctions("getitem", 23, 2));
dict.__setitem__("__getslice__",
new OperatorFunctions("__getslice__", 24, 3));
dict.__setitem__("getslice",
new OperatorFunctions("getslice", 24, 3));
dict.__setitem__("__setitem__",
new OperatorFunctions("__setitem__", 25, 3));
dict.__setitem__("setitem", new OperatorFunctions("setitem", 25, 3));
dict.__setitem__("__setslice__",
new OperatorFunctions("__setslice__", 26, 4));
dict.__setitem__("setslice",
new OperatorFunctions("setslice", 26, 4));
dict.__setitem__("ge", new OperatorFunctions("ge", 27, 2));
dict.__setitem__("__ge__", new OperatorFunctions("__ge__", 27, 2));
dict.__setitem__("le", new OperatorFunctions("le", 28, 2));
dict.__setitem__("__le__", new OperatorFunctions("__le__", 28, 2));
dict.__setitem__("eq", new OperatorFunctions("eq", 29, 2));
dict.__setitem__("__eq__", new OperatorFunctions("__eq__", 29, 2));
dict.__setitem__("floordiv",
new OperatorFunctions("floordiv", 30, 2));
dict.__setitem__("__floordiv__",
new OperatorFunctions("__floordiv__", 30, 2));
dict.__setitem__("gt", new OperatorFunctions("gt", 31, 2));
dict.__setitem__("__gt__", new OperatorFunctions("__gt__", 31, 2));
dict.__setitem__("invert", new OperatorFunctions("invert", 32, 1));
dict.__setitem__("__invert__",
new OperatorFunctions("__invert__", 32, 1));
dict.__setitem__("lt", new OperatorFunctions("lt", 33, 2));
dict.__setitem__("__lt__", new OperatorFunctions("__lt__", 33, 2));
dict.__setitem__("ne", new OperatorFunctions("ne", 34, 2));
dict.__setitem__("__ne__", new OperatorFunctions("__ne__", 34, 2));
dict.__setitem__("truediv", new OperatorFunctions("truediv", 35, 2));
dict.__setitem__("__truediv__",
new OperatorFunctions("__truediv__", 35, 2));
dict.__setitem__("pow", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("__pow__", new OperatorFunctions("pow", 36, 2));
dict.__setitem__("is_", new OperatorFunctions("is_", 37, 2));
dict.__setitem__("is_not", new OperatorFunctions("is_not", 38, 2));
dict.__setitem__("__iadd__", new OperatorFunctions("__iadd__", 39, 2));
dict.__setitem__("iadd", new OperatorFunctions("iadd", 39, 2));
dict.__setitem__("__iconcat__", new OperatorFunctions("__iconcat__", 39, 2));
dict.__setitem__("iconcat", new OperatorFunctions("iconcat", 39, 2));
dict.__setitem__("__iand__", new OperatorFunctions("__iand__", 40, 2));
dict.__setitem__("iand", new OperatorFunctions("iand", 40, 2));
dict.__setitem__("__idiv__", new OperatorFunctions("__idiv__", 41, 2));
dict.__setitem__("idiv", new OperatorFunctions("idiv", 41, 2));
dict.__setitem__("__ifloordiv__", new OperatorFunctions("__ifloordiv__", 42, 2));
dict.__setitem__("ifloordiv", new OperatorFunctions("ifloordiv", 42, 2));
dict.__setitem__("__ilshift__", new OperatorFunctions("__ilshift__", 43, 2));
dict.__setitem__("ilshift", new OperatorFunctions("ilshift", 43, 2));
dict.__setitem__("__imod__", new OperatorFunctions("__imod__", 44, 2));
dict.__setitem__("imod", new OperatorFunctions("imod", 44, 2));
dict.__setitem__("__imul__", new OperatorFunctions("__imul__", 45, 2));
dict.__setitem__("imul", new OperatorFunctions("imul", 45, 2));
dict.__setitem__("__irepeat__", new OperatorFunctions("__irepeat__", 45, 2));
dict.__setitem__("irepeat", new OperatorFunctions("irepeat", 45, 2));
dict.__setitem__("__ior__", new OperatorFunctions("__ior__", 46, 2));
dict.__setitem__("ior", new OperatorFunctions("ior", 46, 2));
dict.__setitem__("__ipow__", new OperatorFunctions("__ipow__", 47, 2));
dict.__setitem__("ipow", new OperatorFunctions("ipow", 47, 2));
dict.__setitem__("__irshift__", new OperatorFunctions("__irshift__", 48, 2));
dict.__setitem__("irshift", new OperatorFunctions("irshift", 48, 2));
dict.__setitem__("__isub__", new OperatorFunctions("__isub__", 49, 2));
dict.__setitem__("isub", new OperatorFunctions("isub", 49, 2));
dict.__setitem__("__itruediv__", new OperatorFunctions("__itruediv__", 50, 2));
dict.__setitem__("itruediv", new OperatorFunctions("itruediv", 50, 2));
dict.__setitem__("__ixor__", new OperatorFunctions("__ixor__", 51, 2));
dict.__setitem__("ixor", new OperatorFunctions("ixor", 51, 2));
dict.__setitem__("__index__", new OperatorFunctions("__index__", 52, 1));
dict.__setitem__("index", new OperatorFunctions("index", 52, 1));
dict.__setitem__("attrgetter", PyAttrGetter.TYPE);
dict.__setitem__("itemgetter", PyItemGetter.TYPE);
}
|
diff --git a/HelloWorld/src/test/java/TestHelloWorld.java b/HelloWorld/src/test/java/TestHelloWorld.java
index 551db22..56dd509 100644
--- a/HelloWorld/src/test/java/TestHelloWorld.java
+++ b/HelloWorld/src/test/java/TestHelloWorld.java
@@ -1,15 +1,15 @@
import static org.junit.Assert.*;
import org.junit.Test;
public class TestHelloWorld {
@Test
public void test() {
- assertTrue(false);
+ assertTrue(true);
}
}
| true | true | public void test() {
assertTrue(false);
}
| public void test() {
assertTrue(true);
}
|
diff --git a/src/main/java/greed/Greed.java b/src/main/java/greed/Greed.java
index f5f1de5..cf4b3bd 100644
--- a/src/main/java/greed/Greed.java
+++ b/src/main/java/greed/Greed.java
@@ -1,458 +1,462 @@
package greed;
import greed.code.CodeByLine;
import greed.code.ConfigurableCodeTransformer;
import greed.code.LanguageManager;
import greed.code.transform.AppendingTransformer;
import greed.code.transform.ContinuousBlankLineRemover;
import greed.code.transform.CutBlockRemover;
import greed.code.transform.EmptyCutBlockCleaner;
import greed.conf.schema.*;
import greed.conf.schema.TemplateDependencyConfig.*;
import greed.model.Contest;
import greed.model.Convert;
import greed.model.Language;
import greed.model.Param;
import greed.model.Problem;
import greed.template.TemplateEngine;
import greed.ui.ConfigurationDialog;
import greed.ui.GreedEditorPanel;
import greed.util.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import javax.swing.JPanel;
import com.topcoder.client.contestant.ProblemComponentModel;
import com.topcoder.shared.problem.Renderer;
/**
* Greed is good! Cheers!
*/
@SuppressWarnings("unused")
public class Greed {
private Language currentLang;
private Problem currentProb;
private Contest currentContest;
private HashMap<String, Object> currentModel;
private TemplateEngine currentEngine;
private GreedEditorPanel talkingWindow;
private boolean initialized;
public Greed() {
// Entrance of all program
Log.i("Greed Plugin");
this.talkingWindow = new GreedEditorPanel(this);
this.initialized = false;
}
// Greed signature in the code
public String getSignature() {
return String.format("%s Powered by %s %s",
LanguageManager.getInstance().getTrait(currentLang).getCommentPrefix(), AppInfo.getAppName(), AppInfo.getVersion());
}
// Cache the editor
public boolean isCacheable() {
return !Modes.devMode;
}
// Called when open the coding frame
// Like FileEdit, a log window is used
public JPanel getEditorPanel() {
return talkingWindow;
}
// Ignore the given source code
public void setSource(String source) {
}
public void initialize() {
try {
talkingWindow.show("Initializing... ");
talkingWindow.indent();
initialized = false;
Utils.initialize();
initialized = true;
talkingWindow.showLine("done");
} catch (greed.conf.ConfigException e) {
Log.e("Loading config error", e);
talkingWindow.showLine("failed");
talkingWindow.error("Config error: " + e.getMessage());
} catch (Throwable e) {
Log.e("Initialization error", e);
talkingWindow.showLine("failed");
talkingWindow.error("Fatal error: " + e.getMessage());
} finally {
talkingWindow.unindent();
talkingWindow.showLine("");
}
}
public void startUsing() {
Log.d("Start using");
talkingWindow.clear();
if (!initialized) {
talkingWindow.showLine(String.format("Greetings from %s", AppInfo.getAppName()));
initialize();
} else {
talkingWindow.showLine(String.format("Hello again :>"));
}
}
public void stopUsing() {
Log.d("Stop using");
}
public void configure() {
new ConfigurationDialog().setVisible(true);
}
public void setProblemComponent(ProblemComponentModel componentModel, com.topcoder.shared.language.Language language, Renderer renderer) {
currentContest = Convert.convertContest(componentModel);
currentLang = Convert.convertLanguage(language);
if (currentLang == Language.VB) {
talkingWindow.error("Unsupported language " + currentLang.toString());
return;
}
currentProb = Convert.convertProblem(componentModel, currentLang);
if (!initialized)
return;
generateCode(false);
}
public void generateCode(boolean regen) {
// Check whether workspace is set
if (Configuration.getWorkspace() == null || "".equals(Configuration.getWorkspace())) {
talkingWindow.setEnabled(false);
talkingWindow.error("Workspace not configured, go set it!");
Log.e("Workspace not configured");
return;
}
talkingWindow.setEnabled(true);
try {
talkingWindow.showLine(String.format("Problem : %s", currentProb.getName()));
talkingWindow.showLine(String.format("Score : %d", currentProb.getScore()));
talkingWindow.showLine(regen ? "Regenerating code..." : "Generating code...");
talkingWindow.indent();
setProblem(currentContest, currentProb, currentLang, regen);
} catch (Throwable e) {
talkingWindow.error("Error: " + e.getMessage());
Log.e("Set problem error", e);
} finally {
talkingWindow.unindent();
}
}
private String renderedCodeRoot(GreedConfig config)
{
return currentEngine.render(config.getCodeRoot(), currentModel);
}
@SuppressWarnings("unchecked")
private void setProblem(Contest contest, Problem problem, Language language, boolean regen) {
GreedConfig config = Utils.getGreedConfig();
LanguageConfig langConfig = config.getLanguage().get(Language.getName(language));
// Initialize code transformers
HashMap<String, ConfigurableCodeTransformer> codeTransformers = new HashMap<String, ConfigurableCodeTransformer>();
for (ConfigurableCodeTransformer ccf: new ConfigurableCodeTransformer[] {
new ContinuousBlankLineRemover(),
new EmptyCutBlockCleaner(langConfig.getCutBegin(), langConfig.getCutEnd())
}) {
codeTransformers.put(ccf.getId(), ccf);
}
// Create model map
currentModel = new HashMap<String, Object>();
currentModel.put("Contest", contest);
currentModel.put("Problem", problem);
currentModel.put("ClassName", problem.getClassName());
currentModel.put("Method", problem.getMethod());
// Bind problem template model
HashMap<String, Object> sharedModel = new HashMap<String, Object>(currentModel);
sharedModel.put("Examples", problem.getTestcases());
sharedModel.put("NumOfExamples", problem.getTestcases().length);
boolean useArray = problem.getMethod().getReturnType().isArray();
sharedModel.put("ReturnsArray", useArray);
for (Param param : problem.getMethod().getParams()) useArray |= param.getType().isArray();
sharedModel.put("HasArray", useArray);
boolean useString = problem.getMethod().getReturnType().isString();
sharedModel.put("ReturnsString", useString);
for (Param param : problem.getMethod().getParams()) useString |= param.getType().isString();
sharedModel.put("HasString", useString);
sharedModel.put("CreateTime", System.currentTimeMillis() / 1000);
sharedModel.put("CutBegin", langConfig.getCutBegin());
sharedModel.put("CutEnd", langConfig.getCutEnd());
// Switch language
currentEngine = TemplateEngine.newLanguageEngine(language);
// Validate template definitions and calculate order
ArrayList<String> templateOrder;
{
ArrayList<String> templates = new ArrayList<String>();
HashSet<String> templateSet = new HashSet<String>();
// Find all the templates needed by hard constraint (direct template dependency)
for (String templateName: langConfig.getTemplates()) {
// Check existence of template
if (!langConfig.getTemplateDef().containsKey(templateName)) {
talkingWindow.error("Unknown template [" + templateName + "] (ignored)");
continue;
}
// Check existence of template file
ResourcePath templateFile = langConfig.getTemplateDef().get(templateName).getTemplateFile();
if (!FileSystem.exists(templateFile)) {
talkingWindow.error("Template file [" + templateFile.getRelativePath() + "] not found (ignored)");
continue;
}
templates.add(templateName);
templateSet.add(templateName);
}
for (int i = 0; i < templates.size(); ++i) {
String template = templates.get(i);
TemplateConfig templateConfig = langConfig.getTemplateDef().get(template);
if (templateConfig.getDependencies() != null) {
for (Dependency dep: templateConfig.getDependencies()) {
if (dep instanceof TemplateDependency) {
String depTemplate = ((TemplateDependency)dep).getTemplate();
- if (!templateSet.contains(depTemplate)) {
+ if (!langConfig.getTemplateDef().containsKey(depTemplate)) {
+ talkingWindow.error(String.format("Unknown template [%s], required by [%s] (halted)", depTemplate, template));
+ return;
+ }
+ else if (!templateSet.contains(depTemplate)) {
templateSet.add(depTemplate);
templates.add(depTemplate);
}
}
}
}
}
// Queue the order
templateOrder = new ArrayList<String>();
HashSet<String> hasKeys = new HashSet<String>();
HashSet<String> hasTemplates = new HashSet<String>();
while (!templateSet.isEmpty()) {
String selected = null;
for (String template: templateSet) {
boolean independent = true;
TemplateConfig templateConfig = langConfig.getTemplateDef().get(template);
if (templateConfig.getDependencies() != null) {
for (Dependency dep: templateConfig.getDependencies()) {
if (!checkDependency(dep, hasKeys, hasTemplates)) {
independent = false;
break;
}
}
}
if (independent) {
selected = template;
break;
}
}
if (selected == null)
break;
templateSet.remove(selected);
templateOrder.add(selected);
hasTemplates.add(selected);
String key = langConfig.getTemplateDef().get(selected).getOutputKey();
if (key != null)
hasKeys.add(key);
}
if (!templateSet.isEmpty())
templateOrder = null;
}
if (templateOrder == null) {
talkingWindow.error("Cannot figure out template generation order");
return;
}
HashMap<String, Object> dependencyModel = new HashMap<String, Object>();
sharedModel.put("Dependencies", dependencyModel);
// Generate templates
for (String templateName : templateOrder) {
talkingWindow.show(String.format("Generating template [" + templateName + "]"));
TemplateConfig template = langConfig.getTemplateDef().get(templateName);
HashMap<String, Object> indivModel = new HashMap<String, Object>();
indivModel.put("Options", template.getOptions());
dependencyModel.put(templateName, indivModel);
// Generate code from templates
String output;
try {
output = currentEngine.render(
FileSystem.getResource(template.getTemplateFile()),
mergeModels(sharedModel, indivModel)
);
if (template.getTransformers() != null) {
CodeByLine codeLines = CodeByLine.fromString(output);
for (String transformerId: template.getTransformers()) {
if (codeTransformers.containsKey(transformerId)) {
codeLines = codeTransformers.get(transformerId).transform(codeLines);
}
else {
talkingWindow.indent();
talkingWindow.error("Unknown transformer \"" + transformerId + "\"");
talkingWindow.unindent();
}
}
output = codeLines.toString();
}
} catch (FileNotFoundException e) {
// Fatal error, the existence has been checked before
Log.e("Fatal error, cannot find resource " + template.getTemplateFile(), e);
throw new IllegalStateException(e);
}
// Output to self
indivModel.put("Output", output);
// Output to model
if (template.getOutputKey() != null) {
sharedModel.put(template.getOutputKey(), output);
}
// Output to file
if (template.getOutputFile() != null) {
String filePath = renderedCodeRoot(config) + "/" +
currentEngine.render(template.getOutputFile(), currentModel);
String fileFolder = FileSystem.getParentPath(filePath);
if (!FileSystem.exists(fileFolder)) {
FileSystem.createFolder(fileFolder);
}
indivModel.put("GeneratedFileName", new java.io.File(filePath).getName());
indivModel.put("GeneratedFilePath", FileSystem.getRawFile(filePath).getPath());
boolean exists = FileSystem.exists(filePath);
TemplateConfig.OverwriteOptions overwrite = template.getOverwrite();
if (regen && overwrite == TemplateConfig.OverwriteOptions.SKIP)
overwrite = TemplateConfig.OverwriteOptions.BACKUP;
talkingWindow.show(" -> " + filePath);
if (exists && overwrite == TemplateConfig.OverwriteOptions.SKIP) {
talkingWindow.showLine(" (skipped)");
continue;
}
if (exists) {
String oldContent;
try {
oldContent = FileSystem.readStream(FileSystem.getResource(new ResourcePath(filePath, false)));
} catch (FileNotFoundException e) {
Log.e("Fatal error, cannot find resource " + filePath, e);
throw new IllegalStateException(e);
}
if (oldContent.equals(output)) {
talkingWindow.show(" (skipped, identical)");
} else {
if (overwrite == TemplateConfig.OverwriteOptions.FORCE) {
talkingWindow.show(" (force overwrite)");
FileSystem.writeFile(filePath, output);
}
else {
talkingWindow.show(" (backup and overwrite)");
FileSystem.backup(filePath); // Backup the old files
FileSystem.writeFile(filePath, output);
}
}
}
else {
FileSystem.writeFile(filePath, output);
}
if (template.getAfterFileGen() != null) {
CommandConfig afterGen = template.getAfterFileGen();
String[] commands = new String[afterGen.getArguments().length + 1];
commands[0] = afterGen.getExecute();
for (int i = 1; i < commands.length; ++i) {
commands[i] = currentEngine.render(afterGen.getArguments()[i - 1], mergeModels(currentModel, indivModel));
}
long timeout = 1000L * afterGen.getTimeout();
talkingWindow.showLine("");
talkingWindow.indent();
talkingWindow.showLine("After generation action: ");
talkingWindow.indent();
talkingWindow.showLine(String.format("(%s)$ %s", fileFolder, StringUtil.join(commands, " ")));
talkingWindow.show("Exit status (-1 means exception): " + ExternalSystem.runExternalCommand(FileSystem.getRawFile(fileFolder), timeout, commands));
talkingWindow.unindent();
talkingWindow.unindent();
}
}
talkingWindow.showLine("");
}
talkingWindow.showLine("All set, good luck!");
talkingWindow.showLine("");
}
private HashMap<String, Object> mergeModels(HashMap<String, Object> ... models) {
HashMap<String, Object> merged = new HashMap<String, Object>();
for (HashMap<String, Object> model: models)
merged.putAll(model);
return merged;
}
private boolean checkDependency(Dependency dependency, HashSet<String> hasKeys, HashSet<String> hasTemplates) {
if (dependency instanceof KeyDependency) {
return hasKeys.contains(((KeyDependency)dependency).getKey());
}
else if (dependency instanceof TemplateDependency) {
return hasTemplates.contains(((TemplateDependency)dependency).getTemplate());
}
else if (dependency instanceof OneOfDependency) {
OneOfDependency oneOfDep = (OneOfDependency)dependency;
for (Dependency dep: oneOfDep.getDependencies()) {
if (checkDependency(dep, hasKeys, hasTemplates)) {
return true;
}
}
return false;
}
throw new IllegalStateException("Invalid types of Dependency");
}
public String getSource() {
GreedConfig config = Utils.getGreedConfig();
LanguageConfig langConfig = config.getLanguage().get(Language.getName(currentLang));
String filePath = renderedCodeRoot(config) + "/" +
currentEngine.render(langConfig.getTemplateDef().get(langConfig.getSubmitTemplate()).getOutputFile(), currentModel);
talkingWindow.showLine("Getting source code from " + filePath);
talkingWindow.indent();
String result = "";
if (!FileSystem.exists(filePath)) {
talkingWindow.error("Source code file doesn't exist");
}
else {
try {
CodeByLine code = CodeByLine.fromInputStream(FileSystem.getResource(new ResourcePath(filePath, false)));
if (LanguageManager.getInstance().getPostTransformer(currentLang) != null)
code = LanguageManager.getInstance().getPostTransformer(currentLang).transform(code);
code = new CutBlockRemover(langConfig.getCutBegin(), langConfig.getCutEnd()).transform(code);
code = new AppendingTransformer(getSignature()).transform(code);
result = code.toString();
} catch (IOException e) {
talkingWindow.error("Cannot fetch source code, message says \"" + e.getMessage() + "\"");
Log.e("Cannot fetch source code", e);
}
}
talkingWindow.unindent();
return result;
}
}
| true | true | private void setProblem(Contest contest, Problem problem, Language language, boolean regen) {
GreedConfig config = Utils.getGreedConfig();
LanguageConfig langConfig = config.getLanguage().get(Language.getName(language));
// Initialize code transformers
HashMap<String, ConfigurableCodeTransformer> codeTransformers = new HashMap<String, ConfigurableCodeTransformer>();
for (ConfigurableCodeTransformer ccf: new ConfigurableCodeTransformer[] {
new ContinuousBlankLineRemover(),
new EmptyCutBlockCleaner(langConfig.getCutBegin(), langConfig.getCutEnd())
}) {
codeTransformers.put(ccf.getId(), ccf);
}
// Create model map
currentModel = new HashMap<String, Object>();
currentModel.put("Contest", contest);
currentModel.put("Problem", problem);
currentModel.put("ClassName", problem.getClassName());
currentModel.put("Method", problem.getMethod());
// Bind problem template model
HashMap<String, Object> sharedModel = new HashMap<String, Object>(currentModel);
sharedModel.put("Examples", problem.getTestcases());
sharedModel.put("NumOfExamples", problem.getTestcases().length);
boolean useArray = problem.getMethod().getReturnType().isArray();
sharedModel.put("ReturnsArray", useArray);
for (Param param : problem.getMethod().getParams()) useArray |= param.getType().isArray();
sharedModel.put("HasArray", useArray);
boolean useString = problem.getMethod().getReturnType().isString();
sharedModel.put("ReturnsString", useString);
for (Param param : problem.getMethod().getParams()) useString |= param.getType().isString();
sharedModel.put("HasString", useString);
sharedModel.put("CreateTime", System.currentTimeMillis() / 1000);
sharedModel.put("CutBegin", langConfig.getCutBegin());
sharedModel.put("CutEnd", langConfig.getCutEnd());
// Switch language
currentEngine = TemplateEngine.newLanguageEngine(language);
// Validate template definitions and calculate order
ArrayList<String> templateOrder;
{
ArrayList<String> templates = new ArrayList<String>();
HashSet<String> templateSet = new HashSet<String>();
// Find all the templates needed by hard constraint (direct template dependency)
for (String templateName: langConfig.getTemplates()) {
// Check existence of template
if (!langConfig.getTemplateDef().containsKey(templateName)) {
talkingWindow.error("Unknown template [" + templateName + "] (ignored)");
continue;
}
// Check existence of template file
ResourcePath templateFile = langConfig.getTemplateDef().get(templateName).getTemplateFile();
if (!FileSystem.exists(templateFile)) {
talkingWindow.error("Template file [" + templateFile.getRelativePath() + "] not found (ignored)");
continue;
}
templates.add(templateName);
templateSet.add(templateName);
}
for (int i = 0; i < templates.size(); ++i) {
String template = templates.get(i);
TemplateConfig templateConfig = langConfig.getTemplateDef().get(template);
if (templateConfig.getDependencies() != null) {
for (Dependency dep: templateConfig.getDependencies()) {
if (dep instanceof TemplateDependency) {
String depTemplate = ((TemplateDependency)dep).getTemplate();
if (!templateSet.contains(depTemplate)) {
templateSet.add(depTemplate);
templates.add(depTemplate);
}
}
}
}
}
// Queue the order
templateOrder = new ArrayList<String>();
HashSet<String> hasKeys = new HashSet<String>();
HashSet<String> hasTemplates = new HashSet<String>();
while (!templateSet.isEmpty()) {
String selected = null;
for (String template: templateSet) {
boolean independent = true;
TemplateConfig templateConfig = langConfig.getTemplateDef().get(template);
if (templateConfig.getDependencies() != null) {
for (Dependency dep: templateConfig.getDependencies()) {
if (!checkDependency(dep, hasKeys, hasTemplates)) {
independent = false;
break;
}
}
}
if (independent) {
selected = template;
break;
}
}
if (selected == null)
break;
templateSet.remove(selected);
templateOrder.add(selected);
hasTemplates.add(selected);
String key = langConfig.getTemplateDef().get(selected).getOutputKey();
if (key != null)
hasKeys.add(key);
}
if (!templateSet.isEmpty())
templateOrder = null;
}
if (templateOrder == null) {
talkingWindow.error("Cannot figure out template generation order");
return;
}
HashMap<String, Object> dependencyModel = new HashMap<String, Object>();
sharedModel.put("Dependencies", dependencyModel);
// Generate templates
for (String templateName : templateOrder) {
talkingWindow.show(String.format("Generating template [" + templateName + "]"));
TemplateConfig template = langConfig.getTemplateDef().get(templateName);
HashMap<String, Object> indivModel = new HashMap<String, Object>();
indivModel.put("Options", template.getOptions());
dependencyModel.put(templateName, indivModel);
// Generate code from templates
String output;
try {
output = currentEngine.render(
FileSystem.getResource(template.getTemplateFile()),
mergeModels(sharedModel, indivModel)
);
if (template.getTransformers() != null) {
CodeByLine codeLines = CodeByLine.fromString(output);
for (String transformerId: template.getTransformers()) {
if (codeTransformers.containsKey(transformerId)) {
codeLines = codeTransformers.get(transformerId).transform(codeLines);
}
else {
talkingWindow.indent();
talkingWindow.error("Unknown transformer \"" + transformerId + "\"");
talkingWindow.unindent();
}
}
output = codeLines.toString();
}
} catch (FileNotFoundException e) {
// Fatal error, the existence has been checked before
Log.e("Fatal error, cannot find resource " + template.getTemplateFile(), e);
throw new IllegalStateException(e);
}
// Output to self
indivModel.put("Output", output);
// Output to model
if (template.getOutputKey() != null) {
sharedModel.put(template.getOutputKey(), output);
}
// Output to file
if (template.getOutputFile() != null) {
String filePath = renderedCodeRoot(config) + "/" +
currentEngine.render(template.getOutputFile(), currentModel);
String fileFolder = FileSystem.getParentPath(filePath);
if (!FileSystem.exists(fileFolder)) {
FileSystem.createFolder(fileFolder);
}
indivModel.put("GeneratedFileName", new java.io.File(filePath).getName());
indivModel.put("GeneratedFilePath", FileSystem.getRawFile(filePath).getPath());
boolean exists = FileSystem.exists(filePath);
TemplateConfig.OverwriteOptions overwrite = template.getOverwrite();
if (regen && overwrite == TemplateConfig.OverwriteOptions.SKIP)
overwrite = TemplateConfig.OverwriteOptions.BACKUP;
talkingWindow.show(" -> " + filePath);
if (exists && overwrite == TemplateConfig.OverwriteOptions.SKIP) {
talkingWindow.showLine(" (skipped)");
continue;
}
if (exists) {
String oldContent;
try {
oldContent = FileSystem.readStream(FileSystem.getResource(new ResourcePath(filePath, false)));
} catch (FileNotFoundException e) {
Log.e("Fatal error, cannot find resource " + filePath, e);
throw new IllegalStateException(e);
}
if (oldContent.equals(output)) {
talkingWindow.show(" (skipped, identical)");
} else {
if (overwrite == TemplateConfig.OverwriteOptions.FORCE) {
talkingWindow.show(" (force overwrite)");
FileSystem.writeFile(filePath, output);
}
else {
talkingWindow.show(" (backup and overwrite)");
FileSystem.backup(filePath); // Backup the old files
FileSystem.writeFile(filePath, output);
}
}
}
else {
FileSystem.writeFile(filePath, output);
}
if (template.getAfterFileGen() != null) {
CommandConfig afterGen = template.getAfterFileGen();
String[] commands = new String[afterGen.getArguments().length + 1];
commands[0] = afterGen.getExecute();
for (int i = 1; i < commands.length; ++i) {
commands[i] = currentEngine.render(afterGen.getArguments()[i - 1], mergeModels(currentModel, indivModel));
}
long timeout = 1000L * afterGen.getTimeout();
talkingWindow.showLine("");
talkingWindow.indent();
talkingWindow.showLine("After generation action: ");
talkingWindow.indent();
talkingWindow.showLine(String.format("(%s)$ %s", fileFolder, StringUtil.join(commands, " ")));
talkingWindow.show("Exit status (-1 means exception): " + ExternalSystem.runExternalCommand(FileSystem.getRawFile(fileFolder), timeout, commands));
talkingWindow.unindent();
talkingWindow.unindent();
}
}
talkingWindow.showLine("");
}
talkingWindow.showLine("All set, good luck!");
talkingWindow.showLine("");
}
| private void setProblem(Contest contest, Problem problem, Language language, boolean regen) {
GreedConfig config = Utils.getGreedConfig();
LanguageConfig langConfig = config.getLanguage().get(Language.getName(language));
// Initialize code transformers
HashMap<String, ConfigurableCodeTransformer> codeTransformers = new HashMap<String, ConfigurableCodeTransformer>();
for (ConfigurableCodeTransformer ccf: new ConfigurableCodeTransformer[] {
new ContinuousBlankLineRemover(),
new EmptyCutBlockCleaner(langConfig.getCutBegin(), langConfig.getCutEnd())
}) {
codeTransformers.put(ccf.getId(), ccf);
}
// Create model map
currentModel = new HashMap<String, Object>();
currentModel.put("Contest", contest);
currentModel.put("Problem", problem);
currentModel.put("ClassName", problem.getClassName());
currentModel.put("Method", problem.getMethod());
// Bind problem template model
HashMap<String, Object> sharedModel = new HashMap<String, Object>(currentModel);
sharedModel.put("Examples", problem.getTestcases());
sharedModel.put("NumOfExamples", problem.getTestcases().length);
boolean useArray = problem.getMethod().getReturnType().isArray();
sharedModel.put("ReturnsArray", useArray);
for (Param param : problem.getMethod().getParams()) useArray |= param.getType().isArray();
sharedModel.put("HasArray", useArray);
boolean useString = problem.getMethod().getReturnType().isString();
sharedModel.put("ReturnsString", useString);
for (Param param : problem.getMethod().getParams()) useString |= param.getType().isString();
sharedModel.put("HasString", useString);
sharedModel.put("CreateTime", System.currentTimeMillis() / 1000);
sharedModel.put("CutBegin", langConfig.getCutBegin());
sharedModel.put("CutEnd", langConfig.getCutEnd());
// Switch language
currentEngine = TemplateEngine.newLanguageEngine(language);
// Validate template definitions and calculate order
ArrayList<String> templateOrder;
{
ArrayList<String> templates = new ArrayList<String>();
HashSet<String> templateSet = new HashSet<String>();
// Find all the templates needed by hard constraint (direct template dependency)
for (String templateName: langConfig.getTemplates()) {
// Check existence of template
if (!langConfig.getTemplateDef().containsKey(templateName)) {
talkingWindow.error("Unknown template [" + templateName + "] (ignored)");
continue;
}
// Check existence of template file
ResourcePath templateFile = langConfig.getTemplateDef().get(templateName).getTemplateFile();
if (!FileSystem.exists(templateFile)) {
talkingWindow.error("Template file [" + templateFile.getRelativePath() + "] not found (ignored)");
continue;
}
templates.add(templateName);
templateSet.add(templateName);
}
for (int i = 0; i < templates.size(); ++i) {
String template = templates.get(i);
TemplateConfig templateConfig = langConfig.getTemplateDef().get(template);
if (templateConfig.getDependencies() != null) {
for (Dependency dep: templateConfig.getDependencies()) {
if (dep instanceof TemplateDependency) {
String depTemplate = ((TemplateDependency)dep).getTemplate();
if (!langConfig.getTemplateDef().containsKey(depTemplate)) {
talkingWindow.error(String.format("Unknown template [%s], required by [%s] (halted)", depTemplate, template));
return;
}
else if (!templateSet.contains(depTemplate)) {
templateSet.add(depTemplate);
templates.add(depTemplate);
}
}
}
}
}
// Queue the order
templateOrder = new ArrayList<String>();
HashSet<String> hasKeys = new HashSet<String>();
HashSet<String> hasTemplates = new HashSet<String>();
while (!templateSet.isEmpty()) {
String selected = null;
for (String template: templateSet) {
boolean independent = true;
TemplateConfig templateConfig = langConfig.getTemplateDef().get(template);
if (templateConfig.getDependencies() != null) {
for (Dependency dep: templateConfig.getDependencies()) {
if (!checkDependency(dep, hasKeys, hasTemplates)) {
independent = false;
break;
}
}
}
if (independent) {
selected = template;
break;
}
}
if (selected == null)
break;
templateSet.remove(selected);
templateOrder.add(selected);
hasTemplates.add(selected);
String key = langConfig.getTemplateDef().get(selected).getOutputKey();
if (key != null)
hasKeys.add(key);
}
if (!templateSet.isEmpty())
templateOrder = null;
}
if (templateOrder == null) {
talkingWindow.error("Cannot figure out template generation order");
return;
}
HashMap<String, Object> dependencyModel = new HashMap<String, Object>();
sharedModel.put("Dependencies", dependencyModel);
// Generate templates
for (String templateName : templateOrder) {
talkingWindow.show(String.format("Generating template [" + templateName + "]"));
TemplateConfig template = langConfig.getTemplateDef().get(templateName);
HashMap<String, Object> indivModel = new HashMap<String, Object>();
indivModel.put("Options", template.getOptions());
dependencyModel.put(templateName, indivModel);
// Generate code from templates
String output;
try {
output = currentEngine.render(
FileSystem.getResource(template.getTemplateFile()),
mergeModels(sharedModel, indivModel)
);
if (template.getTransformers() != null) {
CodeByLine codeLines = CodeByLine.fromString(output);
for (String transformerId: template.getTransformers()) {
if (codeTransformers.containsKey(transformerId)) {
codeLines = codeTransformers.get(transformerId).transform(codeLines);
}
else {
talkingWindow.indent();
talkingWindow.error("Unknown transformer \"" + transformerId + "\"");
talkingWindow.unindent();
}
}
output = codeLines.toString();
}
} catch (FileNotFoundException e) {
// Fatal error, the existence has been checked before
Log.e("Fatal error, cannot find resource " + template.getTemplateFile(), e);
throw new IllegalStateException(e);
}
// Output to self
indivModel.put("Output", output);
// Output to model
if (template.getOutputKey() != null) {
sharedModel.put(template.getOutputKey(), output);
}
// Output to file
if (template.getOutputFile() != null) {
String filePath = renderedCodeRoot(config) + "/" +
currentEngine.render(template.getOutputFile(), currentModel);
String fileFolder = FileSystem.getParentPath(filePath);
if (!FileSystem.exists(fileFolder)) {
FileSystem.createFolder(fileFolder);
}
indivModel.put("GeneratedFileName", new java.io.File(filePath).getName());
indivModel.put("GeneratedFilePath", FileSystem.getRawFile(filePath).getPath());
boolean exists = FileSystem.exists(filePath);
TemplateConfig.OverwriteOptions overwrite = template.getOverwrite();
if (regen && overwrite == TemplateConfig.OverwriteOptions.SKIP)
overwrite = TemplateConfig.OverwriteOptions.BACKUP;
talkingWindow.show(" -> " + filePath);
if (exists && overwrite == TemplateConfig.OverwriteOptions.SKIP) {
talkingWindow.showLine(" (skipped)");
continue;
}
if (exists) {
String oldContent;
try {
oldContent = FileSystem.readStream(FileSystem.getResource(new ResourcePath(filePath, false)));
} catch (FileNotFoundException e) {
Log.e("Fatal error, cannot find resource " + filePath, e);
throw new IllegalStateException(e);
}
if (oldContent.equals(output)) {
talkingWindow.show(" (skipped, identical)");
} else {
if (overwrite == TemplateConfig.OverwriteOptions.FORCE) {
talkingWindow.show(" (force overwrite)");
FileSystem.writeFile(filePath, output);
}
else {
talkingWindow.show(" (backup and overwrite)");
FileSystem.backup(filePath); // Backup the old files
FileSystem.writeFile(filePath, output);
}
}
}
else {
FileSystem.writeFile(filePath, output);
}
if (template.getAfterFileGen() != null) {
CommandConfig afterGen = template.getAfterFileGen();
String[] commands = new String[afterGen.getArguments().length + 1];
commands[0] = afterGen.getExecute();
for (int i = 1; i < commands.length; ++i) {
commands[i] = currentEngine.render(afterGen.getArguments()[i - 1], mergeModels(currentModel, indivModel));
}
long timeout = 1000L * afterGen.getTimeout();
talkingWindow.showLine("");
talkingWindow.indent();
talkingWindow.showLine("After generation action: ");
talkingWindow.indent();
talkingWindow.showLine(String.format("(%s)$ %s", fileFolder, StringUtil.join(commands, " ")));
talkingWindow.show("Exit status (-1 means exception): " + ExternalSystem.runExternalCommand(FileSystem.getRawFile(fileFolder), timeout, commands));
talkingWindow.unindent();
talkingWindow.unindent();
}
}
talkingWindow.showLine("");
}
talkingWindow.showLine("All set, good luck!");
talkingWindow.showLine("");
}
|
diff --git a/src/org/jwildfire/create/tina/variation/BubbleFunc.java b/src/org/jwildfire/create/tina/variation/BubbleFunc.java
index 76bee047..5445ae08 100644
--- a/src/org/jwildfire/create/tina/variation/BubbleFunc.java
+++ b/src/org/jwildfire/create/tina/variation/BubbleFunc.java
@@ -1,36 +1,38 @@
/*
JWildfire - an image and animation processor written in Java
Copyright (C) 1995-2011 Andreas Maschke
This is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser
General Public License as published by the Free Software Foundation; either version 2.1 of the
License, or (at your option) any later version.
This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with this software;
if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jwildfire.create.tina.variation;
import org.jwildfire.create.tina.base.XForm;
import org.jwildfire.create.tina.base.XYZPoint;
public class BubbleFunc extends SimpleVariationFunc {
@Override
public void transform(TransformationContext pContext, XForm pXForm, XYZPoint pAffineTP, XYZPoint pVarTP, double pAmount) {
- double r = pAmount / ((pAffineTP.x * pAffineTP.x + pAffineTP.y * pAffineTP.y) / 4.0 + 1.0);
- pVarTP.x += r * pAffineTP.x;
- pVarTP.y += r * pAffineTP.y;
+ double r = ((pAffineTP.x * pAffineTP.x + pAffineTP.y * pAffineTP.y) / 4.0 + 1.0);
+ double t = pAmount / r;
+ pVarTP.x += t * pAffineTP.x;
+ pVarTP.y += t * pAffineTP.y;
+ pVarTP.z += pAmount * (2.0 / r - 1);
}
@Override
public String getName() {
return "bubble";
}
}
| true | true | public void transform(TransformationContext pContext, XForm pXForm, XYZPoint pAffineTP, XYZPoint pVarTP, double pAmount) {
double r = pAmount / ((pAffineTP.x * pAffineTP.x + pAffineTP.y * pAffineTP.y) / 4.0 + 1.0);
pVarTP.x += r * pAffineTP.x;
pVarTP.y += r * pAffineTP.y;
}
| public void transform(TransformationContext pContext, XForm pXForm, XYZPoint pAffineTP, XYZPoint pVarTP, double pAmount) {
double r = ((pAffineTP.x * pAffineTP.x + pAffineTP.y * pAffineTP.y) / 4.0 + 1.0);
double t = pAmount / r;
pVarTP.x += t * pAffineTP.x;
pVarTP.y += t * pAffineTP.y;
pVarTP.z += pAmount * (2.0 / r - 1);
}
|
diff --git a/src/ch/rollis/emma/RequestHandler.java b/src/ch/rollis/emma/RequestHandler.java
index 50b6462..c717843 100644
--- a/src/ch/rollis/emma/RequestHandler.java
+++ b/src/ch/rollis/emma/RequestHandler.java
@@ -1,189 +1,189 @@
package ch.rollis.emma;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import ch.rollis.emma.contenthandler.ContentHandler;
import ch.rollis.emma.contenthandler.ContentHandlerFactory;
import ch.rollis.emma.context.ServerContext;
import ch.rollis.emma.context.ServerContextManager;
import ch.rollis.emma.request.HttpProtocolException;
import ch.rollis.emma.request.HttpProtocolParser;
import ch.rollis.emma.request.Request;
import ch.rollis.emma.response.Response;
import ch.rollis.emma.response.ResponseFactory;
import ch.rollis.emma.response.ResponseStatus;
import ch.rollis.emma.util.DateConverter;
import ch.rollis.emma.util.DateConverterException;
/**
* The request handler has the responsibility to handle a client request and
* dispatch the request to an appropriate content handler.
* <p>
* The request handler reads in the client's request data, transforms this data
* to request by using the HttpProtocolParser and then dispatches the request to
* an appropriate content handler. Finally after the content handler returns the
* response the request handler writes the response to the output stream and
* therefore back to client.
*
* @author mrolli
*/
public class RequestHandler implements Runnable {
/**
* Communication socket this request originates from.
*/
private final Socket comSocket;
/**
* Flag denotes if connection is SSL secured.
*/
private final boolean sslSecured;
/**
* Manager to get ServerContexts for the given request from.
*/
private final ServerContextManager scm;
/**
* Logger instance this handler shall log its messages to.
*/
private final Logger logger;
/**
* Class constructor that generates a request handler that handles a HTTP
* request initiated by a client.
*
* @param socket
* The socket the connection has been established
* @param sslFlag
* Flag that denotes if connection is SSL secured
* @param loggerInstance
* Global logger to log exception to
* @param contextManager
* SeverContextManager to get the server context of for the
* request
*/
public RequestHandler(final Socket socket, final boolean sslFlag, final Logger loggerInstance,
final ServerContextManager contextManager) {
comSocket = socket;
sslSecured = sslFlag;
scm = contextManager;
logger = loggerInstance;
}
@Override
public void run() {
logger.log(Level.INFO, Thread.currentThread().getName() + " started.");
InetAddress client = comSocket.getInetAddress();
try {
InputStream input = comSocket.getInputStream();
OutputStream output = comSocket.getOutputStream();
while (!Thread.currentThread().isInterrupted()) {
HttpProtocolParser parser = new HttpProtocolParser(input);
try {
Request request;
// setup request timer to handle situations where the client
// does not send anything
Thread timer = new Thread(new RequestHandlerTimeout(comSocket, 15000, logger));
timer.start();
try {
request = parser.parse();
} catch (SocketException e) {
throw new RequestTimeoutException(e);
}
timer.interrupt();
request.setPort(comSocket.getLocalPort());
request.setIsSslSecured(sslSecured);
ServerContext context = scm.getContext(request);
ContentHandler handler = new ContentHandlerFactory().getHandler(request);
Response response = handler.process(request, context);
response.send(output);
context.log(Level.INFO, getLogMessage(client, request, response));
// break if not HTTP/1.1 and keep-alive is not set or if an
// error occurred
if (!request.getProtocol().equals("HTTP/1.1")
|| response.getStatus().getCode() >= 400) {
break;
}
} catch (HttpProtocolException e) {
logger.log(Level.WARNING, "HTTP protocol violation", e);
Response response = new ResponseFactory()
.getResponse(ResponseStatus.BAD_REQUEST);
response.send(output);
break;
}
}
} catch (RequestTimeoutException e) {
- logger.log(Level.SEVERE, "Request timeout reched", e);
+ logger.log(Level.INFO, "Request timeout reached", e);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error in RequestHandler", e);
// try to gracefully inform the client
if (!comSocket.isOutputShutdown()) {
Response response = new ResponseFactory()
.getResponse(ResponseStatus.INTERNAL_SERVER_ERROR);
try {
response.send(comSocket.getOutputStream());
} catch (IOException ioe) {
// do nothing
}
}
} finally {
if (comSocket != null && !comSocket.isClosed()) {
try {
comSocket.close();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error while closing com socket");
}
}
}
logger.log(Level.INFO, Thread.currentThread().getName() + " ended.");
}
/**
* Returns a string representation of a request by a client and its response
* that then can be i.e. logged.
*
* @param client
* InetAddres representing the client of the request
* @param request
* The request received
* @param response
* The response to the request received
* @return The string representation
*/
private String getLogMessage(final InetAddress client, final Request request,
final Response response) {
String date = DateConverter.formatLog(new Date());
String requestDate = response.getHeader("Date");
try {
if (requestDate != null) {
date = DateConverter.formatLog(DateConverter.dateFromString(requestDate));
}
} catch (DateConverterException e) {
// do nothing
logger.log(Level.WARNING, "Invalid date encountered: " + requestDate.toString());
}
String logformat = "%s [%s] \"%s %s %s\" %s %s";
return String.format(logformat, client.getHostAddress(), date,
request.getMethod(), request.getRequestURI().toString(),
request.getProtocol(), response.getStatus().getCode(), response
.getHeader("Content-Length"));
}
}
| true | true | public void run() {
logger.log(Level.INFO, Thread.currentThread().getName() + " started.");
InetAddress client = comSocket.getInetAddress();
try {
InputStream input = comSocket.getInputStream();
OutputStream output = comSocket.getOutputStream();
while (!Thread.currentThread().isInterrupted()) {
HttpProtocolParser parser = new HttpProtocolParser(input);
try {
Request request;
// setup request timer to handle situations where the client
// does not send anything
Thread timer = new Thread(new RequestHandlerTimeout(comSocket, 15000, logger));
timer.start();
try {
request = parser.parse();
} catch (SocketException e) {
throw new RequestTimeoutException(e);
}
timer.interrupt();
request.setPort(comSocket.getLocalPort());
request.setIsSslSecured(sslSecured);
ServerContext context = scm.getContext(request);
ContentHandler handler = new ContentHandlerFactory().getHandler(request);
Response response = handler.process(request, context);
response.send(output);
context.log(Level.INFO, getLogMessage(client, request, response));
// break if not HTTP/1.1 and keep-alive is not set or if an
// error occurred
if (!request.getProtocol().equals("HTTP/1.1")
|| response.getStatus().getCode() >= 400) {
break;
}
} catch (HttpProtocolException e) {
logger.log(Level.WARNING, "HTTP protocol violation", e);
Response response = new ResponseFactory()
.getResponse(ResponseStatus.BAD_REQUEST);
response.send(output);
break;
}
}
} catch (RequestTimeoutException e) {
logger.log(Level.SEVERE, "Request timeout reched", e);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error in RequestHandler", e);
// try to gracefully inform the client
if (!comSocket.isOutputShutdown()) {
Response response = new ResponseFactory()
.getResponse(ResponseStatus.INTERNAL_SERVER_ERROR);
try {
response.send(comSocket.getOutputStream());
} catch (IOException ioe) {
// do nothing
}
}
} finally {
if (comSocket != null && !comSocket.isClosed()) {
try {
comSocket.close();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error while closing com socket");
}
}
}
logger.log(Level.INFO, Thread.currentThread().getName() + " ended.");
}
| public void run() {
logger.log(Level.INFO, Thread.currentThread().getName() + " started.");
InetAddress client = comSocket.getInetAddress();
try {
InputStream input = comSocket.getInputStream();
OutputStream output = comSocket.getOutputStream();
while (!Thread.currentThread().isInterrupted()) {
HttpProtocolParser parser = new HttpProtocolParser(input);
try {
Request request;
// setup request timer to handle situations where the client
// does not send anything
Thread timer = new Thread(new RequestHandlerTimeout(comSocket, 15000, logger));
timer.start();
try {
request = parser.parse();
} catch (SocketException e) {
throw new RequestTimeoutException(e);
}
timer.interrupt();
request.setPort(comSocket.getLocalPort());
request.setIsSslSecured(sslSecured);
ServerContext context = scm.getContext(request);
ContentHandler handler = new ContentHandlerFactory().getHandler(request);
Response response = handler.process(request, context);
response.send(output);
context.log(Level.INFO, getLogMessage(client, request, response));
// break if not HTTP/1.1 and keep-alive is not set or if an
// error occurred
if (!request.getProtocol().equals("HTTP/1.1")
|| response.getStatus().getCode() >= 400) {
break;
}
} catch (HttpProtocolException e) {
logger.log(Level.WARNING, "HTTP protocol violation", e);
Response response = new ResponseFactory()
.getResponse(ResponseStatus.BAD_REQUEST);
response.send(output);
break;
}
}
} catch (RequestTimeoutException e) {
logger.log(Level.INFO, "Request timeout reached", e);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error in RequestHandler", e);
// try to gracefully inform the client
if (!comSocket.isOutputShutdown()) {
Response response = new ResponseFactory()
.getResponse(ResponseStatus.INTERNAL_SERVER_ERROR);
try {
response.send(comSocket.getOutputStream());
} catch (IOException ioe) {
// do nothing
}
}
} finally {
if (comSocket != null && !comSocket.isClosed()) {
try {
comSocket.close();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error while closing com socket");
}
}
}
logger.log(Level.INFO, Thread.currentThread().getName() + " ended.");
}
|
diff --git a/tpc/common/trace/dbTrace.java b/tpc/common/trace/dbTrace.java
index de4d562..b2c1983 100644
--- a/tpc/common/trace/dbTrace.java
+++ b/tpc/common/trace/dbTrace.java
@@ -1,709 +1,709 @@
package Escada.tpc.common.trace;
import com.renesys.raceway.DML.*;
import Escada.interfaces.*;
import Escada.xest.*;
import Escada.tpc.common.*;
import Escada.ddb.kernel.*;
import Escada.Util.*;
import java.util.*;
import java.io.*;
/**
* It defines a set of objects used to store information about a transaction. Specifically, it stores
* the read and write sets and establishes a distinction between local and remote operations. It identifies the tables
* used also establishing a distinction between local and remote operations, read and write access. Finally,
* it computes the size of the read and write operations according to the number of items accessed
* and the size of the tuples.
**/
class BagTransaction
{
Transaction trans = null;
TreeSet masterWS = new TreeSet();
TreeSet masterRS = new TreeSet();
TreeSet slaveWS = new TreeSet();
TreeSet slaveRS = new TreeSet();
HashSet tableSlaveWS = new HashSet();
HashSet tableSlaveRS = new HashSet();
HashSet tableMasterWS = new HashSet();
HashSet tableMasterRS = new HashSet();
int masterws = 0;
int masterrs = 0;
int slavews = 0;
int slavers = 0;
int maxLength = 0;
}
/**
* Basically, this class is responsible to capture the execution of transactions and translate it to
* read and written items. From the perspective of the data, it is the main point in order to integrate
* the benchmarks into a simulated environment.
**/
public class dbTrace {
private static Hashtable outPutBag = new Hashtable();
private static long tid = 0;
private static DMLDBInfo dmlinfo = DMLDB.dmldb;
/**
* It registers for each operation the relations manipulated, the read and write sets.
*
* @param HashSet a set with the accessed items.
* @param String the type of access which means read or write.
* @param String the transaction identification, that is, the unique identifier.
* @param String table
**/
public static void TransactionTrace(HashSet v, String type,
String tid, String table, int index,String hid) {
try {
BagTransaction bagtrans = (BagTransaction) outPutBag.get(tid);
Transaction tran = bagtrans.trans;
String name = tran.header().name();
String tableId = getTableIdentification(table, index);
long offset = dmlinfo.tablename_offset(tableId);
if (tran != null) {
TreeSet items = null;
if(type.equalsIgnoreCase("r")) {
if (DistributedDb.isPossibleExecution(offset,hid)) {
items = bagtrans.masterRS;
bagtrans.masterrs = bagtrans.masterrs + (int)(v.size() * dmlinfo.tuplesize(offset));
bagtrans.tableMasterRS.add(new Long(offset));
}
else {
items = bagtrans.slaveRS;
bagtrans.slavers = bagtrans.slavers + (int)(v.size() * dmlinfo.tuplesize(offset));
bagtrans.tableSlaveRS.add(new Long(offset));
}
}
else {
if (DistributedDb.isPossibleExecution(offset,hid)) {
items = bagtrans.masterWS;
bagtrans.masterws = bagtrans.masterws + (int)(v.size() * dmlinfo.tuplesize(offset));
bagtrans.tableMasterWS.add(new Long(offset));
}
else {
items = bagtrans.slaveWS;
bagtrans.slavews = bagtrans.slavews + (int)(v.size() * dmlinfo.tuplesize(offset));
bagtrans.tableSlaveWS.add(new Long(offset));
}
}
Iterator it = v.iterator();
int i=0;
while(it.hasNext()) {
long l = Long.parseLong((String)it.next());
items.add(new Long(l + offset));
i++;
}
if (bagtrans.maxLength < items.size()) bagtrans.maxLength = items.size();
}
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
/**
* It initializes the structures that stores the transaction information. First of all, it creates
* an internal object "transaction" which is used by simulator. This object is composed by
* a Header and a resource usage that is populated during the transaction execution. It also associates
* a unique identifier to the transaction.
*
* @param String the transaction name which is used to compose the header.
* @param String the amount of time to wait before submitting this transaction.
*
* @return String the transaction unique indentifier.
*
* @see closeTransactionTrance, transactionTrace.
**/
public static String initTransactionTrace(String transaction, String thinkTime) {
// Configuration dml = Simulation.config(); // porra
Header hd = new Header(transaction, (int)tid, "10"); // porra
ResourceUsage payload = new ResourceUsage(null, null, null, null);
Transaction tran = new Transaction(hd, payload,Long.parseLong(thinkTime));
BagTransaction bagtrans = new BagTransaction();
bagtrans.trans = tran;
synchronized (outPutBag)
{
tid++;
tran.header().tid((int)tid);
outPutBag.put(Long.toString(tid),bagtrans);
}
return (Long.toString(tid));
}
/**
* It saves the object transaction in a file which will be probably used off-line and also returns it.
*
* @param tid the transaction unique identifier.
* @param file the file name.
* @param hid the host id in which the transaction was processsed.
*
* @return Transaction the transaction stored in the file.
**/
public static Transaction closeTransactionTrace(String tid, String file,String hid) {
Transaction closeTransactionTrace = null;
try {
ObjectOutputStream getFile = (ObjectOutputStream) getFile(file);
closeTransactionTrace = closeTransactionTrace(tid,hid);
if (closeTransactionTrace != null) {
synchronized (outPutBag)
{
getFile.writeObject(closeTransactionTrace);
getFile.flush();
outPutBag.remove(tid);
}
}
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
return (closeTransactionTrace);
}
/**
* It returns the transaction that was captured during its execution and before returning it populates
* its resource usage defined during the creation with the information stored in the BagTransaction.
* The resource usage extends a stack and for that reason the order in which the requests for resource
* usage are inserted is extremelly important. For the current version of the simulation the order
* must be as follows:
*
* 1 - push unlock request
* 2 - push write request
* 3 - push certification request
* 4 - push cpu request
* 5 - push read request
* 6 - push thinktime request
* 7 - push lock request
* 8 - push distributed request
*
* @param tid the transaction unique identifier.
* @param hid the host id in which the transaction was processsed.
*
* @return Transaction the transaction executed and translated according the simulator specifications.
**/
public static Transaction closeTransactionTrace(String tid,String hid) {
Transaction closeTransactionTrace = null;
try {
BagTransaction bagtrans = (BagTransaction) outPutBag.get(tid);
closeTransactionTrace = bagtrans.trans;
Iterator it = null;
int i = 0, j = 0;
long lastTable = -1;
long[] masterWS = null;
long[] masterRS = null;
long[] slaveWS = null;
long[] slaveRS = null;
int[] tableMasterWS = null;
int[] tableMasterRS = null;
int[] tableSlaveWS = null;
int[] tableSlaveRS = null;
if (closeTransactionTrace != null) {
outPutBag.remove(tid);
if (bagtrans.masterWS.size() != 0)
{
masterWS = new long[bagtrans.masterWS.size()];
- tableMasterWS = new int[bagtrans.tableMasterWS.size() + 1];
+ tableMasterWS = new int[bagtrans.tableMasterWS.size()];
it = bagtrans.masterWS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
masterWS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(masterWS[i])) {
tableMasterWS[j] = i;
lastTable = dmlinfo.table_of(masterWS[i]);
j++;
}
i++;
}
}
if (bagtrans.masterRS.size() != 0)
{
masterRS = new long[bagtrans.masterRS.size()];
tableMasterRS = new int[bagtrans.tableMasterRS.size()];
it = bagtrans.masterRS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
masterRS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(masterRS[i])) {
tableMasterRS[j] = i;
lastTable = dmlinfo.table_of(masterRS[i]);
j++;
}
i++;
}
}
if (bagtrans.slaveRS.size() != 0)
{
slaveRS = new long[bagtrans.slaveRS.size()];
tableSlaveRS = new int[bagtrans.tableSlaveRS.size()];
it = bagtrans.slaveRS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
slaveRS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(slaveRS[i])) {
tableSlaveRS[j] = i;
lastTable = dmlinfo.table_of(slaveRS[i]);
j++;
}
i++;
}
}
if (bagtrans.slaveWS.size() != 0)
{
slaveWS = new long[bagtrans.slaveWS.size()];
tableSlaveWS = new int[bagtrans.tableSlaveWS.size()];
it = bagtrans.slaveWS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
slaveWS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(slaveWS[i])) {
tableSlaveWS[j] = i;
lastTable = dmlinfo.table_of(slaveWS[i]);
j++;
}
i++;
}
}
closeTransactionTrace.payload().WS(masterWS);
closeTransactionTrace.payload().RS(masterRS);
closeTransactionTrace.payload().indexOfWrittenTables(tableMasterWS);
closeTransactionTrace.payload().indexOfReadTables(tableMasterRS);
Simulation em = Simulation.self();
Tuple transModel = null;
Tuple []tmpModel = null;
if ((masterWS == null) && (slaveWS == null)) {
tmpModel = em.getTemplate(hid,true);
}
else {
tmpModel = em.getTemplate(hid,false);
}
long qttUsage = TransactionTimers.calculateQueryThinkTime(closeTransactionTrace.header().name());
long cpuUsage = TransactionTimers.calculateCPUTime(closeTransactionTrace.header().name());
Request req = null;
String info = null;
for (i = tmpModel.length - 1; i >= 0; i--) {
transModel = tmpModel[i];
if (((String)transModel.get(0)).equalsIgnoreCase("DBSMAdapter")) {
req = new NetRequest (Integer.valueOf(tid),(String)transModel.get(1),closeTransactionTrace); // DBSM
}
else if (((String)transModel.get(0)).equalsIgnoreCase("Storage")) {
info = (String)transModel.get(2);
if (info.equalsIgnoreCase("R")) {
req = new StorageRequest(Integer.valueOf(tid),(String)transModel.get(1),bagtrans.masterrs,true);
}
else {
if ((masterWS == null) && (slaveWS == null)) {
req = new StorageRequest(Integer.valueOf(tid),(String)transModel.get(1),bagtrans.masterws,false);
}
}
}
else if (((String)transModel.get(0)).equalsIgnoreCase("CPU")) {
req = new ProcessRequest(Integer.valueOf(tid),(String)transModel.get(1),cpuUsage,false); // CPU
}
else if (((String)transModel.get(0)).equalsIgnoreCase("Thinker")) {
req = new ProcessRequest(Integer.valueOf(tid),(String)transModel.get(1),qttUsage,false); // QTT
}
else if (((String)transModel.get(0)).equalsIgnoreCase("DDbProxyProcess")) {
req = new NetRequest (Integer.valueOf(tid),(String)transModel.get(1),closeTransactionTrace); // DDB
}
else if (((String)transModel.get(0)).equalsIgnoreCase("LockManager")) {
info = (String)transModel.get(2);
if (info.equalsIgnoreCase("L"))
req = new LockRequest(Integer.valueOf(tid),transModel.get(1),LockRequest.ORDER_LOCK,masterRS,masterWS,false);
else
req = new LockRequest(Integer.valueOf(tid),transModel.get(1),LockRequest.ORDER_UNLOCK,masterRS,masterWS,false);
}
closeTransactionTrace.payload().push(req);
}
}
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
return (closeTransactionTrace);
}
public static Transaction closeErrorTransactionTrace(String tid) {
Transaction closeTransactionTrace = null;
try {
BagTransaction bagtrans = (BagTransaction) outPutBag.get(tid);
closeTransactionTrace = bagtrans.trans;
if (closeTransactionTrace != null) {
outPutBag.remove(tid);
}
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
if (closeTransactionTrace != null) closeTransactionTrace.setInducedAbort();
return (closeTransactionTrace);
}
public static synchronized void generateOtherInformation(String transaction) {
try {
Runtime r = Runtime.getRuntime();
Process proc = r.exec("./scriptlog.sh " + transaction);
InputStreamReader reader = new InputStreamReader(proc.getInputStream());
while (reader.read() != -1) {
}
proc.waitFor();
proc.exitValue();
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
}
public static ObjectOutputStream getFile(String file) {
ObjectOutputStream getFile = (ObjectOutputStream) outPutBag.get(file);
try {
if (getFile == null) {
getFile = new ObjectOutputStream(new FileOutputStream(file));
if (getFile == null) {
throw new Exception("Problem opening archive.");
}
}
outPutBag.put(file, getFile);
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
return (getFile);
}
public static PrintStream getStringFile(String baseDirectory,
String file) {
PrintStream getStringFile = (PrintStream) outPutBag.get(file.toLowerCase());
try {
if (getStringFile == null) {
getStringFile = new PrintStream(new FileOutputStream(baseDirectory +
"/" + file));
if (getStringFile == null) {
throw new Exception("Problem opening archive.");
}
}
outPutBag.put(file.toLowerCase(), getStringFile);
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
return (getStringFile);
}
public static String getTableIdentification(String table, int index) {
int frag = 1;
String tablename = null;
frag = index - 1;
if ((dmlinfo.isFragmentedDatabase()) && (!dmlinfo.isGlobalTable(table))) {
tablename = table + frag;
}
else
{
tablename = table;
}
return (tablename);
}
public static void compileTransactionTrace(String trans,
String idStringTrace) {
}
public static void compileTransactionTrace(String trans,
OutInfo obj) {
String stm = null;
String param = null;
String value = null;
int loop = 0;
String stmbkp = null;
String parambkp = null;
int valuebkp = 0;
boolean noOutput = false;
PrintStream pts = getStringFile("trace", (String) obj.getInfo("file"));
pts.println("Thinktime: " + (String) obj.getInfo("thinktime"));
pts.println("Transaction: " + trans);
try {
BufferedReader dread
= new BufferedReader(new InputStreamReader(new FileInputStream(
"cache" + "/" + trans)));
while ( (stm = dread.readLine()) != null) {
stm = replaceString(stm, "%master%", "");
stm = replaceString(stm, "%slave%", "");
stm = replaceString(stm, "->", "");
param = getStringParam(stm);
if (param != null) {
if (param.equalsIgnoreCase("repeat")) {
stm = replaceStringParam(stm, param, "");
param = getStringParam(stm);
value = (String) obj.getInfo(param);
stm = replaceStringParam(stm, param, "");
}
else {
value = "1";
}
loop = 0;
stmbkp = stm;
parambkp = null;
noOutput = false;
valuebkp = Integer.parseInt(value);
while (loop < valuebkp) {
stm = stmbkp;
while (stm.indexOf("%") != -1) {
param = getStringParam(stm);
if (param.indexOf("repeat") != -1) {
parambkp = param;
param = param.substring(0, param.indexOf("repeat"));
param = param.concat(Integer.toString(loop));
value = (String) obj.getInfo(param);
stm = replaceStringParam(stm, parambkp, value);
}
else if (param.indexOf("inc") != -1) {
value = Integer.toString(loop + 1);
stm = replaceStringParam(stm, param, value);
}
else if (param.equalsIgnoreCase("if")) {
stm = replaceOneStringParam(stm, param, "");
param = getStringParam(stm);
stm = replaceOneStringParam(stm, param, "");
String rstr = param.substring(0, param.indexOf("="));
String lstr = param.substring(param.indexOf("=") + 1);
value = (String) obj.getInfo(rstr);
if (value != null) {
if (!value.equalsIgnoreCase(lstr)) {
noOutput = true;
break;
}
}
else {
noOutput = true;
break;
}
}
else if (param.equalsIgnoreCase("like"))
{
stm = replaceOneStringParam(stm, param, "");
String rstr = getStringParam(stm);
stm = replaceOneStringParam(stm, rstr, "");
String lstr = getStringParam(stm);
value = (String) obj.getInfo(lstr.substring(0,lstr.length() - 1));
String like = rstr + " like '" + value + "*'";
like = parseLike(like);
stm = replaceOneStringParam(stm,lstr,like);
}
else {
value = (String) obj.getInfo(param);
stm = replaceStringParam(stm, param, value);
}
}
if (!noOutput) {
stm = stm.replace('�', '%');
pts.println(stm);
}
loop++;
}
}
else {
if (stm.indexOf("committran") != -1) {
value = (String) obj.getInfo("abort");
if (value.equalsIgnoreCase("0")) {
pts.println(stm);
}
else {
pts.println("aborttran");
}
}
else {
pts.println(stm);
}
}
}
}
catch (FileNotFoundException ex) {
}
catch (IOException ex) {
}
catch (Exception ex) {
ex.printStackTrace(System.err);
System.err.println("Statement " + stm + " param " + param + " value " +
value);
}
pts.flush();
obj.resetInfo();
}
private static String PERCENT_ASTERISK = "*";
private static String parseLike(String pLike){
String lReturn = "";
String splitLike[] = pLike.split("like");
String lField = splitLike[0];
String splitQuotations[] = pLike.split("'");
if(!splitQuotations[1].endsWith(PERCENT_ASTERISK) && !splitQuotations[1].startsWith(PERCENT_ASTERISK)){
return lField + " = '" + splitQuotations[1].substring(0,splitQuotations[1].length());
}
if(splitQuotations[1].startsWith(PERCENT_ASTERISK)){
splitQuotations[1] = splitQuotations[1].substring(1,splitQuotations[1].length());
lReturn = " %not implemented";
}
if(splitQuotations[1].endsWith(PERCENT_ASTERISK)){
lReturn += lField + " >= '"
+ splitQuotations[1].substring(0,splitQuotations[1].length()-1)
+ "' and "
+ lField
+ " < '"
+ splitQuotations[1].substring(0,splitQuotations[1].length()-2)
+ (char)((int)splitQuotations[1].substring(splitQuotations[1].length()-2,splitQuotations[1].length()-1).charAt(0)+1)
+ "'";
}
return lReturn;
}
private static String getStringParam(String stm) {
if (stm == null) {
return (null);
}
int posini = stm.indexOf("%");
int posend = stm.indexOf("%", posini + 1);
if ( (posini == -1) || (posend == -1)) {
return (null);
}
else {
return (stm.substring(posini + 1, posend));
}
}
private static String replaceOneStringParam(String stm, String param,
String value) {
int posini = -1, posend = -1;
if ( (stm == null) || (param == null)) {
return (stm);
}
else if (value == null) {
value = "0";
}
param = "%" + param + "%";
posini = stm.indexOf(param);
posend = param.length() + posini;
stm = stm.substring(0, posini) + value.replace('%', '�') +
stm.substring(posend);
return (stm);
}
private static String replaceStringParam(String stm, String param,
String value) {
if ( (stm == null) || (param == null)) {
return (stm);
}
else if (value == null) {
value = "0";
}
return (replaceString(stm, "%" + param + "%", value));
}
private static String replaceString(String stm, String param,
String value) {
int posini = -1, posend = -1;
if (param == null || stm == null || value == null) {
return (stm);
}
while (stm.indexOf(param) != -1) {
posini = stm.indexOf(param);
posend = param.length() + posini;
stm = stm.substring(0, posini) + value.replace('%', '�') +
stm.substring(posend);
}
return (stm);
}
}
// arch-tag: cd27b7fe-ae93-483e-af78-79491b558ac0
// arch-tag: e932c514-e0b2-4b45-9a47-902984767993
| true | true | public static Transaction closeTransactionTrace(String tid,String hid) {
Transaction closeTransactionTrace = null;
try {
BagTransaction bagtrans = (BagTransaction) outPutBag.get(tid);
closeTransactionTrace = bagtrans.trans;
Iterator it = null;
int i = 0, j = 0;
long lastTable = -1;
long[] masterWS = null;
long[] masterRS = null;
long[] slaveWS = null;
long[] slaveRS = null;
int[] tableMasterWS = null;
int[] tableMasterRS = null;
int[] tableSlaveWS = null;
int[] tableSlaveRS = null;
if (closeTransactionTrace != null) {
outPutBag.remove(tid);
if (bagtrans.masterWS.size() != 0)
{
masterWS = new long[bagtrans.masterWS.size()];
tableMasterWS = new int[bagtrans.tableMasterWS.size() + 1];
it = bagtrans.masterWS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
masterWS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(masterWS[i])) {
tableMasterWS[j] = i;
lastTable = dmlinfo.table_of(masterWS[i]);
j++;
}
i++;
}
}
if (bagtrans.masterRS.size() != 0)
{
masterRS = new long[bagtrans.masterRS.size()];
tableMasterRS = new int[bagtrans.tableMasterRS.size()];
it = bagtrans.masterRS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
masterRS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(masterRS[i])) {
tableMasterRS[j] = i;
lastTable = dmlinfo.table_of(masterRS[i]);
j++;
}
i++;
}
}
if (bagtrans.slaveRS.size() != 0)
{
slaveRS = new long[bagtrans.slaveRS.size()];
tableSlaveRS = new int[bagtrans.tableSlaveRS.size()];
it = bagtrans.slaveRS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
slaveRS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(slaveRS[i])) {
tableSlaveRS[j] = i;
lastTable = dmlinfo.table_of(slaveRS[i]);
j++;
}
i++;
}
}
if (bagtrans.slaveWS.size() != 0)
{
slaveWS = new long[bagtrans.slaveWS.size()];
tableSlaveWS = new int[bagtrans.tableSlaveWS.size()];
it = bagtrans.slaveWS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
slaveWS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(slaveWS[i])) {
tableSlaveWS[j] = i;
lastTable = dmlinfo.table_of(slaveWS[i]);
j++;
}
i++;
}
}
closeTransactionTrace.payload().WS(masterWS);
closeTransactionTrace.payload().RS(masterRS);
closeTransactionTrace.payload().indexOfWrittenTables(tableMasterWS);
closeTransactionTrace.payload().indexOfReadTables(tableMasterRS);
Simulation em = Simulation.self();
Tuple transModel = null;
Tuple []tmpModel = null;
if ((masterWS == null) && (slaveWS == null)) {
tmpModel = em.getTemplate(hid,true);
}
else {
tmpModel = em.getTemplate(hid,false);
}
long qttUsage = TransactionTimers.calculateQueryThinkTime(closeTransactionTrace.header().name());
long cpuUsage = TransactionTimers.calculateCPUTime(closeTransactionTrace.header().name());
Request req = null;
String info = null;
for (i = tmpModel.length - 1; i >= 0; i--) {
transModel = tmpModel[i];
if (((String)transModel.get(0)).equalsIgnoreCase("DBSMAdapter")) {
req = new NetRequest (Integer.valueOf(tid),(String)transModel.get(1),closeTransactionTrace); // DBSM
}
else if (((String)transModel.get(0)).equalsIgnoreCase("Storage")) {
info = (String)transModel.get(2);
if (info.equalsIgnoreCase("R")) {
req = new StorageRequest(Integer.valueOf(tid),(String)transModel.get(1),bagtrans.masterrs,true);
}
else {
if ((masterWS == null) && (slaveWS == null)) {
req = new StorageRequest(Integer.valueOf(tid),(String)transModel.get(1),bagtrans.masterws,false);
}
}
}
else if (((String)transModel.get(0)).equalsIgnoreCase("CPU")) {
req = new ProcessRequest(Integer.valueOf(tid),(String)transModel.get(1),cpuUsage,false); // CPU
}
else if (((String)transModel.get(0)).equalsIgnoreCase("Thinker")) {
req = new ProcessRequest(Integer.valueOf(tid),(String)transModel.get(1),qttUsage,false); // QTT
}
else if (((String)transModel.get(0)).equalsIgnoreCase("DDbProxyProcess")) {
req = new NetRequest (Integer.valueOf(tid),(String)transModel.get(1),closeTransactionTrace); // DDB
}
else if (((String)transModel.get(0)).equalsIgnoreCase("LockManager")) {
info = (String)transModel.get(2);
if (info.equalsIgnoreCase("L"))
req = new LockRequest(Integer.valueOf(tid),transModel.get(1),LockRequest.ORDER_LOCK,masterRS,masterWS,false);
else
req = new LockRequest(Integer.valueOf(tid),transModel.get(1),LockRequest.ORDER_UNLOCK,masterRS,masterWS,false);
}
closeTransactionTrace.payload().push(req);
}
}
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
return (closeTransactionTrace);
}
| public static Transaction closeTransactionTrace(String tid,String hid) {
Transaction closeTransactionTrace = null;
try {
BagTransaction bagtrans = (BagTransaction) outPutBag.get(tid);
closeTransactionTrace = bagtrans.trans;
Iterator it = null;
int i = 0, j = 0;
long lastTable = -1;
long[] masterWS = null;
long[] masterRS = null;
long[] slaveWS = null;
long[] slaveRS = null;
int[] tableMasterWS = null;
int[] tableMasterRS = null;
int[] tableSlaveWS = null;
int[] tableSlaveRS = null;
if (closeTransactionTrace != null) {
outPutBag.remove(tid);
if (bagtrans.masterWS.size() != 0)
{
masterWS = new long[bagtrans.masterWS.size()];
tableMasterWS = new int[bagtrans.tableMasterWS.size()];
it = bagtrans.masterWS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
masterWS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(masterWS[i])) {
tableMasterWS[j] = i;
lastTable = dmlinfo.table_of(masterWS[i]);
j++;
}
i++;
}
}
if (bagtrans.masterRS.size() != 0)
{
masterRS = new long[bagtrans.masterRS.size()];
tableMasterRS = new int[bagtrans.tableMasterRS.size()];
it = bagtrans.masterRS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
masterRS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(masterRS[i])) {
tableMasterRS[j] = i;
lastTable = dmlinfo.table_of(masterRS[i]);
j++;
}
i++;
}
}
if (bagtrans.slaveRS.size() != 0)
{
slaveRS = new long[bagtrans.slaveRS.size()];
tableSlaveRS = new int[bagtrans.tableSlaveRS.size()];
it = bagtrans.slaveRS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
slaveRS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(slaveRS[i])) {
tableSlaveRS[j] = i;
lastTable = dmlinfo.table_of(slaveRS[i]);
j++;
}
i++;
}
}
if (bagtrans.slaveWS.size() != 0)
{
slaveWS = new long[bagtrans.slaveWS.size()];
tableSlaveWS = new int[bagtrans.tableSlaveWS.size()];
it = bagtrans.slaveWS.iterator();
i = 0; j = 0; lastTable = -1;
while(it.hasNext()) {
slaveWS[i] = ((Long)it.next()).longValue();
if (lastTable != dmlinfo.table_of(slaveWS[i])) {
tableSlaveWS[j] = i;
lastTable = dmlinfo.table_of(slaveWS[i]);
j++;
}
i++;
}
}
closeTransactionTrace.payload().WS(masterWS);
closeTransactionTrace.payload().RS(masterRS);
closeTransactionTrace.payload().indexOfWrittenTables(tableMasterWS);
closeTransactionTrace.payload().indexOfReadTables(tableMasterRS);
Simulation em = Simulation.self();
Tuple transModel = null;
Tuple []tmpModel = null;
if ((masterWS == null) && (slaveWS == null)) {
tmpModel = em.getTemplate(hid,true);
}
else {
tmpModel = em.getTemplate(hid,false);
}
long qttUsage = TransactionTimers.calculateQueryThinkTime(closeTransactionTrace.header().name());
long cpuUsage = TransactionTimers.calculateCPUTime(closeTransactionTrace.header().name());
Request req = null;
String info = null;
for (i = tmpModel.length - 1; i >= 0; i--) {
transModel = tmpModel[i];
if (((String)transModel.get(0)).equalsIgnoreCase("DBSMAdapter")) {
req = new NetRequest (Integer.valueOf(tid),(String)transModel.get(1),closeTransactionTrace); // DBSM
}
else if (((String)transModel.get(0)).equalsIgnoreCase("Storage")) {
info = (String)transModel.get(2);
if (info.equalsIgnoreCase("R")) {
req = new StorageRequest(Integer.valueOf(tid),(String)transModel.get(1),bagtrans.masterrs,true);
}
else {
if ((masterWS == null) && (slaveWS == null)) {
req = new StorageRequest(Integer.valueOf(tid),(String)transModel.get(1),bagtrans.masterws,false);
}
}
}
else if (((String)transModel.get(0)).equalsIgnoreCase("CPU")) {
req = new ProcessRequest(Integer.valueOf(tid),(String)transModel.get(1),cpuUsage,false); // CPU
}
else if (((String)transModel.get(0)).equalsIgnoreCase("Thinker")) {
req = new ProcessRequest(Integer.valueOf(tid),(String)transModel.get(1),qttUsage,false); // QTT
}
else if (((String)transModel.get(0)).equalsIgnoreCase("DDbProxyProcess")) {
req = new NetRequest (Integer.valueOf(tid),(String)transModel.get(1),closeTransactionTrace); // DDB
}
else if (((String)transModel.get(0)).equalsIgnoreCase("LockManager")) {
info = (String)transModel.get(2);
if (info.equalsIgnoreCase("L"))
req = new LockRequest(Integer.valueOf(tid),transModel.get(1),LockRequest.ORDER_LOCK,masterRS,masterWS,false);
else
req = new LockRequest(Integer.valueOf(tid),transModel.get(1),LockRequest.ORDER_UNLOCK,masterRS,masterWS,false);
}
closeTransactionTrace.payload().push(req);
}
}
}
catch (Exception ex) {
ex.printStackTrace(System.err);
}
return (closeTransactionTrace);
}
|
diff --git a/project3/edu/berkeley/cs/cs162/Server/ClientLogic.java b/project3/edu/berkeley/cs/cs162/Server/ClientLogic.java
index 7250061..83fa140 100644
--- a/project3/edu/berkeley/cs/cs162/Server/ClientLogic.java
+++ b/project3/edu/berkeley/cs/cs162/Server/ClientLogic.java
@@ -1,106 +1,109 @@
package edu.berkeley.cs.cs162.Server;
import edu.berkeley.cs.cs162.Synchronization.Lock;
import edu.berkeley.cs.cs162.Writable.ClientInfo;
import edu.berkeley.cs.cs162.Writable.ClientMessages;
import edu.berkeley.cs.cs162.Writable.ClientMessages.ChangePasswordMessage;
import edu.berkeley.cs.cs162.Writable.GameInfo;
import edu.berkeley.cs.cs162.Writable.Message;
import edu.berkeley.cs.cs162.Writable.MessageFactory;
import edu.berkeley.cs.cs162.Writable.MessageProtocol;
public abstract class ClientLogic {
private String name;
private GameServer server;
Lock observingLock;
private int clientID;
public ClientLogic(GameServer server, String name) {
this.name = name;
this.server = server;
observingLock = new Lock();
}
public static ClientLogic getClientLogicForClientType(GameServer server, String name, byte playerType, ClientConnection connection) {
switch (playerType) {
case MessageProtocol.TYPE_HUMAN:
return new PlayerLogic.HumanPlayerLogic(server, connection, name);
case MessageProtocol.TYPE_MACHINE:
return new PlayerLogic.MachinePlayerLogic(server, connection, name);
case MessageProtocol.TYPE_OBSERVER:
return new ObserverLogic(server, connection, name);
}
throw new AssertionError("Unknown Client Type");
}
public Message handleMessage(Message message) {
switch (message.getMsgType()) {
case MessageProtocol.OP_TYPE_LISTGAMES: {
return handleListGames();
}
case MessageProtocol.OP_TYPE_JOIN: {
return handleJoinGame(((ClientMessages.JoinMessage) message).getGameInfo());
}
case MessageProtocol.OP_TYPE_LEAVE: {
return handleLeaveGame(((ClientMessages.LeaveMessage)message).getGameInfo());
}
case MessageProtocol.OP_TYPE_WAITFORGAME: {
return handleWaitForGame();
}
case MessageProtocol.OP_TYPE_DISCONNECT: {
return null;
}
case MessageProtocol.OP_TYPE_CHANGEPW: {
return handleChangePassword((ChangePasswordMessage) message);
}
case MessageProtocol.OP_TYPE_REGISTER: {
return MessageFactory.createErrorRejectedMessage();
}
+ case MessageProtocol.OP_TYPE_CONNECT: {
+ return MessageFactory.createErrorRejectedMessage();
+ }
}
throw new AssertionError("Unimplemented Method");
}
public Message handleChangePassword(ClientMessages.ChangePasswordMessage message) {
if (message.getClientInfo().equals(makeClientInfo())) {
getServer().getAuthenticationManager().changePassword(message.getClientInfo(), message.getPasswordHash());
return MessageFactory.createStatusOkMessage();
}
else {
return MessageFactory.createErrorRejectedMessage();
}
}
public Message handleWaitForGame() {
return MessageFactory.createErrorRejectedMessage();
}
public Message handleLeaveGame(GameInfo gameInfo) {
return MessageFactory.createErrorRejectedMessage();
}
public Message handleJoinGame(GameInfo gameInfo) {
return MessageFactory.createErrorRejectedMessage();
}
public Message handleListGames() {
return MessageFactory.createErrorRejectedMessage();
}
public GameServer getServer() {
return server;
}
public String getName() {
return name;
}
public abstract void handleSendMessage(Message message);
public abstract void cleanup();
public abstract ClientInfo makeClientInfo();
public void setID(int clientID) {
this.clientID = clientID;
}
public int getID() {
return clientID;
}
}
| true | true | public Message handleMessage(Message message) {
switch (message.getMsgType()) {
case MessageProtocol.OP_TYPE_LISTGAMES: {
return handleListGames();
}
case MessageProtocol.OP_TYPE_JOIN: {
return handleJoinGame(((ClientMessages.JoinMessage) message).getGameInfo());
}
case MessageProtocol.OP_TYPE_LEAVE: {
return handleLeaveGame(((ClientMessages.LeaveMessage)message).getGameInfo());
}
case MessageProtocol.OP_TYPE_WAITFORGAME: {
return handleWaitForGame();
}
case MessageProtocol.OP_TYPE_DISCONNECT: {
return null;
}
case MessageProtocol.OP_TYPE_CHANGEPW: {
return handleChangePassword((ChangePasswordMessage) message);
}
case MessageProtocol.OP_TYPE_REGISTER: {
return MessageFactory.createErrorRejectedMessage();
}
}
throw new AssertionError("Unimplemented Method");
}
| public Message handleMessage(Message message) {
switch (message.getMsgType()) {
case MessageProtocol.OP_TYPE_LISTGAMES: {
return handleListGames();
}
case MessageProtocol.OP_TYPE_JOIN: {
return handleJoinGame(((ClientMessages.JoinMessage) message).getGameInfo());
}
case MessageProtocol.OP_TYPE_LEAVE: {
return handleLeaveGame(((ClientMessages.LeaveMessage)message).getGameInfo());
}
case MessageProtocol.OP_TYPE_WAITFORGAME: {
return handleWaitForGame();
}
case MessageProtocol.OP_TYPE_DISCONNECT: {
return null;
}
case MessageProtocol.OP_TYPE_CHANGEPW: {
return handleChangePassword((ChangePasswordMessage) message);
}
case MessageProtocol.OP_TYPE_REGISTER: {
return MessageFactory.createErrorRejectedMessage();
}
case MessageProtocol.OP_TYPE_CONNECT: {
return MessageFactory.createErrorRejectedMessage();
}
}
throw new AssertionError("Unimplemented Method");
}
|
diff --git a/bpm/bonita-core/bonita-process-engine/src/main/java/org/bonitasoft/engine/api/impl/PlatformAPIImpl.java b/bpm/bonita-core/bonita-process-engine/src/main/java/org/bonitasoft/engine/api/impl/PlatformAPIImpl.java
index 32a9f0a36c..402d53355f 100644
--- a/bpm/bonita-core/bonita-process-engine/src/main/java/org/bonitasoft/engine/api/impl/PlatformAPIImpl.java
+++ b/bpm/bonita-core/bonita-process-engine/src/main/java/org/bonitasoft/engine/api/impl/PlatformAPIImpl.java
@@ -1,772 +1,772 @@
/**
* Copyright (C) 2011-2013 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* 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
* version 2.1 of the License.
* 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
* program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301, USA.
**/
package org.bonitasoft.engine.api.impl;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable;
import org.apache.commons.io.FileUtils;
import org.bonitasoft.engine.api.PlatformAPI;
import org.bonitasoft.engine.api.impl.transaction.CustomTransactions;
import org.bonitasoft.engine.api.impl.transaction.platform.ActivateTenant;
import org.bonitasoft.engine.api.impl.transaction.platform.CleanPlatformTableContent;
import org.bonitasoft.engine.api.impl.transaction.platform.DeactivateTenant;
import org.bonitasoft.engine.api.impl.transaction.platform.DeleteAllTenants;
import org.bonitasoft.engine.api.impl.transaction.platform.DeletePlatformContent;
import org.bonitasoft.engine.api.impl.transaction.platform.DeletePlatformTableContent;
import org.bonitasoft.engine.api.impl.transaction.platform.DeleteTenant;
import org.bonitasoft.engine.api.impl.transaction.platform.DeleteTenantObjects;
import org.bonitasoft.engine.api.impl.transaction.platform.GetDefaultTenantInstance;
import org.bonitasoft.engine.api.impl.transaction.platform.GetPlatformContent;
import org.bonitasoft.engine.api.impl.transaction.platform.IsPlatformCreated;
import org.bonitasoft.engine.api.impl.transaction.platform.RefreshPlatformClassLoader;
import org.bonitasoft.engine.api.impl.transaction.platform.RefreshTenantClassLoaders;
import org.bonitasoft.engine.classloader.ClassLoaderException;
import org.bonitasoft.engine.command.CommandDescriptor;
import org.bonitasoft.engine.command.CommandService;
import org.bonitasoft.engine.command.DefaultCommandProvider;
import org.bonitasoft.engine.command.SCommandAlreadyExistsException;
import org.bonitasoft.engine.command.SCommandCreationException;
import org.bonitasoft.engine.command.model.SCommand;
import org.bonitasoft.engine.command.model.SCommandBuilder;
import org.bonitasoft.engine.commons.IOUtil;
import org.bonitasoft.engine.commons.RestartHandler;
import org.bonitasoft.engine.commons.exceptions.SBonitaException;
import org.bonitasoft.engine.commons.transaction.TransactionContent;
import org.bonitasoft.engine.commons.transaction.TransactionContentWithResult;
import org.bonitasoft.engine.commons.transaction.TransactionExecutor;
import org.bonitasoft.engine.data.DataService;
import org.bonitasoft.engine.data.SDataException;
import org.bonitasoft.engine.data.SDataSourceAlreadyExistException;
import org.bonitasoft.engine.data.model.SDataSource;
import org.bonitasoft.engine.data.model.SDataSourceState;
import org.bonitasoft.engine.data.model.builder.SDataSourceModelBuilder;
import org.bonitasoft.engine.dependency.SDependencyException;
import org.bonitasoft.engine.events.model.FireEventException;
import org.bonitasoft.engine.exception.BonitaHomeConfigurationException;
import org.bonitasoft.engine.exception.BonitaHomeNotSetException;
import org.bonitasoft.engine.exception.CreationException;
import org.bonitasoft.engine.exception.DeletionException;
import org.bonitasoft.engine.home.BonitaHomeServer;
import org.bonitasoft.engine.io.PropertiesManager;
import org.bonitasoft.engine.log.technical.TechnicalLogSeverity;
import org.bonitasoft.engine.log.technical.TechnicalLoggerService;
import org.bonitasoft.engine.platform.Platform;
import org.bonitasoft.engine.platform.PlatformNotFoundException;
import org.bonitasoft.engine.platform.PlatformService;
import org.bonitasoft.engine.platform.PlatformState;
import org.bonitasoft.engine.platform.SDeletingActivatedTenantException;
import org.bonitasoft.engine.platform.STenantActivationException;
import org.bonitasoft.engine.platform.STenantCreationException;
import org.bonitasoft.engine.platform.STenantDeactivationException;
import org.bonitasoft.engine.platform.STenantDeletionException;
import org.bonitasoft.engine.platform.STenantNotFoundException;
import org.bonitasoft.engine.platform.StartNodeException;
import org.bonitasoft.engine.platform.StopNodeException;
import org.bonitasoft.engine.platform.model.SPlatform;
import org.bonitasoft.engine.platform.model.STenant;
import org.bonitasoft.engine.platform.model.builder.SPlatformBuilder;
import org.bonitasoft.engine.platform.model.builder.STenantBuilder;
import org.bonitasoft.engine.restart.TenantRestartHandler;
import org.bonitasoft.engine.scheduler.SchedulerService;
import org.bonitasoft.engine.scheduler.exception.SSchedulerException;
import org.bonitasoft.engine.service.ModelConvertor;
import org.bonitasoft.engine.service.PlatformServiceAccessor;
import org.bonitasoft.engine.service.TenantServiceAccessor;
import org.bonitasoft.engine.service.impl.ServiceAccessorFactory;
import org.bonitasoft.engine.session.SessionService;
import org.bonitasoft.engine.session.model.SSession;
import org.bonitasoft.engine.sessionaccessor.SessionAccessor;
import org.bonitasoft.engine.transaction.STransactionException;
import org.bonitasoft.engine.transaction.TransactionService;
import org.bonitasoft.engine.work.WorkService;
/**
* @author Matthieu Chaffotte
* @author Elias Ricken de Medeiros
* @author Lu Kai
* @author Zhang Bole
* @author Yanyan Liu
* @author Emmanuel Duchastenier
*/
public class PlatformAPIImpl implements PlatformAPI {
private static final String STATUS_DEACTIVATED = "DEACTIVATED";
private static boolean isNodeStarted = false;
@Override
@CustomTransactions
@AvailableOnStoppedNode
public void createPlatform() throws CreationException {
PlatformServiceAccessor platformAccessor;
try {
platformAccessor = getPlatformAccessor();
} catch (final Exception e) {
throw new CreationException(e);
}
final PlatformService platformService = platformAccessor.getPlatformService();
final TransactionService transactionService = platformAccessor.getTransactionService();
try {
final SPlatform platform = constructPlatform(platformAccessor);
platformService.createPlatformTables();
platformService.createTenantTables();
transactionService.begin();
try {
platformService.initializePlatformStructure();
} finally {
transactionService.complete();
}
transactionService.begin();
try {
platformService.createPlatform(platform);
platformService.getPlatform();
} finally {
transactionService.complete();
}
} catch (final SBonitaException e) {
throw new CreationException("Platform Creation failed.", e);
} catch (final IOException ioe) {
throw new CreationException("Platform Creation failed.", ioe);
}
}
@Override
@CustomTransactions
@AvailableOnStoppedNode
public void initializePlatform() throws CreationException {
PlatformServiceAccessor platformAccessor;
try {
platformAccessor = getPlatformAccessor();
} catch (final Exception e) {
throw new CreationException(e);
}
final PlatformService platformService = platformAccessor.getPlatformService();
final TransactionService transactionService = platformAccessor.getTransactionService();
final TechnicalLoggerService technicalLoggerService = platformAccessor.getTechnicalLoggerService();
// 1 tx to create content and default tenant
try {
transactionService.begin();
try {
// inside new tx because we need sequence ids
createDefaultTenant(platformAccessor, platformService, transactionService);
activateDefaultTenant();
} catch (final SBonitaException e) {
if (technicalLoggerService.isLoggable(this.getClass(), TechnicalLogSeverity.WARNING)) {
technicalLoggerService.log(this.getClass(), TechnicalLogSeverity.WARNING, e);
}
throw new CreationException("Platform initialisation failed.", e);
} finally {
transactionService.complete();
}
} catch (final STransactionException e1) {
throw new CreationException(e1);
}
}
@Override
@CustomTransactions
@AvailableOnStoppedNode
public void createAndInitializePlatform() throws CreationException {
createPlatform();
initializePlatform();
}
protected PlatformServiceAccessor getPlatformAccessor() throws BonitaHomeNotSetException, InstantiationException, IllegalAccessException,
ClassNotFoundException, IOException, BonitaHomeConfigurationException {
return ServiceAccessorFactory.getInstance().createPlatformServiceAccessor();
}
private SPlatform constructPlatform(final PlatformServiceAccessor platformAccessor) throws IOException {
final URL resource = PlatformAPIImpl.class.getResource("platform.properties");
final Properties properties = PropertiesManager.getProperties(resource);
// FIXME construct platform object from a configuration file
final String version = (String) properties.get("version");
final String previousVersion = "";
final String initialVersion = (String) properties.get("version");
// FIXME createdBy when PlatformSessionAccessor will exist
final String createdBy = "platformAdmin";
// FIXME do that in the builder
final long created = System.currentTimeMillis();
final SPlatformBuilder platformBuilder = platformAccessor.getSPlatformBuilder();
return platformBuilder.createNewInstance(version, previousVersion, initialVersion, createdBy, created).done();
}
@Override
@CustomTransactions
@AvailableOnStoppedNode
public void startNode() throws StartNodeException {
final PlatformServiceAccessor platformAccessor;
SessionAccessor sessionAccessor = null;
try {
platformAccessor = getPlatformAccessor();
sessionAccessor = ServiceAccessorFactory.getInstance().createSessionAccessor();
} catch (final Exception e) {
throw new StartNodeException(e);
}
final NodeConfiguration platformConfiguration = platformAccessor.getPlaformConfiguration();
final SchedulerService schedulerService = platformAccessor.getSchedulerService();
WorkService workService = platformAccessor.getWorkService();
try {
try {
final TransactionExecutor executor = platformAccessor.getTransactionExecutor();
final RefreshPlatformClassLoader refreshPlatformClassLoader = new RefreshPlatformClassLoader(platformAccessor);
executor.execute(refreshPlatformClassLoader);
final List<Long> tenantIds = refreshPlatformClassLoader.getResult();
// set tenant classloader
final SessionService sessionService = platformAccessor.getSessionService();
for (final Long tenantId : tenantIds) {
long sessionId = -1;
long platformSessionId = -1;
try {
platformSessionId = sessionAccessor.getSessionId();
sessionAccessor.deleteSessionId();
sessionId = createSessionAndMakeItActive(tenantId, sessionAccessor, sessionService);
final TenantServiceAccessor tenantServiceAccessor = platformAccessor.getTenantServiceAccessor(tenantId);
final TransactionExecutor tenantExecutor = tenantServiceAccessor.getTransactionExecutor();
tenantExecutor.execute(new RefreshTenantClassLoaders(tenantServiceAccessor, tenantId));
} finally {
sessionService.deleteSession(sessionId);
cleanSessionAccessor(sessionAccessor);
sessionAccessor.setSessionInfo(platformSessionId, -1);
}
}
// FIXME: shouldn't we also stop the workService?:
workService.startup();
if (!isNodeStarted()) {
- if (platformConfiguration.shouldStartScheduler()) {
+ if (platformConfiguration.shouldStartScheduler() && !schedulerService.isStarted()) {
schedulerService.start();
}
if (platformConfiguration.shouldResumeElements()) {
// Here get all elements that are not "finished"
// * FlowNodes that have flag: stateExecuting to true: call execute on them (connectors were executing)
// * Process instances with token count == 0 (either not started again or finishing) -> same thing connectors were executing
// * transitions that are in state created: call execute on them
// * flow node that are completed and not deleted : call execute to make it create transitions and so on
// * all element that are in not stable state
final PlatformService platformService = platformAccessor.getPlatformService();
final GetDefaultTenantInstance getDefaultTenantInstance = new GetDefaultTenantInstance(platformService);
platformAccessor.getTransactionExecutor().execute(getDefaultTenantInstance);
final STenant defaultTenant = getDefaultTenantInstance.getResult();
final long tenantId = defaultTenant.getId();
final TenantServiceAccessor tenantServiceAccessor = getTenantServiceAccessor(tenantId);
final long sessionId = createSessionAndMakeItActive(defaultTenant.getId(), sessionAccessor, sessionService);
for (final TenantRestartHandler restartHandler : platformConfiguration.getTenantRestartHandlers()) {
Callable<Void> callable = new Callable<Void>() {
@Override
public Void call() throws Exception {
restartHandler.handleRestart(platformAccessor, tenantServiceAccessor);
return null;
}
};
tenantServiceAccessor.getTransactionService().executeInTransaction(callable);
}
sessionService.deleteSession(sessionId);
}
for (final RestartHandler restartHandler : platformConfiguration.getRestartHandlers()) {
restartHandler.execute();
}
}
} catch (final ClassLoaderException e) {
throw new StartNodeException("Platform starting failed while initializing platform classloaders.", e);
} catch (final SDependencyException e) {
throw new StartNodeException("Platform starting failed while initializing platform classloaders.", e);
} catch (final SBonitaException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final BonitaHomeNotSetException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final BonitaHomeConfigurationException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final IOException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final NoSuchMethodException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final InstantiationException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final IllegalAccessException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final InvocationTargetException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final Exception e) {
throw new StartNodeException("Platform starting failed.", e);
} finally {
cleanSessionAccessor(sessionAccessor);
}
isNodeStarted = true;
} catch (final StartNodeException e) {
// If an exception is thrown, stop the platform that was started.
try {
shutdownScheduler(platformAccessor, schedulerService);
} catch (final SBonitaException exp) {
throw new StartNodeException("Platform stoping failed : " + exp.getMessage(), e);
}
throw e;
}
}
protected TenantServiceAccessor getTenantServiceAccessor(final long tenantId) throws SBonitaException, BonitaHomeNotSetException, IOException,
BonitaHomeConfigurationException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
return ServiceAccessorFactory.getInstance().createTenantServiceAccessor(tenantId);
}
@Override
@CustomTransactions
@AvailableOnStoppedNode
public void stopNode() throws StopNodeException {
try {
final PlatformServiceAccessor platformAccessor = getPlatformAccessor();
final SchedulerService schedulerService = platformAccessor.getSchedulerService();
NodeConfiguration plaformConfiguration = platformAccessor.getPlaformConfiguration();
if (plaformConfiguration.shouldStartScheduler()) {
// we shutdown the scheduler only if we are also responsible of starting it
shutdownScheduler(platformAccessor, schedulerService);
}
WorkService workService = platformAccessor.getWorkService();
workService.shutdown();
if (plaformConfiguration.shouldClearSessions()) {
platformAccessor.getSessionService().deleteSessions();
}
isNodeStarted = false;
} catch (final SBonitaException e) {
throw new StopNodeException(e);
} catch (final BonitaHomeNotSetException e) {
throw new StopNodeException(e);
} catch (final InstantiationException e) {
throw new StopNodeException(e);
} catch (final IllegalAccessException e) {
throw new StopNodeException(e);
} catch (final ClassNotFoundException e) {
throw new StopNodeException(e);
} catch (final IOException e) {
throw new StopNodeException(e);
} catch (final BonitaHomeConfigurationException e) {
throw new StopNodeException(e.getMessage());
} catch (final Exception e) {
throw new StopNodeException(e);
}
}
private void shutdownScheduler(final PlatformServiceAccessor platformAccessor, final SchedulerService schedulerService) throws SSchedulerException,
FireEventException {
if (isNodeStarted()) {
schedulerService.shutdown();
}
}
@Override
@CustomTransactions
@AvailableOnStoppedNode
public void cleanPlatform() throws DeletionException {
PlatformServiceAccessor platformAccessor;
try {
platformAccessor = getPlatformAccessor();
} catch (final Exception e) {
throw new DeletionException(e);
}
final PlatformService platformService = platformAccessor.getPlatformService();
final TransactionService transactionService = platformAccessor.getTransactionService();
final CleanPlatformTableContent clean = new CleanPlatformTableContent(platformService);
final DeleteAllTenants deleteAll = new DeleteAllTenants(platformService);
try {
transactionService.executeInTransaction(new Callable<Void>() {
@Override
public Void call() throws Exception {
try {
final STenant tenant = getDefaultTenant();
deactiveTenant(tenant.getId());
} catch (STenantNotFoundException e) {
}
clean.execute();
deleteAll.execute();
return null;
}
});
} catch (Exception e) {
throw new DeletionException(e);
}
}
@Override
@CustomTransactions
@AvailableOnStoppedNode
public void deletePlatform() throws DeletionException {
// TODO : Reduce number of transactions
PlatformServiceAccessor platformAccessor;
try {
platformAccessor = getPlatformAccessor();
} catch (final Exception e) {
throw new DeletionException(e);
}
final PlatformService platformService = platformAccessor.getPlatformService();
final TransactionExecutor transactionExecutor = platformAccessor.getTransactionExecutor();
final TransactionContent deletePlatformContent = new DeletePlatformContent(platformService);
try {
final TransactionContent deleteTenantTables = new TransactionContent() {
@Override
public void execute() throws SBonitaException {
platformService.deleteTenantTables();
}
};
transactionExecutor.execute(deletePlatformContent);
transactionExecutor.execute(deleteTenantTables);
final TransactionContent deletePlatformTableContent = new DeletePlatformTableContent(platformService);
transactionExecutor.execute(deletePlatformTableContent);
} catch (final SBonitaException e) {
throw new DeletionException(e);
}
}
@Override
@CustomTransactions
@AvailableOnStoppedNode
public void cleanAndDeletePlaftorm() throws DeletionException {
cleanPlatform();
deletePlatform();
}
@Override
@AvailableOnStoppedNode
public Platform getPlatform() throws PlatformNotFoundException {
PlatformServiceAccessor platformAccessor;
try {
platformAccessor = getPlatformAccessor();
} catch (final Exception e) {
throw new PlatformNotFoundException(e);
}
final PlatformService platformService = platformAccessor.getPlatformService();
final GetPlatformContent transactionContent = new GetPlatformContent(platformService);
try {
transactionContent.execute();
} catch (final SBonitaException e) {
throw new PlatformNotFoundException(e);
}
final SPlatform sPlatform = transactionContent.getResult();
return ModelConvertor.toPlatform(sPlatform);
}
private void createDefaultTenant(final PlatformServiceAccessor platformAccessor, final PlatformService platformService,
final TransactionService transactionService) throws STenantCreationException {
final String tenantName = "default";
final String description = "Default tenant";
String userName = "";
SessionAccessor sessionAccessor = null;
long platformSessionId = -1;
try {
// add tenant to database
final String createdBy = "defaultUser";
final STenantBuilder sTenantBuilder = platformAccessor.getSTenantBuilder();
final STenant tenant = sTenantBuilder.createNewInstance(tenantName, createdBy, System.currentTimeMillis(), STATUS_DEACTIVATED, true)
.setDescription(description).done();
final Long tenantId = platformService.createTenant(tenant);
transactionService.complete();
transactionService.begin();
// add tenant folder
String targetDir;
String sourceDir;
try {
final BonitaHomeServer home = BonitaHomeServer.getInstance();
targetDir = home.getTenantsFolder() + File.separator + tenant.getId();
sourceDir = home.getTenantTemplateFolder();
} catch (final Exception e) {
deleteTenant(tenant.getId());
throw new STenantCreationException("Bonita home not set!");
}
// copy configuration file
try {
FileUtils.copyDirectory(new File(sourceDir), new File(targetDir));
} catch (final IOException e) {
IOUtil.deleteDir(new File(targetDir));
deleteTenant(tenant.getId());
throw new STenantCreationException("Copy File Exception!");
}
// Get user name
try {
userName = getUserName(tenantId);
} catch (final Exception e) {
IOUtil.deleteDir(new File(targetDir));
deleteTenant(tenant.getId());
throw new STenantCreationException("Access File Exception!");
}
final TenantServiceAccessor tenantServiceAccessor = platformAccessor.getTenantServiceAccessor(tenantId);
final SDataSourceModelBuilder sDataSourceModelBuilder = tenantServiceAccessor.getSDataSourceModelBuilder();
final DataService dataService = tenantServiceAccessor.getDataService();
final SessionService sessionService = platformAccessor.getSessionService();
final CommandService commandService = tenantServiceAccessor.getCommandService();
final SCommandBuilder commandBuilder = tenantServiceAccessor.getSCommandBuilderAccessor().getSCommandBuilder();
sessionAccessor = ServiceAccessorFactory.getInstance().createSessionAccessor();
final SSession session = sessionService.createSession(tenantId, -1L, userName, true);
platformSessionId = sessionAccessor.getSessionId();
sessionAccessor.deleteSessionId();
sessionAccessor.setSessionInfo(session.getId(), tenantId);// necessary to create default data source
createDefaultDataSource(sDataSourceModelBuilder, dataService);
final DefaultCommandProvider defaultCommandProvider = tenantServiceAccessor.getDefaultCommandProvider();
createDefaultCommands(commandService, commandBuilder, defaultCommandProvider);
sessionService.deleteSession(session.getId());
} catch (final Exception e) {
throw new STenantCreationException("Unable to create tenant " + tenantName, e);
} finally {
cleanSessionAccessor(sessionAccessor);
sessionAccessor.setSessionInfo(platformSessionId, -1);
}
}
private void cleanSessionAccessor(final SessionAccessor sessionAccessor) {
if (sessionAccessor != null) {
sessionAccessor.deleteSessionId();
}
}
protected void createDefaultCommands(final CommandService commandService, final SCommandBuilder commandBuilder, final DefaultCommandProvider provider)
throws SCommandAlreadyExistsException, SCommandCreationException {
for (final CommandDescriptor command : provider.getDefaultCommands()) {
final SCommand sCommand = commandBuilder.createNewInstance(command.getName(), command.getDescription(), command.getImplementation())
.setSystem(true).done();
commandService.create(sCommand);
}
}
protected void createDefaultDataSource(final SDataSourceModelBuilder sDataSourceModelBuilder, final DataService dataService)
throws SDataSourceAlreadyExistException, SDataException {
final SDataSource bonitaDataSource = sDataSourceModelBuilder.getDataSourceBuilder()
.createNewInstance("bonita_data_source", "6.0", SDataSourceState.ACTIVE, "org.bonitasoft.engine.data.instance.DataInstanceDataSourceImpl")
.done();
dataService.createDataSource(bonitaDataSource);
final SDataSource transientDataSource = sDataSourceModelBuilder
.getDataSourceBuilder()
.createNewInstance("bonita_transient_data_source", "6.0", SDataSourceState.ACTIVE,
"org.bonitasoft.engine.core.data.instance.impl.TransientDataInstanceDataSource").done();
dataService.createDataSource(transientDataSource);
}
private String getUserName(final long tenantId) throws IOException, BonitaHomeNotSetException {
final String tenantPath = BonitaHomeServer.getInstance().getTenantConfFolder(tenantId) + File.separator + "bonita-server.properties";
final File file = new File(tenantPath);
final Properties properties = PropertiesManager.getProperties(file);
return properties.getProperty("userName");
}
private void deleteTenant(final long tenantId) throws STenantDeletionException {
// TODO : Reduce number of transactions
PlatformServiceAccessor platformAccessor = null;
try {
platformAccessor = getPlatformAccessor();
final PlatformService platformService = platformAccessor.getPlatformService();
final TransactionExecutor transactionExecutor = platformAccessor.getTransactionExecutor();
// delete tenant objects in database
final TransactionContent transactionContentForTenantObjects = new DeleteTenantObjects(tenantId, platformService);
transactionExecutor.execute(transactionContentForTenantObjects);
// delete tenant in database
final TransactionContent transactionContentForTenant = new DeleteTenant(tenantId, platformService);
transactionExecutor.execute(transactionContentForTenant);
// delete tenant folder
final String targetDir = BonitaHomeServer.getInstance().getTenantsFolder() + File.separator + tenantId;
IOUtil.deleteDir(new File(targetDir));
} catch (final STenantNotFoundException e) {
log(platformAccessor, e);
throw new STenantDeletionException(e);
} catch (final SDeletingActivatedTenantException e) {
log(platformAccessor, e);
throw new STenantDeletionException("Unable to delete an activated tenant " + tenantId);
} catch (final Exception e) {
log(platformAccessor, e);
throw new STenantDeletionException(e);
}
}
private void activateDefaultTenant() throws STenantActivationException {
// TODO : Reduce number of transactions
PlatformServiceAccessor platformAccessor = null;
SessionAccessor sessionAccessor = null;
SchedulerService schedulerService = null;
boolean schedulerStarted = false;
long platformSessionId = -1;
try {
platformAccessor = getPlatformAccessor();
sessionAccessor = ServiceAccessorFactory.getInstance().createSessionAccessor();
final STenant tenant = getDefaultTenant();
final long tenantId = tenant.getId();
final PlatformService platformService = platformAccessor.getPlatformService();
schedulerService = platformAccessor.getSchedulerService();
final SessionService sessionService = platformAccessor.getSessionService();
final NodeConfiguration plaformConfiguration = platformAccessor.getPlaformConfiguration();
final WorkService workService = platformAccessor.getWorkService();
// here the scheduler is started only to be able to store global jobs. Once theses jobs are stored the scheduler is stopped and it will started
// definitively in startNode method
schedulerService.start();
// FIXME: commented out for the tests to not restart the scheduler all the time. Will need to be refactored. (It should be the responsibility of
// startNode() method to start the scheduler, not ActivateTenant)
// schedulerStarted = true;
platformSessionId = sessionAccessor.getSessionId();
sessionAccessor.deleteSessionId();
final long sessionId = createSessionAndMakeItActive(tenantId, sessionAccessor, sessionService);
final ActivateTenant activateTenant = new ActivateTenant(tenantId, platformService, schedulerService, plaformConfiguration,
platformAccessor.getTechnicalLoggerService(), workService);
activateTenant.execute();
sessionService.deleteSession(sessionId);
} catch (final STenantActivationException stae) {
log(platformAccessor, stae);
throw stae;
} catch (final STenantNotFoundException stnfe) {
log(platformAccessor, stnfe);
throw new STenantActivationException(stnfe);
} catch (final Exception e) {
log(platformAccessor, e);
throw new STenantActivationException(e);
} finally {
if (schedulerStarted) {
try {
// stop scheduler after scheduling global jobs
schedulerService.shutdown();
} catch (final SBonitaException e) {
log(platformAccessor, e);
throw new STenantActivationException(e);
}
}
cleanSessionAccessor(sessionAccessor);
sessionAccessor.setSessionInfo(platformSessionId, -1);
}
}
protected Long createSession(final long tenantId, final SessionService sessionService) throws SBonitaException {
return sessionService.createSession(tenantId, "system").getId();
}
private void log(final PlatformServiceAccessor platformAccessor, final Exception e) {
if (platformAccessor != null) {
platformAccessor.getTechnicalLoggerService().log(this.getClass(), TechnicalLogSeverity.ERROR, e);
} else {
e.printStackTrace();
}
}
private void deactiveTenant(final long tenantId) throws STenantDeactivationException {
// TODO : Reduce number of transactions
PlatformServiceAccessor platformAccessor = null;
SessionAccessor sessionAccessor = null;
long platformSessionId = -1;
try {
platformAccessor = getPlatformAccessor();
sessionAccessor = ServiceAccessorFactory.getInstance().createSessionAccessor();
final PlatformService platformService = platformAccessor.getPlatformService();
final SchedulerService schedulerService = platformAccessor.getSchedulerService();
final SessionService sessionService = platformAccessor.getSessionService();
final WorkService workService = platformAccessor.getWorkService();
final long sessionId = createSession(tenantId, sessionService);
platformSessionId = sessionAccessor.getSessionId();
sessionAccessor.deleteSessionId();
final TransactionContent transactionContent = new DeactivateTenant(tenantId, platformService, schedulerService, workService, sessionService);
transactionContent.execute();
sessionService.deleteSession(sessionId);
sessionService.deleteSessionsOfTenant(tenantId);
} catch (final STenantDeactivationException stde) {
log(platformAccessor, stde);
throw stde;
} catch (final Exception e) {
log(platformAccessor, e);
throw new STenantDeactivationException("Tenant deactivation failed.", e);
} finally {
cleanSessionAccessor(sessionAccessor);
sessionAccessor.setSessionInfo(platformSessionId, -1);
}
}
private long createSessionAndMakeItActive(final long tenantId, final SessionAccessor sessionAccessor, final SessionService sessionService)
throws SBonitaException {
final long sessionId = createSession(tenantId, sessionService);
sessionAccessor.setSessionInfo(sessionId, tenantId);
return sessionId;
}
@Override
@CustomTransactions
@AvailableOnStoppedNode
public boolean isPlatformCreated() throws PlatformNotFoundException {
PlatformServiceAccessor platformAccessor;
try {
platformAccessor = getPlatformAccessor();
} catch (final Exception e) {
throw new PlatformNotFoundException(e);
}
final PlatformService platformService = platformAccessor.getPlatformService();
final TransactionExecutor transactionExecutor = platformAccessor.getTransactionExecutor();
final TransactionContentWithResult<Boolean> transactionContent = new IsPlatformCreated(platformService);
try {
transactionExecutor.execute(transactionContent);
return transactionContent.getResult();
} catch (final SBonitaException e) {
return false;
}
}
@Override
@CustomTransactions
@AvailableOnStoppedNode
public PlatformState getPlatformState() throws PlatformNotFoundException {
if (isNodeStarted()) {
return PlatformState.STARTED;
}
return PlatformState.STOPPED;
}
private STenant getDefaultTenant() throws STenantNotFoundException {
PlatformServiceAccessor platformAccessor = null;
try {
platformAccessor = getPlatformAccessor();
final PlatformService platformService = platformAccessor.getPlatformService();
return platformService.getDefaultTenant();
} catch (final SBonitaException e) {
log(platformAccessor, e);
throw new STenantNotFoundException("Unable to retrieve the defaultTenant", e);
} catch (final Exception e) {
log(platformAccessor, e);
throw new STenantNotFoundException("Unable to retrieve the defaultTenant", e);
}
}
/**
* @return true if the current node is started, false otherwise
*/
@Override
@AvailableOnStoppedNode
public boolean isNodeStarted() {
return isNodeStarted;
}
}
| true | true | public void startNode() throws StartNodeException {
final PlatformServiceAccessor platformAccessor;
SessionAccessor sessionAccessor = null;
try {
platformAccessor = getPlatformAccessor();
sessionAccessor = ServiceAccessorFactory.getInstance().createSessionAccessor();
} catch (final Exception e) {
throw new StartNodeException(e);
}
final NodeConfiguration platformConfiguration = platformAccessor.getPlaformConfiguration();
final SchedulerService schedulerService = platformAccessor.getSchedulerService();
WorkService workService = platformAccessor.getWorkService();
try {
try {
final TransactionExecutor executor = platformAccessor.getTransactionExecutor();
final RefreshPlatformClassLoader refreshPlatformClassLoader = new RefreshPlatformClassLoader(platformAccessor);
executor.execute(refreshPlatformClassLoader);
final List<Long> tenantIds = refreshPlatformClassLoader.getResult();
// set tenant classloader
final SessionService sessionService = platformAccessor.getSessionService();
for (final Long tenantId : tenantIds) {
long sessionId = -1;
long platformSessionId = -1;
try {
platformSessionId = sessionAccessor.getSessionId();
sessionAccessor.deleteSessionId();
sessionId = createSessionAndMakeItActive(tenantId, sessionAccessor, sessionService);
final TenantServiceAccessor tenantServiceAccessor = platformAccessor.getTenantServiceAccessor(tenantId);
final TransactionExecutor tenantExecutor = tenantServiceAccessor.getTransactionExecutor();
tenantExecutor.execute(new RefreshTenantClassLoaders(tenantServiceAccessor, tenantId));
} finally {
sessionService.deleteSession(sessionId);
cleanSessionAccessor(sessionAccessor);
sessionAccessor.setSessionInfo(platformSessionId, -1);
}
}
// FIXME: shouldn't we also stop the workService?:
workService.startup();
if (!isNodeStarted()) {
if (platformConfiguration.shouldStartScheduler()) {
schedulerService.start();
}
if (platformConfiguration.shouldResumeElements()) {
// Here get all elements that are not "finished"
// * FlowNodes that have flag: stateExecuting to true: call execute on them (connectors were executing)
// * Process instances with token count == 0 (either not started again or finishing) -> same thing connectors were executing
// * transitions that are in state created: call execute on them
// * flow node that are completed and not deleted : call execute to make it create transitions and so on
// * all element that are in not stable state
final PlatformService platformService = platformAccessor.getPlatformService();
final GetDefaultTenantInstance getDefaultTenantInstance = new GetDefaultTenantInstance(platformService);
platformAccessor.getTransactionExecutor().execute(getDefaultTenantInstance);
final STenant defaultTenant = getDefaultTenantInstance.getResult();
final long tenantId = defaultTenant.getId();
final TenantServiceAccessor tenantServiceAccessor = getTenantServiceAccessor(tenantId);
final long sessionId = createSessionAndMakeItActive(defaultTenant.getId(), sessionAccessor, sessionService);
for (final TenantRestartHandler restartHandler : platformConfiguration.getTenantRestartHandlers()) {
Callable<Void> callable = new Callable<Void>() {
@Override
public Void call() throws Exception {
restartHandler.handleRestart(platformAccessor, tenantServiceAccessor);
return null;
}
};
tenantServiceAccessor.getTransactionService().executeInTransaction(callable);
}
sessionService.deleteSession(sessionId);
}
for (final RestartHandler restartHandler : platformConfiguration.getRestartHandlers()) {
restartHandler.execute();
}
}
} catch (final ClassLoaderException e) {
throw new StartNodeException("Platform starting failed while initializing platform classloaders.", e);
} catch (final SDependencyException e) {
throw new StartNodeException("Platform starting failed while initializing platform classloaders.", e);
} catch (final SBonitaException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final BonitaHomeNotSetException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final BonitaHomeConfigurationException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final IOException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final NoSuchMethodException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final InstantiationException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final IllegalAccessException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final InvocationTargetException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final Exception e) {
throw new StartNodeException("Platform starting failed.", e);
} finally {
cleanSessionAccessor(sessionAccessor);
}
isNodeStarted = true;
} catch (final StartNodeException e) {
// If an exception is thrown, stop the platform that was started.
try {
shutdownScheduler(platformAccessor, schedulerService);
} catch (final SBonitaException exp) {
throw new StartNodeException("Platform stoping failed : " + exp.getMessage(), e);
}
throw e;
}
}
| public void startNode() throws StartNodeException {
final PlatformServiceAccessor platformAccessor;
SessionAccessor sessionAccessor = null;
try {
platformAccessor = getPlatformAccessor();
sessionAccessor = ServiceAccessorFactory.getInstance().createSessionAccessor();
} catch (final Exception e) {
throw new StartNodeException(e);
}
final NodeConfiguration platformConfiguration = platformAccessor.getPlaformConfiguration();
final SchedulerService schedulerService = platformAccessor.getSchedulerService();
WorkService workService = platformAccessor.getWorkService();
try {
try {
final TransactionExecutor executor = platformAccessor.getTransactionExecutor();
final RefreshPlatformClassLoader refreshPlatformClassLoader = new RefreshPlatformClassLoader(platformAccessor);
executor.execute(refreshPlatformClassLoader);
final List<Long> tenantIds = refreshPlatformClassLoader.getResult();
// set tenant classloader
final SessionService sessionService = platformAccessor.getSessionService();
for (final Long tenantId : tenantIds) {
long sessionId = -1;
long platformSessionId = -1;
try {
platformSessionId = sessionAccessor.getSessionId();
sessionAccessor.deleteSessionId();
sessionId = createSessionAndMakeItActive(tenantId, sessionAccessor, sessionService);
final TenantServiceAccessor tenantServiceAccessor = platformAccessor.getTenantServiceAccessor(tenantId);
final TransactionExecutor tenantExecutor = tenantServiceAccessor.getTransactionExecutor();
tenantExecutor.execute(new RefreshTenantClassLoaders(tenantServiceAccessor, tenantId));
} finally {
sessionService.deleteSession(sessionId);
cleanSessionAccessor(sessionAccessor);
sessionAccessor.setSessionInfo(platformSessionId, -1);
}
}
// FIXME: shouldn't we also stop the workService?:
workService.startup();
if (!isNodeStarted()) {
if (platformConfiguration.shouldStartScheduler() && !schedulerService.isStarted()) {
schedulerService.start();
}
if (platformConfiguration.shouldResumeElements()) {
// Here get all elements that are not "finished"
// * FlowNodes that have flag: stateExecuting to true: call execute on them (connectors were executing)
// * Process instances with token count == 0 (either not started again or finishing) -> same thing connectors were executing
// * transitions that are in state created: call execute on them
// * flow node that are completed and not deleted : call execute to make it create transitions and so on
// * all element that are in not stable state
final PlatformService platformService = platformAccessor.getPlatformService();
final GetDefaultTenantInstance getDefaultTenantInstance = new GetDefaultTenantInstance(platformService);
platformAccessor.getTransactionExecutor().execute(getDefaultTenantInstance);
final STenant defaultTenant = getDefaultTenantInstance.getResult();
final long tenantId = defaultTenant.getId();
final TenantServiceAccessor tenantServiceAccessor = getTenantServiceAccessor(tenantId);
final long sessionId = createSessionAndMakeItActive(defaultTenant.getId(), sessionAccessor, sessionService);
for (final TenantRestartHandler restartHandler : platformConfiguration.getTenantRestartHandlers()) {
Callable<Void> callable = new Callable<Void>() {
@Override
public Void call() throws Exception {
restartHandler.handleRestart(platformAccessor, tenantServiceAccessor);
return null;
}
};
tenantServiceAccessor.getTransactionService().executeInTransaction(callable);
}
sessionService.deleteSession(sessionId);
}
for (final RestartHandler restartHandler : platformConfiguration.getRestartHandlers()) {
restartHandler.execute();
}
}
} catch (final ClassLoaderException e) {
throw new StartNodeException("Platform starting failed while initializing platform classloaders.", e);
} catch (final SDependencyException e) {
throw new StartNodeException("Platform starting failed while initializing platform classloaders.", e);
} catch (final SBonitaException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final BonitaHomeNotSetException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final BonitaHomeConfigurationException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final IOException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final NoSuchMethodException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final InstantiationException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final IllegalAccessException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final InvocationTargetException e) {
throw new StartNodeException("Platform starting failed.", e);
} catch (final Exception e) {
throw new StartNodeException("Platform starting failed.", e);
} finally {
cleanSessionAccessor(sessionAccessor);
}
isNodeStarted = true;
} catch (final StartNodeException e) {
// If an exception is thrown, stop the platform that was started.
try {
shutdownScheduler(platformAccessor, schedulerService);
} catch (final SBonitaException exp) {
throw new StartNodeException("Platform stoping failed : " + exp.getMessage(), e);
}
throw e;
}
}
|
diff --git a/org.springsource.ide.eclipse.commons.frameworks.core/src/org/springsource/ide/eclipse/commons/frameworks/core/legacyconversion/LegacyProjectConverter.java b/org.springsource.ide.eclipse.commons.frameworks.core/src/org/springsource/ide/eclipse/commons/frameworks/core/legacyconversion/LegacyProjectConverter.java
index 630a3fd0..9f0e4f26 100644
--- a/org.springsource.ide.eclipse.commons.frameworks.core/src/org/springsource/ide/eclipse/commons/frameworks/core/legacyconversion/LegacyProjectConverter.java
+++ b/org.springsource.ide.eclipse.commons.frameworks.core/src/org/springsource/ide/eclipse/commons/frameworks/core/legacyconversion/LegacyProjectConverter.java
@@ -1,188 +1,188 @@
/*******************************************************************************
* Copyright (c) 2012 VMware, Inc.
* 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:
* VMware, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.commons.frameworks.core.legacyconversion;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import org.eclipse.core.internal.runtime.InternalPlatform;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.preferences.InstanceScope;
import org.eclipse.jdt.core.IClasspathAttribute;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.springsource.ide.eclipse.commons.frameworks.core.FrameworkCoreActivator;
/**
* Converts legacy maven projects to the new m2e
* @author Andrew Eisenberg
* @since 3.0.0
*/
public class LegacyProjectConverter extends AbstractLegacyConverter implements IConversionConstants {
private final List<IProject> allLegacyProjects;
private IProject[] selectedLegacyProjects;
/**
* Converts a single project
*/
public LegacyProjectConverter(IProject legacyProject) {
allLegacyProjects = Collections.singletonList(legacyProject);
selectedLegacyProjects = new IProject[] { legacyProject };
}
public LegacyProjectConverter(List<IProject> legacyProjects) {
this.allLegacyProjects = legacyProjects;
}
public List<IProject> getAllLegacyProjects() {
return allLegacyProjects;
}
public IProject[] getSelectedLegacyProjects() {
return selectedLegacyProjects;
}
public void setSelectedLegacyProjects(IProject[] selectedLegacyProjects) {
this.selectedLegacyProjects = selectedLegacyProjects;
}
public IStatus convert(IProgressMonitor monitor) {
if (monitor == null) {
monitor = new NullProgressMonitor();
}
SubMonitor sub = SubMonitor.convert(monitor, selectedLegacyProjects.length);
IStatus[] statuses = new IStatus[selectedLegacyProjects.length];
int i = 0;
for (IProject project : selectedLegacyProjects) {
if (project.isAccessible()) {
sub.subTask("Converting " + project.getName()); //$NON-NLS-1$
if (sub.isCanceled()) {
throw new OperationCanceledException();
}
statuses[i++] = convert(project, monitor);
} else {
// project was closed before job started.
statuses[i++] = Status.OK_STATUS;
}
sub.worked(1);
}
return new MultiStatus(FrameworkCoreActivator.PLUGIN_ID, 0, statuses, "Result of converting legacy maven projects", null); //$NON-NLS-1$
}
private IStatus convert(IProject project, IProgressMonitor monitor) {
SubMonitor sub = SubMonitor.convert(monitor, 1);
// grab project rule
Job.getJobManager().beginRule(ResourcesPlugin.getWorkspace().getRoot(), sub);
try {
if (project.hasNature(GRAILS_OLD_NATURE)) {
convertGrailsProject(project, sub);
} else if (project.hasNature(ROO_OLD_NATURE)) {
convertRooProject(project, sub);
}
} catch (Exception e) {
return new Status(IStatus.ERROR, FrameworkCoreActivator.PLUGIN_ID, "Failed to convert " + project.getName(), e); //$NON-NLS-1$
} finally {
// release rule
Job.getJobManager().endRule(ResourcesPlugin.getWorkspace().getRoot());
}
sub.worked(1);
return new Status(IStatus.OK, FrameworkCoreActivator.PLUGIN_ID, "Converted " + project.getName()); //$NON-NLS-1$
}
private void convertGrailsProject(IProject project, SubMonitor sub) throws Exception {
// nature
IProjectDescription description = project.getDescription();
String[] ids = description.getNatureIds();
List<String> newIds = new ArrayList<String>(ids.length);
for (int i = 0; i < ids.length; i++) {
if (!ids[i].equals(GRAILS_OLD_NATURE) && !ids[i].equals(GRAILS_NEW_NATURE)) {
newIds.add(ids[i]);
} else {
newIds.add(GRAILS_NEW_NATURE);
}
}
description.setNatureIds(newIds.toArray(new String[0]));
project.setDescription(description, sub);
// project preferences
IFolder preferencesFolder = project.getFolder(".settings/"); //$NON-NLS-1$
File settingsFile = preferencesFolder.getFile(GRAILS_OLD_PLUGIN_NAME + ".prefs").getLocation().toFile(); //$NON-NLS-1$ //$NON-NLS-2$
- File newSettingsFile = preferencesFolder.getFile(GRAILS_OLD_PLUGIN_NAME + ".prefs").getLocation().toFile(); //$NON-NLS-1$ //$NON-NLS-2$
+ File newSettingsFile = preferencesFolder.getFile(GRAILS_NEW_PLUGIN_NAME + ".prefs").getLocation().toFile(); //$NON-NLS-1$ //$NON-NLS-2$
copyPreferencesFile(settingsFile, newSettingsFile, GRAILS_OLD_PREFERENCE_PREFIX, GRAILS_NEW_PREFERENCE_PREFIX);
InstanceScope.INSTANCE.getNode(GRAILS_OLD_PLUGIN_NAME).sync();
preferencesFolder.refreshLocal(IResource.DEPTH_ONE, sub);
// classpath container
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] classpath = javaProject.getRawClasspath();
List<IClasspathEntry> newClasspath = new ArrayList<IClasspathEntry>();
for (int i = 0; i < classpath.length; i++) {
if (classpath[i].getPath().toString().equals(GRAILS_OLD_CONTAINER)) {
newClasspath.add(JavaCore.newContainerEntry(new Path(GRAILS_NEW_CONTAINER), classpath[i].getAccessRules(), convertGrailsClasspathAttributes(classpath[i]), classpath[i].isExported()));
} else if (classpath[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
newClasspath.add(JavaCore.newSourceEntry(classpath[i].getPath(), classpath[i].getInclusionPatterns(),
classpath[i].getExclusionPatterns(), classpath[i].getOutputLocation(), convertGrailsClasspathAttributes(classpath[i])));
} else {
newClasspath.add(classpath[i]);
}
}
javaProject.setRawClasspath(newClasspath.toArray(new IClasspathEntry[0]), sub);
}
private IClasspathAttribute[] convertGrailsClasspathAttributes(
IClasspathEntry entry) {
IClasspathAttribute[] oldAttributes = entry.getExtraAttributes();
if (oldAttributes == null || oldAttributes.length == 0) {
return new IClasspathAttribute[0];
}
IClasspathAttribute[] newAttributes = new IClasspathAttribute[oldAttributes.length];
for (int i = 0; i < oldAttributes.length; i++) {
if (oldAttributes[i].getName().equals(GRAILS_OLD_ATTRIBUTE)) {
newAttributes[i] = JavaCore.newClasspathAttribute(GRAILS_NEW_ATTRIBUTE, oldAttributes[i].getValue());
} else {
newAttributes[i] = oldAttributes[i];
}
}
return newAttributes;
}
// TODO FIXLDS Convert roo project
private void convertRooProject(IProject project, SubMonitor sub) {
}
}
| true | true | private void convertGrailsProject(IProject project, SubMonitor sub) throws Exception {
// nature
IProjectDescription description = project.getDescription();
String[] ids = description.getNatureIds();
List<String> newIds = new ArrayList<String>(ids.length);
for (int i = 0; i < ids.length; i++) {
if (!ids[i].equals(GRAILS_OLD_NATURE) && !ids[i].equals(GRAILS_NEW_NATURE)) {
newIds.add(ids[i]);
} else {
newIds.add(GRAILS_NEW_NATURE);
}
}
description.setNatureIds(newIds.toArray(new String[0]));
project.setDescription(description, sub);
// project preferences
IFolder preferencesFolder = project.getFolder(".settings/"); //$NON-NLS-1$
File settingsFile = preferencesFolder.getFile(GRAILS_OLD_PLUGIN_NAME + ".prefs").getLocation().toFile(); //$NON-NLS-1$ //$NON-NLS-2$
File newSettingsFile = preferencesFolder.getFile(GRAILS_OLD_PLUGIN_NAME + ".prefs").getLocation().toFile(); //$NON-NLS-1$ //$NON-NLS-2$
copyPreferencesFile(settingsFile, newSettingsFile, GRAILS_OLD_PREFERENCE_PREFIX, GRAILS_NEW_PREFERENCE_PREFIX);
InstanceScope.INSTANCE.getNode(GRAILS_OLD_PLUGIN_NAME).sync();
preferencesFolder.refreshLocal(IResource.DEPTH_ONE, sub);
// classpath container
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] classpath = javaProject.getRawClasspath();
List<IClasspathEntry> newClasspath = new ArrayList<IClasspathEntry>();
for (int i = 0; i < classpath.length; i++) {
if (classpath[i].getPath().toString().equals(GRAILS_OLD_CONTAINER)) {
newClasspath.add(JavaCore.newContainerEntry(new Path(GRAILS_NEW_CONTAINER), classpath[i].getAccessRules(), convertGrailsClasspathAttributes(classpath[i]), classpath[i].isExported()));
} else if (classpath[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
newClasspath.add(JavaCore.newSourceEntry(classpath[i].getPath(), classpath[i].getInclusionPatterns(),
classpath[i].getExclusionPatterns(), classpath[i].getOutputLocation(), convertGrailsClasspathAttributes(classpath[i])));
} else {
newClasspath.add(classpath[i]);
}
}
javaProject.setRawClasspath(newClasspath.toArray(new IClasspathEntry[0]), sub);
}
| private void convertGrailsProject(IProject project, SubMonitor sub) throws Exception {
// nature
IProjectDescription description = project.getDescription();
String[] ids = description.getNatureIds();
List<String> newIds = new ArrayList<String>(ids.length);
for (int i = 0; i < ids.length; i++) {
if (!ids[i].equals(GRAILS_OLD_NATURE) && !ids[i].equals(GRAILS_NEW_NATURE)) {
newIds.add(ids[i]);
} else {
newIds.add(GRAILS_NEW_NATURE);
}
}
description.setNatureIds(newIds.toArray(new String[0]));
project.setDescription(description, sub);
// project preferences
IFolder preferencesFolder = project.getFolder(".settings/"); //$NON-NLS-1$
File settingsFile = preferencesFolder.getFile(GRAILS_OLD_PLUGIN_NAME + ".prefs").getLocation().toFile(); //$NON-NLS-1$ //$NON-NLS-2$
File newSettingsFile = preferencesFolder.getFile(GRAILS_NEW_PLUGIN_NAME + ".prefs").getLocation().toFile(); //$NON-NLS-1$ //$NON-NLS-2$
copyPreferencesFile(settingsFile, newSettingsFile, GRAILS_OLD_PREFERENCE_PREFIX, GRAILS_NEW_PREFERENCE_PREFIX);
InstanceScope.INSTANCE.getNode(GRAILS_OLD_PLUGIN_NAME).sync();
preferencesFolder.refreshLocal(IResource.DEPTH_ONE, sub);
// classpath container
IJavaProject javaProject = JavaCore.create(project);
IClasspathEntry[] classpath = javaProject.getRawClasspath();
List<IClasspathEntry> newClasspath = new ArrayList<IClasspathEntry>();
for (int i = 0; i < classpath.length; i++) {
if (classpath[i].getPath().toString().equals(GRAILS_OLD_CONTAINER)) {
newClasspath.add(JavaCore.newContainerEntry(new Path(GRAILS_NEW_CONTAINER), classpath[i].getAccessRules(), convertGrailsClasspathAttributes(classpath[i]), classpath[i].isExported()));
} else if (classpath[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
newClasspath.add(JavaCore.newSourceEntry(classpath[i].getPath(), classpath[i].getInclusionPatterns(),
classpath[i].getExclusionPatterns(), classpath[i].getOutputLocation(), convertGrailsClasspathAttributes(classpath[i])));
} else {
newClasspath.add(classpath[i]);
}
}
javaProject.setRawClasspath(newClasspath.toArray(new IClasspathEntry[0]), sub);
}
|
diff --git a/src/ee/ut/math/tvt/salessystem/ui/popups/PurchaseConfirmPopup.java b/src/ee/ut/math/tvt/salessystem/ui/popups/PurchaseConfirmPopup.java
index 2e06d80..d8ac72e 100644
--- a/src/ee/ut/math/tvt/salessystem/ui/popups/PurchaseConfirmPopup.java
+++ b/src/ee/ut/math/tvt/salessystem/ui/popups/PurchaseConfirmPopup.java
@@ -1,113 +1,115 @@
package ee.ut.math.tvt.salessystem.ui.popups;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import ee.ut.math.tvt.salessystem.ui.model.SalesSystemModel;
import ee.ut.math.tvt.salessystem.ui.tabs.PurchaseTab;
public class PurchaseConfirmPopup extends JFrame {
private static final long serialVersionUID = 1L; // class version
private DefaultPopup frame;
private Map<String, JTextField> elements = new HashMap<String, JTextField>();
private SalesSystemModel model;
private String totalField = "Total:";
private String paymentField = "Payment:";
private String changeField = "Change:";
// builds add product panel
public PurchaseConfirmPopup(final double total, SalesSystemModel mod,
final PurchaseTab parent) {
String title = "Add product";
this.model = mod;
// Fill the change field if the payment field loses focus
final JTextField payment = new JTextField();
final JTextField change = new JTextField();
payment.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
try {
- change.setText(String.valueOf(Double.valueOf(payment
- .getText()) - total));
+ change.setText(String.format("%.2g%n",
+ Double.valueOf(payment.getText()) - total));
} catch (NumberFormatException ex) {
- JOptionPane
- .showMessageDialog(PurchaseConfirmPopup.this,
- "Payment must be a number!",
- "Purchase not completed",
- JOptionPane.PLAIN_MESSAGE);
+ if (!payment.getText().equals("")) {
+ JOptionPane.showMessageDialog(
+ PurchaseConfirmPopup.this,
+ "Payment must be a number!",
+ "Purchase not completed",
+ JOptionPane.PLAIN_MESSAGE);
+ }
}
}
});
// Make the elements
elements = new HashMap<String, JTextField>();
elements.put(totalField, new JTextField(String.valueOf(total)));
elements.put(paymentField, payment);
elements.put(changeField, change);
// Make the window
frame = new DefaultPopup(title, 400, 280, 1);
// Make the panel
JPanel panel = frame.makePanel(title, elements, false);
// Add ok button
JButton okButton = new JButton("Confirm purchase");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (Double.valueOf(payment.getText()) < total) {
JOptionPane.showMessageDialog(
PurchaseConfirmPopup.this,
"Payment is not large enough!",
"Purchase not completed",
JOptionPane.PLAIN_MESSAGE);
} else {
parent.submitPurchaseButtonClicked();
frame.dispose();
}
} catch (NumberFormatException ex) {
JOptionPane
.showMessageDialog(PurchaseConfirmPopup.this,
"Payment must be a number!",
"Purchase not completed",
JOptionPane.PLAIN_MESSAGE);
}
}
});
panel.add(okButton);
// Add cancel button
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
panel.add(cancelButton);
// Fill window
frame.add(panel);
frame.repaint();
frame.setVisible(true);
}
}
| false | true | public PurchaseConfirmPopup(final double total, SalesSystemModel mod,
final PurchaseTab parent) {
String title = "Add product";
this.model = mod;
// Fill the change field if the payment field loses focus
final JTextField payment = new JTextField();
final JTextField change = new JTextField();
payment.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
try {
change.setText(String.valueOf(Double.valueOf(payment
.getText()) - total));
} catch (NumberFormatException ex) {
JOptionPane
.showMessageDialog(PurchaseConfirmPopup.this,
"Payment must be a number!",
"Purchase not completed",
JOptionPane.PLAIN_MESSAGE);
}
}
});
// Make the elements
elements = new HashMap<String, JTextField>();
elements.put(totalField, new JTextField(String.valueOf(total)));
elements.put(paymentField, payment);
elements.put(changeField, change);
// Make the window
frame = new DefaultPopup(title, 400, 280, 1);
// Make the panel
JPanel panel = frame.makePanel(title, elements, false);
// Add ok button
JButton okButton = new JButton("Confirm purchase");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (Double.valueOf(payment.getText()) < total) {
JOptionPane.showMessageDialog(
PurchaseConfirmPopup.this,
"Payment is not large enough!",
"Purchase not completed",
JOptionPane.PLAIN_MESSAGE);
} else {
parent.submitPurchaseButtonClicked();
frame.dispose();
}
} catch (NumberFormatException ex) {
JOptionPane
.showMessageDialog(PurchaseConfirmPopup.this,
"Payment must be a number!",
"Purchase not completed",
JOptionPane.PLAIN_MESSAGE);
}
}
});
panel.add(okButton);
// Add cancel button
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
panel.add(cancelButton);
// Fill window
frame.add(panel);
frame.repaint();
frame.setVisible(true);
}
| public PurchaseConfirmPopup(final double total, SalesSystemModel mod,
final PurchaseTab parent) {
String title = "Add product";
this.model = mod;
// Fill the change field if the payment field loses focus
final JTextField payment = new JTextField();
final JTextField change = new JTextField();
payment.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
try {
change.setText(String.format("%.2g%n",
Double.valueOf(payment.getText()) - total));
} catch (NumberFormatException ex) {
if (!payment.getText().equals("")) {
JOptionPane.showMessageDialog(
PurchaseConfirmPopup.this,
"Payment must be a number!",
"Purchase not completed",
JOptionPane.PLAIN_MESSAGE);
}
}
}
});
// Make the elements
elements = new HashMap<String, JTextField>();
elements.put(totalField, new JTextField(String.valueOf(total)));
elements.put(paymentField, payment);
elements.put(changeField, change);
// Make the window
frame = new DefaultPopup(title, 400, 280, 1);
// Make the panel
JPanel panel = frame.makePanel(title, elements, false);
// Add ok button
JButton okButton = new JButton("Confirm purchase");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (Double.valueOf(payment.getText()) < total) {
JOptionPane.showMessageDialog(
PurchaseConfirmPopup.this,
"Payment is not large enough!",
"Purchase not completed",
JOptionPane.PLAIN_MESSAGE);
} else {
parent.submitPurchaseButtonClicked();
frame.dispose();
}
} catch (NumberFormatException ex) {
JOptionPane
.showMessageDialog(PurchaseConfirmPopup.this,
"Payment must be a number!",
"Purchase not completed",
JOptionPane.PLAIN_MESSAGE);
}
}
});
panel.add(okButton);
// Add cancel button
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
panel.add(cancelButton);
// Fill window
frame.add(panel);
frame.repaint();
frame.setVisible(true);
}
|
diff --git a/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/AdvertisementOperations.java b/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/AdvertisementOperations.java
index 22b67a5c..3e6702a6 100644
--- a/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/AdvertisementOperations.java
+++ b/cejug-classifieds-server/src/net/java/dev/cejug/classifieds/service/endpoint/impl/AdvertisementOperations.java
@@ -1,261 +1,262 @@
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Copyright (C) 2008 CEJUG - Ceará Java Users Group
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
This file is part of the CEJUG-CLASSIFIEDS Project - an open source classifieds system
originally used by CEJUG - Ceará Java Users Group.
The project is hosted https://cejug-classifieds.dev.java.net/
You can contact us through the mail [email protected]
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
package net.java.dev.cejug.classifieds.service.endpoint.impl;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.xml.ws.WebServiceException;
import net.java.dev.cejug.classifieds.adapter.SoapOrmAdapter;
import net.java.dev.cejug.classifieds.business.interfaces.AdvertisementAdapterLocal;
import net.java.dev.cejug.classifieds.business.interfaces.AdvertisementOperationsLocal;
import net.java.dev.cejug.classifieds.entity.AdvertisementEntity;
import net.java.dev.cejug.classifieds.entity.facade.AdvertisementFacadeLocal;
import net.java.dev.cejug.classifieds.entity.facade.EntityFacade;
import net.java.dev.cejug.classifieds.exception.RepositoryAccessException;
import net.java.dev.cejug_classifieds.metadata.attachments.AtavarImage;
import net.java.dev.cejug_classifieds.metadata.attachments.AvatarImageOrUrl;
import net.java.dev.cejug_classifieds.metadata.business.Advertisement;
import net.java.dev.cejug_classifieds.metadata.business.AdvertisementCollection;
import net.java.dev.cejug_classifieds.metadata.business.AdvertisementCollectionFilter;
import net.java.dev.cejug_classifieds.metadata.business.PublishingHeader;
import net.java.dev.cejug_classifieds.metadata.common.Customer;
/**
* TODO: to comment.
*
* @author $Author$
* @version $Rev$ ($Date$)
*/
@Stateless
public class AdvertisementOperations extends
AbstractCrudImpl<AdvertisementEntity, Advertisement> implements
AdvertisementOperationsLocal {
/**
* Persistence façade of Advertisement entities.
*/
@EJB
private transient AdvertisementFacadeLocal advFacade;
@EJB
private transient AdvertisementAdapterLocal advAdapter;
/**
* the global log manager, used to allow third party services to override
* the default logger.
*/
private static final Logger logger = Logger.getLogger(
AdvertisementOperations.class.getName(), "i18n/log");
@Override
protected SoapOrmAdapter<Advertisement, AdvertisementEntity> getAdapter() {
return advAdapter;
}
@Override
protected EntityFacade<AdvertisementEntity> getFacade() {
return advFacade;
}
public AdvertisementCollection loadAdvertisementOperation(
final AdvertisementCollectionFilter filter) {
// TODO: load advertisements from timetable.... filtering with periods,
// etc..
try {
AdvertisementCollection collection = new AdvertisementCollection();
List<AdvertisementEntity> entities = advFacade.readByCategory(Long
.parseLong(filter.getCategory()));
for (AdvertisementEntity entity : entities) {
collection.getAdvertisement().add(advAdapter.toSoap(entity));
}
return collection;
} catch (Exception e) {
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
public Advertisement publishOperation(final Advertisement advertisement,
final PublishingHeader header) {
// TODO: to implement the real code.
try {
// TODO: re-think a factory to reuse adapters...
Customer customer = new Customer();
customer.setLogin(header.getCustomerLogin());
customer.setDomainId(header.getCustomerDomainId());
advertisement.setCustomer(customer);
AvatarImageOrUrl avatar = advertisement.getAvatarImageOrUrl();
AtavarImage img = null;
/*
* if (avatar.getGravatarEmail() != null) { avatar
* .setUrl("http://www.gravatar.com/avatar/" +
* hashGravatarEmail(avatar.getGravatarEmail()) + ".jpg"); } else if
* (avatar.getUrl() != null) { img = avatar.getImage(); AtavarImage
* temp = new AtavarImage();
* temp.setContentType(img.getContentType()); temp.setValue(null);
* avatar.setImage(temp); }
*/
String[] fakeAvatar = { "767fc9c115a1b989744c755db47feb60",
"5915fd742d0c26f6a584f9d21f991b9c",
"f4510afa5a1ceb6ae7c058c25051aed9",
"84987b436214f52ec0b04cd1f8a73c3c",
"bb29d699b5cba218c313b61aa82249da",
"b0b357b291ac72bc7da81b4d74430fe6",
"d212b7b6c54f0ccb2c848d23440b33ba",
"1a33e7a69df4f675fcd799edca088ac2",
"992df4737c71df3189eed335a98fa0c0",
"a558f2098da8edf67d9a673739d18aff",
"8379aabc84ecee06f48d8ca48e09eef4",
"4d346581a3340e32cf93703c9ce46bd4",
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
+ hashGravatarEmail("[email protected]"),
"eed0e8d62f562daf038f182de7f1fd42",
"7acb05d25c22cbc0942a5e3de59392bb",
"df126b735a54ed95b4f4cc346b786843",
"aac7e0386facd070f6d4b817c257a958",
"c19b763b0577beb2e0032812e18e567d",
"06005cd2700c136d09e71838645d36ff" };
avatar
.setUrl("http://www.gravatar.com/avatar/"
// +
// hashGravatarEmail((Math.random()>.5?"[email protected]":"[email protected]"))
+ fakeAvatar[(int) (Math.random()
* fakeAvatar.length - 0.0000000000001d)]
+ ".jpg");
/*
* Copy resources to the content repository - the file system. try {
* copyResourcesToRepository(advertisement); } catch (Exception e) {
* e.printStackTrace(); }
*/
AdvertisementEntity entity = advAdapter.toEntity(advertisement);
advFacade.create(entity);
/*
if (img != null) {
String reference = copyResourcesToRepository(avatar.getName(),
img.getValue(), entity.getId(), header
.getCustomerDomainId());
entity.getAvatar().setReference(reference);
advFacade.update(entity);
}*/
logger.finest("Advertisement #" + entity.getId() + " published ("
+ entity.getTitle() + ")");
return advAdapter.toSoap(entity);
} catch (NoSuchAlgorithmException e) {
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
/**
* A customer can submit a resource URL or a resource content, more common
* in case of images (PNG/JPG). In this case, the server first store the
* image contents in the file system and refer its location in the database.
* This method receives an Avatar object, check it size and store it
* contents in the file system.
*
* @param l
* @param advertisement
* the advertisement containing attachments.
* @return the resource address.
* @throws RepositoryAccessException
* problems accessing the content repository.
*/
private String copyResourcesToRepository(String name, byte[] contents,
long customerId, long domainId) throws RepositoryAccessException {
if (contents == null || contents.length < 1) {
return null;
} else if (customerId < 1 || domainId < 1) {
throw new RepositoryAccessException("Unaccepted ID (customer id:"
+ customerId + ", domain: " + domainId);
} else {
String glassfishHome = System.getenv("AS_HOME");
String path = glassfishHome
+ "/domains/domain1/applications/j2ee-apps/cejug-classifieds-server/cejug-classifieds-server_war/resource/"
+ domainId + '/' + customerId;
String file = path + "/" + name;
File pathF = new File(path);
File fileF = new File(file);
try {
if (pathF.mkdirs() && fileF.createNewFile()) {
FileOutputStream out;
out = new FileOutputStream(file);
out.write(contents);
out.close();
String resourcePath = "http://fgaucho.dyndns.org:8080/cejug-classifieds-server/resource/"
+ domainId + "/" + customerId + "/" + name;
logger.info("resource created: " + resourcePath);
return resourcePath;
} else {
throw new RepositoryAccessException(
"error trying tocreate the resource path '" + file
+ "'");
}
} catch (IOException e) {
logger.severe(e.getMessage());
throw new RepositoryAccessException(e);
}
}
}
private static final char[] HEXADECIMAL = { '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
private static String hashGravatarEmail(String email)
throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
byte[] bytes = md.digest(email.getBytes());
StringBuilder sb = new StringBuilder(2 * bytes.length);
for (int i = 0; i < bytes.length; i++) {
int low = (int) (bytes[i] & 0x0f);
int high = (int) ((bytes[i] & 0xf0) >> 4);
sb.append(HEXADECIMAL[high]);
sb.append(HEXADECIMAL[low]);
}
return sb.toString();
}
}
| true | true | public Advertisement publishOperation(final Advertisement advertisement,
final PublishingHeader header) {
// TODO: to implement the real code.
try {
// TODO: re-think a factory to reuse adapters...
Customer customer = new Customer();
customer.setLogin(header.getCustomerLogin());
customer.setDomainId(header.getCustomerDomainId());
advertisement.setCustomer(customer);
AvatarImageOrUrl avatar = advertisement.getAvatarImageOrUrl();
AtavarImage img = null;
/*
* if (avatar.getGravatarEmail() != null) { avatar
* .setUrl("http://www.gravatar.com/avatar/" +
* hashGravatarEmail(avatar.getGravatarEmail()) + ".jpg"); } else if
* (avatar.getUrl() != null) { img = avatar.getImage(); AtavarImage
* temp = new AtavarImage();
* temp.setContentType(img.getContentType()); temp.setValue(null);
* avatar.setImage(temp); }
*/
String[] fakeAvatar = { "767fc9c115a1b989744c755db47feb60",
"5915fd742d0c26f6a584f9d21f991b9c",
"f4510afa5a1ceb6ae7c058c25051aed9",
"84987b436214f52ec0b04cd1f8a73c3c",
"bb29d699b5cba218c313b61aa82249da",
"b0b357b291ac72bc7da81b4d74430fe6",
"d212b7b6c54f0ccb2c848d23440b33ba",
"1a33e7a69df4f675fcd799edca088ac2",
"992df4737c71df3189eed335a98fa0c0",
"a558f2098da8edf67d9a673739d18aff",
"8379aabc84ecee06f48d8ca48e09eef4",
"4d346581a3340e32cf93703c9ce46bd4",
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
"eed0e8d62f562daf038f182de7f1fd42",
"7acb05d25c22cbc0942a5e3de59392bb",
"df126b735a54ed95b4f4cc346b786843",
"aac7e0386facd070f6d4b817c257a958",
"c19b763b0577beb2e0032812e18e567d",
"06005cd2700c136d09e71838645d36ff" };
avatar
.setUrl("http://www.gravatar.com/avatar/"
// +
// hashGravatarEmail((Math.random()>.5?"[email protected]":"[email protected]"))
+ fakeAvatar[(int) (Math.random()
* fakeAvatar.length - 0.0000000000001d)]
+ ".jpg");
/*
* Copy resources to the content repository - the file system. try {
* copyResourcesToRepository(advertisement); } catch (Exception e) {
* e.printStackTrace(); }
*/
AdvertisementEntity entity = advAdapter.toEntity(advertisement);
advFacade.create(entity);
/*
if (img != null) {
String reference = copyResourcesToRepository(avatar.getName(),
img.getValue(), entity.getId(), header
.getCustomerDomainId());
entity.getAvatar().setReference(reference);
advFacade.update(entity);
}*/
logger.finest("Advertisement #" + entity.getId() + " published ("
+ entity.getTitle() + ")");
return advAdapter.toSoap(entity);
} catch (NoSuchAlgorithmException e) {
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
| public Advertisement publishOperation(final Advertisement advertisement,
final PublishingHeader header) {
// TODO: to implement the real code.
try {
// TODO: re-think a factory to reuse adapters...
Customer customer = new Customer();
customer.setLogin(header.getCustomerLogin());
customer.setDomainId(header.getCustomerDomainId());
advertisement.setCustomer(customer);
AvatarImageOrUrl avatar = advertisement.getAvatarImageOrUrl();
AtavarImage img = null;
/*
* if (avatar.getGravatarEmail() != null) { avatar
* .setUrl("http://www.gravatar.com/avatar/" +
* hashGravatarEmail(avatar.getGravatarEmail()) + ".jpg"); } else if
* (avatar.getUrl() != null) { img = avatar.getImage(); AtavarImage
* temp = new AtavarImage();
* temp.setContentType(img.getContentType()); temp.setValue(null);
* avatar.setImage(temp); }
*/
String[] fakeAvatar = { "767fc9c115a1b989744c755db47feb60",
"5915fd742d0c26f6a584f9d21f991b9c",
"f4510afa5a1ceb6ae7c058c25051aed9",
"84987b436214f52ec0b04cd1f8a73c3c",
"bb29d699b5cba218c313b61aa82249da",
"b0b357b291ac72bc7da81b4d74430fe6",
"d212b7b6c54f0ccb2c848d23440b33ba",
"1a33e7a69df4f675fcd799edca088ac2",
"992df4737c71df3189eed335a98fa0c0",
"a558f2098da8edf67d9a673739d18aff",
"8379aabc84ecee06f48d8ca48e09eef4",
"4d346581a3340e32cf93703c9ce46bd4",
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
hashGravatarEmail("[email protected]"),
"eed0e8d62f562daf038f182de7f1fd42",
"7acb05d25c22cbc0942a5e3de59392bb",
"df126b735a54ed95b4f4cc346b786843",
"aac7e0386facd070f6d4b817c257a958",
"c19b763b0577beb2e0032812e18e567d",
"06005cd2700c136d09e71838645d36ff" };
avatar
.setUrl("http://www.gravatar.com/avatar/"
// +
// hashGravatarEmail((Math.random()>.5?"[email protected]":"[email protected]"))
+ fakeAvatar[(int) (Math.random()
* fakeAvatar.length - 0.0000000000001d)]
+ ".jpg");
/*
* Copy resources to the content repository - the file system. try {
* copyResourcesToRepository(advertisement); } catch (Exception e) {
* e.printStackTrace(); }
*/
AdvertisementEntity entity = advAdapter.toEntity(advertisement);
advFacade.create(entity);
/*
if (img != null) {
String reference = copyResourcesToRepository(avatar.getName(),
img.getValue(), entity.getId(), header
.getCustomerDomainId());
entity.getAvatar().setReference(reference);
advFacade.update(entity);
}*/
logger.finest("Advertisement #" + entity.getId() + " published ("
+ entity.getTitle() + ")");
return advAdapter.toSoap(entity);
} catch (NoSuchAlgorithmException e) {
logger.severe(e.getMessage());
throw new WebServiceException(e);
}
}
|
diff --git a/src/com/sohail/alam/mango_pi/smart/cache/SmartCacheHistoryImpl.java b/src/com/sohail/alam/mango_pi/smart/cache/SmartCacheHistoryImpl.java
index cb133fb..414a9f5 100644
--- a/src/com/sohail/alam/mango_pi/smart/cache/SmartCacheHistoryImpl.java
+++ b/src/com/sohail/alam/mango_pi/smart/cache/SmartCacheHistoryImpl.java
@@ -1,227 +1,227 @@
package com.sohail.alam.mango_pi.smart.cache;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
/**
* User: Sohail Alam
* Version: 1.0.0
* Date: 6/7/13
* Time: 10:16 PM
*/
class SmartCacheHistoryImpl<K, V extends SmartCachePojo> implements SmartCacheHistory<K, V> {
protected static final SmartCacheHistory HISTORY = new SmartCacheHistoryImpl();
private final ConcurrentHashMap<K, SmartCacheHistoryPojo> SMART_CACHE_HISTORY;
private final ExecutorService HISTORY_EXECUTOR = Executors.newSingleThreadExecutor();
private AtomicLong maxElementCount = new AtomicLong(1000);
private SmartCacheHistoryImpl() {
SMART_CACHE_HISTORY = new ConcurrentHashMap<K, SmartCacheHistoryPojo>();
}
/**
* Add to history.
*
* @param reason the reason
* @param key the key
* @param value the value
*/
@Override
public void addToHistory(String reason, K key, V value) {
if (SMART_CACHE_HISTORY.size() >= maxElementCount.get())
SMART_CACHE_HISTORY.clear();
SMART_CACHE_HISTORY.put(key, new SmartCacheHistoryPojo<K, V>(reason, key, value));
}
/**
* Add all to history.
*
* @param reason the reason
* @param dataMap the data map
*/
@Override
public void addAllToHistory(String reason, ConcurrentMap<K, V> dataMap) {
if (dataMap != null) {
for (K key : dataMap.keySet()) {
addToHistory(reason, key, dataMap.get(key));
}
}
}
/**
* View history.
*
* @param key the key
*
* @return the string
*/
@Override
public String viewHistory(K key) {
StringBuffer buffer = new StringBuffer();
SmartCacheHistoryPojo found = SMART_CACHE_HISTORY.get(key);
buffer.append("Smart Cache History: ");
buffer.append("\r\n--------------------------------------------------------" +
"---------------------------------------------------------------\r\n");
buffer.append(String.format("%-15s", "REASON"));
buffer.append(String.format("%-50s", "KEY"));
buffer.append(String.format("%-35s", "CREATION TIME"));
buffer.append(String.format("%-35s", "DELETION TIME"));
buffer.append("\r\n--------------------------------------------------------" +
"---------------------------------------------------------------\r\n");
buffer.append(String.format("%-15s", found.DELETE_REASON));
buffer.append(String.format("%-50s", found.KEY));
buffer.append(String.format("%-35s", found.CREATION_TIME));
buffer.append(String.format("%-35s", found.DELETION_TIME));
buffer.append("\r\n");
return buffer.toString();
}
/**
* View history.
*
* @param reason the reason
*
* @return the string
*/
@Override
public String viewHistoryForReason(String reason) {
StringBuffer buffer = new StringBuffer();
SmartCacheHistoryPojo foundPojo = null;
boolean found = false;
buffer.append("Smart Cache History: ");
buffer.append("\r\n--------------------------------------------------------" +
"---------------------------------------------------------------\r\n");
buffer.append(String.format("%-15s", "REASON"));
buffer.append(String.format("%-50s", "KEY"));
buffer.append(String.format("%-35s", "CREATION TIME"));
buffer.append(String.format("%-35s", "DELETION TIME"));
buffer.append("\r\n--------------------------------------------------------" +
"---------------------------------------------------------------\r\n");
for (K key : SMART_CACHE_HISTORY.keySet()) {
if ((foundPojo = SMART_CACHE_HISTORY.get(key)).DELETE_REASON.equals(reason)) {
buffer.append(String.format("%-15s", foundPojo.DELETE_REASON));
buffer.append(String.format("%-50s", foundPojo.KEY));
buffer.append(String.format("%-35s", foundPojo.CREATION_TIME));
buffer.append(String.format("%-35s", foundPojo.DELETION_TIME));
buffer.append("\r\n");
found = true;
}
}
if (!found) {
buffer.append("There are no history corresponding to the reason: " + reason);
buffer.append("\r\n");
}
return buffer.toString();
}
/**
* View history.
*
* @return the string
*/
@Override
public String viewAllHistory() {
StringBuffer buffer = new StringBuffer();
SmartCacheHistoryPojo foundPojo = null;
buffer.append("Smart Cache History: ");
buffer.append("\r\n--------------------------------------------------------" +
"---------------------------------------------------------------\r\n");
buffer.append(String.format("%-15s", "REASON"));
buffer.append(String.format("%-50s", "KEY"));
buffer.append(String.format("%-35s", "CREATION TIME"));
buffer.append(String.format("%-35s", "DELETION TIME"));
buffer.append("\r\n--------------------------------------------------------" +
"---------------------------------------------------------------\r\n");
for (K key : SMART_CACHE_HISTORY.keySet()) {
foundPojo = SMART_CACHE_HISTORY.get(key);
buffer.append(String.format("%-15s", foundPojo.DELETE_REASON));
buffer.append(String.format("%-50s", foundPojo.KEY));
buffer.append(String.format("%-35s", foundPojo.CREATION_TIME));
buffer.append(String.format("%-35s", foundPojo.DELETION_TIME));
buffer.append("\r\n");
}
return buffer.toString();
}
/**
* Set the maximum number of entries after which the History is
* deleted permanently.
*
* @param maxElementCount the max element count
*/
@Override
public void autoDeleteHistory(int maxElementCount) {
this.maxElementCount.set(maxElementCount);
}
/**
* Purges the contents of History into a user defined file.
* By default the SmartCache will dump the data into a file named -
* SmartCacheHistory_(current-date/time).txt
*
* @param filePath the absolute file path for the dump file.
*/
@Override
public void purgeHistory(String filePath) throws Exception {
HISTORY_EXECUTOR.execute(new PurgerClass(filePath));
}
private final class PurgerClass implements Runnable {
String filePath;
public PurgerClass(String filePath) {
this.filePath = filePath;
}
@Override
public void run() {
String directory = "/";
String fileName = "SmartCacheHistory_" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + ".txt";
if (filePath.contains("/")) {
directory = filePath.substring(0, filePath.lastIndexOf("/") + 1);
fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
} else if (filePath.contains("\\")) {
directory = filePath.substring(0, filePath.lastIndexOf("\\") + 1);
fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
}
// Create the directories if not present
File dir = new File(directory);
dir.mkdirs();
// Create the file
- File file = new File(fileName);
+ File file = new File(dir.getAbsoluteFile() + fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(viewAllHistory().getBytes());
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
| true | true | public void run() {
String directory = "/";
String fileName = "SmartCacheHistory_" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + ".txt";
if (filePath.contains("/")) {
directory = filePath.substring(0, filePath.lastIndexOf("/") + 1);
fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
} else if (filePath.contains("\\")) {
directory = filePath.substring(0, filePath.lastIndexOf("\\") + 1);
fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
}
// Create the directories if not present
File dir = new File(directory);
dir.mkdirs();
// Create the file
File file = new File(fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(viewAllHistory().getBytes());
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| public void run() {
String directory = "/";
String fileName = "SmartCacheHistory_" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + ".txt";
if (filePath.contains("/")) {
directory = filePath.substring(0, filePath.lastIndexOf("/") + 1);
fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
} else if (filePath.contains("\\")) {
directory = filePath.substring(0, filePath.lastIndexOf("\\") + 1);
fileName = filePath.substring(filePath.lastIndexOf("\\") + 1);
}
// Create the directories if not present
File dir = new File(directory);
dir.mkdirs();
// Create the file
File file = new File(dir.getAbsoluteFile() + fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
fos.write(viewAllHistory().getBytes());
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|
diff --git a/src/replicatorg/app/ui/controlpanel/ExtruderPanel.java b/src/replicatorg/app/ui/controlpanel/ExtruderPanel.java
index 115dae8c..f6f48fde 100644
--- a/src/replicatorg/app/ui/controlpanel/ExtruderPanel.java
+++ b/src/replicatorg/app/ui/controlpanel/ExtruderPanel.java
@@ -1,529 +1,535 @@
package replicatorg.app.ui.controlpanel;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.image.BufferedImage;
import java.util.Date;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.TickUnits;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYStepRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeTableXYDataset;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import replicatorg.app.Base;
import replicatorg.app.MachineController;
import replicatorg.drivers.Driver;
import replicatorg.drivers.RetryException;
import replicatorg.machine.model.ToolModel;
public class ExtruderPanel extends JPanel implements FocusListener, ActionListener, ItemListener {
private ToolModel toolModel;
private MachineController machine;
public ToolModel getTool() { return toolModel; }
protected JTextField currentTempField;
protected JTextField platformCurrentTempField;
protected double targetTemperature;
protected double targetPlatformTemperature;
final private static Color targetColor = Color.BLUE;
final private static Color measuredColor = Color.RED;
final private static Color targetPlatformColor = Color.YELLOW;
final private static Color measuredPlatformColor = Color.WHITE;
long startMillis = System.currentTimeMillis();
private TimeTableXYDataset measuredDataset = new TimeTableXYDataset();
private TimeTableXYDataset targetDataset = new TimeTableXYDataset();
private TimeTableXYDataset measuredPlatformDataset = new TimeTableXYDataset();
private TimeTableXYDataset targetPlatformDataset = new TimeTableXYDataset();
/**
* Make a label with an icon indicating its color on the graph.
* @param text The text of the label
* @param c The color of the matching line on the graph
* @return the generated label
*/
private JLabel makeKeyLabel(String text, Color c) {
BufferedImage image = new BufferedImage(10,10,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setColor(c);
g.fillRect(0,0,10,10);
//image.getGraphics().fillRect(0,0,10,10);
Icon icon = new ImageIcon(image);
return new JLabel(text,icon,SwingConstants.LEFT);
}
public ChartPanel makeChart(ToolModel t) {
JFreeChart chart = ChartFactory.createXYLineChart(null, null, null,
measuredDataset, PlotOrientation.VERTICAL,
false, false, false);
chart.setBorderVisible(false);
chart.setBackgroundPaint(null);
XYPlot plot = chart.getXYPlot();
ValueAxis axis = plot.getDomainAxis();
axis.setLowerMargin(0);
axis.setFixedAutoRange(3L*60L*1000L); // auto range to three minutes
TickUnits unitSource = new TickUnits();
unitSource.add(new NumberTickUnit(60L*1000L)); // minutes
unitSource.add(new NumberTickUnit(1L*1000L)); // seconds
axis.setStandardTickUnits(unitSource);
axis.setTickLabelsVisible(false); // We don't need to see the millisecond count
axis = plot.getRangeAxis();
axis.setRange(0,260); // set termperature range from 0 to 260 degrees C
// Tweak L&F of chart
//((XYAreaRenderer)plot.getRenderer()).setOutline(true);
XYStepRenderer renderer = new XYStepRenderer();
plot.setDataset(1, targetDataset);
plot.setRenderer(1, renderer);
plot.getRenderer(1).setSeriesPaint(0, targetColor);
plot.getRenderer(0).setSeriesPaint(0, measuredColor);
if (t.hasHeatedPlatform()) {
plot.setDataset(2,measuredPlatformDataset);
plot.setRenderer(2, new XYLineAndShapeRenderer(true,false));
plot.getRenderer(2).setSeriesPaint(0, measuredPlatformColor);
plot.setDataset(3,targetPlatformDataset);
plot.setRenderer(3, new XYStepRenderer());
plot.getRenderer(3).setSeriesPaint(0, targetPlatformColor);
}
plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new Dimension(400,140));
chartPanel.setOpaque(false);
return chartPanel;
}
private final Dimension labelMinimumSize = new Dimension(175, 25);
private JLabel makeLabel(String text) {
JLabel label = new JLabel();
label.setText(text);
label.setMinimumSize(labelMinimumSize);
label.setMaximumSize(labelMinimumSize);
label.setPreferredSize(labelMinimumSize);
label.setHorizontalAlignment(JLabel.LEFT);
return label;
}
public ExtruderPanel(MachineController machine, ToolModel t) {
this.machine = machine;
this.toolModel = t;
int textBoxWidth = 75;
Dimension panelSize = new Dimension(420, 30);
Driver driver = machine.getDriver();
// create our initial panel
setLayout(new MigLayout());
// create our motor options
if (t.hasMotor()) {
// Due to current implementation issues, we need to send the PWM
// before the RPM
// for a stepper motor. Thus we display both controls in these
// cases.
{
// our motor speed vars
JLabel label = makeLabel("Motor Speed (PWM)");
JTextField field = new JTextField();
field.setMaximumSize(new Dimension(textBoxWidth, 25));
field.setMinimumSize(new Dimension(textBoxWidth, 25));
field.setPreferredSize(new Dimension(textBoxWidth, 25));
field.setName("motor-speed-pwm");
field.addFocusListener(this);
field.setActionCommand("handleTextfield");
field.setText(Integer.toString(t.getMotorSpeedPWM()));
+ try {
+ driver.setMotorSpeedPWM(Integer.parseInt(field.getText()));
+ } catch (Exception e) {} // ignore parse errors.
field.addActionListener(this);
add(label);
add(field,"wrap");
}
if (t.motorHasEncoder() || t.motorIsStepper()) {
// our motor speed vars
JLabel label = makeLabel("Motor Speed (RPM)");
JTextField field = new JTextField();
field.setMaximumSize(new Dimension(textBoxWidth, 25));
field.setMinimumSize(new Dimension(textBoxWidth, 25));
field.setPreferredSize(new Dimension(textBoxWidth, 25));
field.setName("motor-speed");
field.addFocusListener(this);
field.setActionCommand("handleTextfield");
field.setText(Double.toString(t.getMotorSpeedRPM()));
+ try {
+ driver.setMotorRPM(Double.parseDouble(field.getText()));
+ } catch (Exception e) {} // ignore parse errors.
field.addActionListener(this);
add(label);
add(field,"wrap");
}
// create our motor options
JLabel motorEnabledLabel = makeLabel("Motor Control");
JRadioButton motorReverseButton = new JRadioButton("reverse");
motorReverseButton.setName("motor-reverse");
motorReverseButton.addItemListener(this);
JRadioButton motorStoppedButton = new JRadioButton("stop");
motorStoppedButton.setName("motor-stop");
motorStoppedButton.addItemListener(this);
JRadioButton motorForwardButton = new JRadioButton("forward");
motorForwardButton.setName("motor-forward");
motorForwardButton.addItemListener(this);
ButtonGroup motorControl = new ButtonGroup();
motorControl.add(motorReverseButton);
motorControl.add(motorStoppedButton);
motorControl.add(motorForwardButton);
// add components in.
add(motorEnabledLabel,"split,spanx");
add(motorReverseButton);
add(motorStoppedButton);
add(motorForwardButton,"wrap");
}
// our temperature fields
if (t.hasHeater()) {
JLabel targetTempLabel = makeKeyLabel("Target Temperature (C)",targetColor);
JTextField targetTempField = new JTextField();
targetTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
targetTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
targetTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
targetTempField.setName("target-temp");
targetTempField.addFocusListener(this);
targetTemperature = driver.getTemperatureSetting();
targetTempField.setText(Double.toString(targetTemperature));
targetTempField.setActionCommand("handleTextfield");
targetTempField.addActionListener(this);
JLabel currentTempLabel = makeKeyLabel("Current Temperature (C)",measuredColor);
currentTempField = new JTextField();
currentTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
currentTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
currentTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
currentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(currentTempField,"wrap");
}
// our heated platform fields
if (t.hasHeatedPlatform()) {
JLabel targetTempLabel = makeKeyLabel("Platform Target Temp (C)",targetPlatformColor);
JTextField targetTempField = new JTextField();
targetTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
targetTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
targetTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
targetTempField.setName("platform-target-temp");
targetTempField.addFocusListener(this);
double temperature = driver.getPlatformTemperatureSetting();
targetPlatformTemperature = temperature;
targetTempField.setText(Double.toString(temperature));
targetTempField.setActionCommand("handleTextfield");
targetTempField.addActionListener(this);
JLabel currentTempLabel = makeKeyLabel("Platform Current Temp (C)",measuredPlatformColor);
platformCurrentTempField = new JTextField();
platformCurrentTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
platformCurrentTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
platformCurrentTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
platformCurrentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(platformCurrentTempField,"wrap");
}
if (t.hasHeater() || t.hasHeatedPlatform()) {
add(new JLabel("Temperature Chart"),"growx,spanx,wrap");
add(makeChart(t),"growx,spanx,wrap");
}
// flood coolant controls
if (t.hasFloodCoolant()) {
JLabel floodCoolantLabel = makeLabel("Flood Coolant");
JCheckBox floodCoolantCheck = new JCheckBox("enable");
floodCoolantCheck.setName("flood-coolant");
floodCoolantCheck.addItemListener(this);
add(floodCoolantLabel);
add(floodCoolantCheck,"wrap");
}
// mist coolant controls
if (t.hasMistCoolant()) {
JLabel mistCoolantLabel = makeLabel("Mist Coolant");
JCheckBox mistCoolantCheck = new JCheckBox("enable");
mistCoolantCheck.setName("mist-coolant");
mistCoolantCheck.addItemListener(this);
add(mistCoolantLabel);
add(mistCoolantCheck,"wrap");
}
// cooling fan controls
if (t.hasFan()) {
String fanString = "Cooling Fan";
String enableString = "enable";
Element xml = findMappingNode(t.getXml(),"fan");
if (xml != null) {
fanString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel fanLabel = makeLabel(fanString);
JCheckBox fanCheck = new JCheckBox(enableString);
fanCheck.setName("fan-check");
fanCheck.addItemListener(this);
add(fanLabel);
add(fanCheck,"wrap");
}
// cooling fan controls
if (t.hasAutomatedPlatform()) {
String abpString = "Build platform belt";
String enableString = "enable";
JLabel abpLabel = makeLabel(abpString);
JCheckBox abpCheck = new JCheckBox(enableString);
abpCheck.setName("abp-check");
abpCheck.addItemListener(this);
add(abpLabel);
add(abpCheck,"wrap");
}
// valve controls
if (t.hasValve()) {
String valveString = "Valve";
String enableString = "open";
Element xml = findMappingNode(t.getXml(),"valve");
if (xml != null) {
valveString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel valveLabel = makeLabel(valveString);
JCheckBox valveCheck = new JCheckBox(enableString);
valveCheck.setName("valve-check");
valveCheck.addItemListener(this);
add(valveLabel);
add(valveCheck,"wrap");
}
// valve controls
if (t.hasCollet()) {
JLabel colletLabel = makeLabel("Collet");
JCheckBox colletCheck = new JCheckBox("open");
colletCheck.setName("collet-check");
colletCheck.addItemListener(this);
JPanel colletPanel = new JPanel();
colletPanel.setLayout(new BoxLayout(colletPanel,
BoxLayout.LINE_AXIS));
colletPanel.setMaximumSize(panelSize);
colletPanel.setMinimumSize(panelSize);
colletPanel.setPreferredSize(panelSize);
add(colletLabel);
add(colletCheck,"wrap");
}
}
private Element findMappingNode(Node xml,String portName) {
// scan the remapping nodes.
NodeList children = xml.getChildNodes();
for (int j=0; j<children.getLength(); j++) {
Node child = children.item(j);
if (child.getNodeName().equals("remap")) {
Element e = (Element)child;
if (e.getAttribute("port").equals(portName)) {
return e;
}
}
}
return null;
}
public void updateStatus() {
Second second = new Second(new Date(System.currentTimeMillis() - startMillis));
if (machine.getModel().currentTool() == toolModel && toolModel.hasHeater()) {
double temperature = machine.getDriver().getTemperature();
updateTemperature(second, temperature);
}
if (machine.getModel().currentTool() == toolModel && toolModel.hasHeatedPlatform()) {
double temperature = machine.getDriver().getPlatformTemperature();
updatePlatformTemperature(second, temperature);
}
}
synchronized public void updateTemperature(Second second, double temperature)
{
currentTempField.setText(Double.toString(temperature));
measuredDataset.add(second, temperature,"a");
targetDataset.add(second, targetTemperature,"a");
}
synchronized public void updatePlatformTemperature(Second second, double temperature)
{
platformCurrentTempField.setText(Double.toString(temperature));
measuredPlatformDataset.add(second, temperature,"a");
targetPlatformDataset.add(second, targetPlatformTemperature,"a");
}
public void focusGained(FocusEvent e) {
}
public void focusLost(FocusEvent e) {
JTextField source = (JTextField) e.getSource();
try {
handleChangedTextField(source);
} catch (RetryException e1) {
Base.logger.severe("Could not execute command; machine busy.");
}
}
public void handleChangedTextField(JTextField source) throws RetryException
{
String name = source.getName();
Driver driver = machine.getDriver();
if (source.getText().length() > 0) {
if (name.equals("target-temp")) {
double temperature = Double.parseDouble(source.getText());
driver.setTemperature(temperature);
targetTemperature = temperature;
} else if (name.equals("platform-target-temp")) {
double temperature = Double.parseDouble(source.getText());
driver.setPlatformTemperature(temperature);
targetPlatformTemperature = temperature;
} else if (name.equals("motor-speed")) {
driver.setMotorRPM(Double.parseDouble(source.getText()));
} else if (name.equals("motor-speed-pwm")) {
driver.setMotorSpeedPWM(Integer.parseInt(source.getText()));
} else
Base.logger.warning("Unhandled text field: "+name);
}
}
public void itemStateChanged(ItemEvent e) {
Component source = (Component) e.getItemSelectable();
String name = source.getName();
Driver driver = machine.getDriver();
try {
if (e.getStateChange() == ItemEvent.SELECTED) {
if (name.equals("motor-forward")) {
driver.setMotorDirection(ToolModel.MOTOR_CLOCKWISE);
driver.enableMotor();
} else if (name.equals("motor-reverse")) {
driver.setMotorDirection(ToolModel.MOTOR_COUNTER_CLOCKWISE);
driver.enableMotor();
} else if (name.equals("motor-stop"))
driver.disableMotor();
else if (name.equals("spindle-enabled"))
driver.enableSpindle();
else if (name.equals("flood-coolant"))
driver.enableFloodCoolant();
else if (name.equals("mist-coolant"))
driver.enableMistCoolant();
else if (name.equals("fan-check"))
driver.enableFan();
else if (name.equals("abp-check"))
driver.enableFan();
else if (name.equals("valve-check"))
driver.openValve();
else if (name.equals("collet-check"))
driver.openCollet();
else
Base.logger.warning("checkbox selected: " + source.getName());
} else {
if (name.equals("motor-enabled"))
driver.disableMotor();
else if (name.equals("spindle-enabled"))
driver.disableSpindle();
else if (name.equals("flood-coolant"))
driver.disableFloodCoolant();
else if (name.equals("mist-coolant"))
driver.disableMistCoolant();
else if (name.equals("fan-check"))
driver.disableFan();
else if (name.equals("abp-check"))
driver.disableFan();
else if (name.equals("valve-check"))
driver.closeValve();
else if (name.equals("collet-check"))
driver.closeCollet();
}
} catch (RetryException r) {
Base.logger.severe("Could not execute command; machine busy.");
}
}
public void actionPerformed(ActionEvent e) {
String s = e.getActionCommand();
if(s.equals("handleTextfield"))
{
JTextField source = (JTextField) e.getSource();
try {
handleChangedTextField(source);
} catch (RetryException e1) {
Base.logger.severe("Could not execute command; machine busy.");
}
source.selectAll();
}
}
}
| false | true | public ExtruderPanel(MachineController machine, ToolModel t) {
this.machine = machine;
this.toolModel = t;
int textBoxWidth = 75;
Dimension panelSize = new Dimension(420, 30);
Driver driver = machine.getDriver();
// create our initial panel
setLayout(new MigLayout());
// create our motor options
if (t.hasMotor()) {
// Due to current implementation issues, we need to send the PWM
// before the RPM
// for a stepper motor. Thus we display both controls in these
// cases.
{
// our motor speed vars
JLabel label = makeLabel("Motor Speed (PWM)");
JTextField field = new JTextField();
field.setMaximumSize(new Dimension(textBoxWidth, 25));
field.setMinimumSize(new Dimension(textBoxWidth, 25));
field.setPreferredSize(new Dimension(textBoxWidth, 25));
field.setName("motor-speed-pwm");
field.addFocusListener(this);
field.setActionCommand("handleTextfield");
field.setText(Integer.toString(t.getMotorSpeedPWM()));
field.addActionListener(this);
add(label);
add(field,"wrap");
}
if (t.motorHasEncoder() || t.motorIsStepper()) {
// our motor speed vars
JLabel label = makeLabel("Motor Speed (RPM)");
JTextField field = new JTextField();
field.setMaximumSize(new Dimension(textBoxWidth, 25));
field.setMinimumSize(new Dimension(textBoxWidth, 25));
field.setPreferredSize(new Dimension(textBoxWidth, 25));
field.setName("motor-speed");
field.addFocusListener(this);
field.setActionCommand("handleTextfield");
field.setText(Double.toString(t.getMotorSpeedRPM()));
field.addActionListener(this);
add(label);
add(field,"wrap");
}
// create our motor options
JLabel motorEnabledLabel = makeLabel("Motor Control");
JRadioButton motorReverseButton = new JRadioButton("reverse");
motorReverseButton.setName("motor-reverse");
motorReverseButton.addItemListener(this);
JRadioButton motorStoppedButton = new JRadioButton("stop");
motorStoppedButton.setName("motor-stop");
motorStoppedButton.addItemListener(this);
JRadioButton motorForwardButton = new JRadioButton("forward");
motorForwardButton.setName("motor-forward");
motorForwardButton.addItemListener(this);
ButtonGroup motorControl = new ButtonGroup();
motorControl.add(motorReverseButton);
motorControl.add(motorStoppedButton);
motorControl.add(motorForwardButton);
// add components in.
add(motorEnabledLabel,"split,spanx");
add(motorReverseButton);
add(motorStoppedButton);
add(motorForwardButton,"wrap");
}
// our temperature fields
if (t.hasHeater()) {
JLabel targetTempLabel = makeKeyLabel("Target Temperature (C)",targetColor);
JTextField targetTempField = new JTextField();
targetTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
targetTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
targetTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
targetTempField.setName("target-temp");
targetTempField.addFocusListener(this);
targetTemperature = driver.getTemperatureSetting();
targetTempField.setText(Double.toString(targetTemperature));
targetTempField.setActionCommand("handleTextfield");
targetTempField.addActionListener(this);
JLabel currentTempLabel = makeKeyLabel("Current Temperature (C)",measuredColor);
currentTempField = new JTextField();
currentTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
currentTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
currentTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
currentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(currentTempField,"wrap");
}
// our heated platform fields
if (t.hasHeatedPlatform()) {
JLabel targetTempLabel = makeKeyLabel("Platform Target Temp (C)",targetPlatformColor);
JTextField targetTempField = new JTextField();
targetTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
targetTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
targetTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
targetTempField.setName("platform-target-temp");
targetTempField.addFocusListener(this);
double temperature = driver.getPlatformTemperatureSetting();
targetPlatformTemperature = temperature;
targetTempField.setText(Double.toString(temperature));
targetTempField.setActionCommand("handleTextfield");
targetTempField.addActionListener(this);
JLabel currentTempLabel = makeKeyLabel("Platform Current Temp (C)",measuredPlatformColor);
platformCurrentTempField = new JTextField();
platformCurrentTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
platformCurrentTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
platformCurrentTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
platformCurrentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(platformCurrentTempField,"wrap");
}
if (t.hasHeater() || t.hasHeatedPlatform()) {
add(new JLabel("Temperature Chart"),"growx,spanx,wrap");
add(makeChart(t),"growx,spanx,wrap");
}
// flood coolant controls
if (t.hasFloodCoolant()) {
JLabel floodCoolantLabel = makeLabel("Flood Coolant");
JCheckBox floodCoolantCheck = new JCheckBox("enable");
floodCoolantCheck.setName("flood-coolant");
floodCoolantCheck.addItemListener(this);
add(floodCoolantLabel);
add(floodCoolantCheck,"wrap");
}
// mist coolant controls
if (t.hasMistCoolant()) {
JLabel mistCoolantLabel = makeLabel("Mist Coolant");
JCheckBox mistCoolantCheck = new JCheckBox("enable");
mistCoolantCheck.setName("mist-coolant");
mistCoolantCheck.addItemListener(this);
add(mistCoolantLabel);
add(mistCoolantCheck,"wrap");
}
// cooling fan controls
if (t.hasFan()) {
String fanString = "Cooling Fan";
String enableString = "enable";
Element xml = findMappingNode(t.getXml(),"fan");
if (xml != null) {
fanString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel fanLabel = makeLabel(fanString);
JCheckBox fanCheck = new JCheckBox(enableString);
fanCheck.setName("fan-check");
fanCheck.addItemListener(this);
add(fanLabel);
add(fanCheck,"wrap");
}
// cooling fan controls
if (t.hasAutomatedPlatform()) {
String abpString = "Build platform belt";
String enableString = "enable";
JLabel abpLabel = makeLabel(abpString);
JCheckBox abpCheck = new JCheckBox(enableString);
abpCheck.setName("abp-check");
abpCheck.addItemListener(this);
add(abpLabel);
add(abpCheck,"wrap");
}
// valve controls
if (t.hasValve()) {
String valveString = "Valve";
String enableString = "open";
Element xml = findMappingNode(t.getXml(),"valve");
if (xml != null) {
valveString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel valveLabel = makeLabel(valveString);
JCheckBox valveCheck = new JCheckBox(enableString);
valveCheck.setName("valve-check");
valveCheck.addItemListener(this);
add(valveLabel);
add(valveCheck,"wrap");
}
// valve controls
if (t.hasCollet()) {
JLabel colletLabel = makeLabel("Collet");
JCheckBox colletCheck = new JCheckBox("open");
colletCheck.setName("collet-check");
colletCheck.addItemListener(this);
JPanel colletPanel = new JPanel();
colletPanel.setLayout(new BoxLayout(colletPanel,
BoxLayout.LINE_AXIS));
colletPanel.setMaximumSize(panelSize);
colletPanel.setMinimumSize(panelSize);
colletPanel.setPreferredSize(panelSize);
add(colletLabel);
add(colletCheck,"wrap");
}
}
| public ExtruderPanel(MachineController machine, ToolModel t) {
this.machine = machine;
this.toolModel = t;
int textBoxWidth = 75;
Dimension panelSize = new Dimension(420, 30);
Driver driver = machine.getDriver();
// create our initial panel
setLayout(new MigLayout());
// create our motor options
if (t.hasMotor()) {
// Due to current implementation issues, we need to send the PWM
// before the RPM
// for a stepper motor. Thus we display both controls in these
// cases.
{
// our motor speed vars
JLabel label = makeLabel("Motor Speed (PWM)");
JTextField field = new JTextField();
field.setMaximumSize(new Dimension(textBoxWidth, 25));
field.setMinimumSize(new Dimension(textBoxWidth, 25));
field.setPreferredSize(new Dimension(textBoxWidth, 25));
field.setName("motor-speed-pwm");
field.addFocusListener(this);
field.setActionCommand("handleTextfield");
field.setText(Integer.toString(t.getMotorSpeedPWM()));
try {
driver.setMotorSpeedPWM(Integer.parseInt(field.getText()));
} catch (Exception e) {} // ignore parse errors.
field.addActionListener(this);
add(label);
add(field,"wrap");
}
if (t.motorHasEncoder() || t.motorIsStepper()) {
// our motor speed vars
JLabel label = makeLabel("Motor Speed (RPM)");
JTextField field = new JTextField();
field.setMaximumSize(new Dimension(textBoxWidth, 25));
field.setMinimumSize(new Dimension(textBoxWidth, 25));
field.setPreferredSize(new Dimension(textBoxWidth, 25));
field.setName("motor-speed");
field.addFocusListener(this);
field.setActionCommand("handleTextfield");
field.setText(Double.toString(t.getMotorSpeedRPM()));
try {
driver.setMotorRPM(Double.parseDouble(field.getText()));
} catch (Exception e) {} // ignore parse errors.
field.addActionListener(this);
add(label);
add(field,"wrap");
}
// create our motor options
JLabel motorEnabledLabel = makeLabel("Motor Control");
JRadioButton motorReverseButton = new JRadioButton("reverse");
motorReverseButton.setName("motor-reverse");
motorReverseButton.addItemListener(this);
JRadioButton motorStoppedButton = new JRadioButton("stop");
motorStoppedButton.setName("motor-stop");
motorStoppedButton.addItemListener(this);
JRadioButton motorForwardButton = new JRadioButton("forward");
motorForwardButton.setName("motor-forward");
motorForwardButton.addItemListener(this);
ButtonGroup motorControl = new ButtonGroup();
motorControl.add(motorReverseButton);
motorControl.add(motorStoppedButton);
motorControl.add(motorForwardButton);
// add components in.
add(motorEnabledLabel,"split,spanx");
add(motorReverseButton);
add(motorStoppedButton);
add(motorForwardButton,"wrap");
}
// our temperature fields
if (t.hasHeater()) {
JLabel targetTempLabel = makeKeyLabel("Target Temperature (C)",targetColor);
JTextField targetTempField = new JTextField();
targetTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
targetTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
targetTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
targetTempField.setName("target-temp");
targetTempField.addFocusListener(this);
targetTemperature = driver.getTemperatureSetting();
targetTempField.setText(Double.toString(targetTemperature));
targetTempField.setActionCommand("handleTextfield");
targetTempField.addActionListener(this);
JLabel currentTempLabel = makeKeyLabel("Current Temperature (C)",measuredColor);
currentTempField = new JTextField();
currentTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
currentTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
currentTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
currentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(currentTempField,"wrap");
}
// our heated platform fields
if (t.hasHeatedPlatform()) {
JLabel targetTempLabel = makeKeyLabel("Platform Target Temp (C)",targetPlatformColor);
JTextField targetTempField = new JTextField();
targetTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
targetTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
targetTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
targetTempField.setName("platform-target-temp");
targetTempField.addFocusListener(this);
double temperature = driver.getPlatformTemperatureSetting();
targetPlatformTemperature = temperature;
targetTempField.setText(Double.toString(temperature));
targetTempField.setActionCommand("handleTextfield");
targetTempField.addActionListener(this);
JLabel currentTempLabel = makeKeyLabel("Platform Current Temp (C)",measuredPlatformColor);
platformCurrentTempField = new JTextField();
platformCurrentTempField.setMaximumSize(new Dimension(textBoxWidth, 25));
platformCurrentTempField.setMinimumSize(new Dimension(textBoxWidth, 25));
platformCurrentTempField.setPreferredSize(new Dimension(textBoxWidth, 25));
platformCurrentTempField.setEnabled(false);
add(targetTempLabel);
add(targetTempField,"wrap");
add(currentTempLabel);
add(platformCurrentTempField,"wrap");
}
if (t.hasHeater() || t.hasHeatedPlatform()) {
add(new JLabel("Temperature Chart"),"growx,spanx,wrap");
add(makeChart(t),"growx,spanx,wrap");
}
// flood coolant controls
if (t.hasFloodCoolant()) {
JLabel floodCoolantLabel = makeLabel("Flood Coolant");
JCheckBox floodCoolantCheck = new JCheckBox("enable");
floodCoolantCheck.setName("flood-coolant");
floodCoolantCheck.addItemListener(this);
add(floodCoolantLabel);
add(floodCoolantCheck,"wrap");
}
// mist coolant controls
if (t.hasMistCoolant()) {
JLabel mistCoolantLabel = makeLabel("Mist Coolant");
JCheckBox mistCoolantCheck = new JCheckBox("enable");
mistCoolantCheck.setName("mist-coolant");
mistCoolantCheck.addItemListener(this);
add(mistCoolantLabel);
add(mistCoolantCheck,"wrap");
}
// cooling fan controls
if (t.hasFan()) {
String fanString = "Cooling Fan";
String enableString = "enable";
Element xml = findMappingNode(t.getXml(),"fan");
if (xml != null) {
fanString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel fanLabel = makeLabel(fanString);
JCheckBox fanCheck = new JCheckBox(enableString);
fanCheck.setName("fan-check");
fanCheck.addItemListener(this);
add(fanLabel);
add(fanCheck,"wrap");
}
// cooling fan controls
if (t.hasAutomatedPlatform()) {
String abpString = "Build platform belt";
String enableString = "enable";
JLabel abpLabel = makeLabel(abpString);
JCheckBox abpCheck = new JCheckBox(enableString);
abpCheck.setName("abp-check");
abpCheck.addItemListener(this);
add(abpLabel);
add(abpCheck,"wrap");
}
// valve controls
if (t.hasValve()) {
String valveString = "Valve";
String enableString = "open";
Element xml = findMappingNode(t.getXml(),"valve");
if (xml != null) {
valveString = xml.getAttribute("name");
enableString = xml.getAttribute("actuated");
}
JLabel valveLabel = makeLabel(valveString);
JCheckBox valveCheck = new JCheckBox(enableString);
valveCheck.setName("valve-check");
valveCheck.addItemListener(this);
add(valveLabel);
add(valveCheck,"wrap");
}
// valve controls
if (t.hasCollet()) {
JLabel colletLabel = makeLabel("Collet");
JCheckBox colletCheck = new JCheckBox("open");
colletCheck.setName("collet-check");
colletCheck.addItemListener(this);
JPanel colletPanel = new JPanel();
colletPanel.setLayout(new BoxLayout(colletPanel,
BoxLayout.LINE_AXIS));
colletPanel.setMaximumSize(panelSize);
colletPanel.setMinimumSize(panelSize);
colletPanel.setPreferredSize(panelSize);
add(colletLabel);
add(colletCheck,"wrap");
}
}
|
diff --git a/src/main/java/de/juplo/plugins/hibernate4/Hbm2DdlMojo.java b/src/main/java/de/juplo/plugins/hibernate4/Hbm2DdlMojo.java
index f66f524..313c127 100644
--- a/src/main/java/de/juplo/plugins/hibernate4/Hbm2DdlMojo.java
+++ b/src/main/java/de/juplo/plugins/hibernate4/Hbm2DdlMojo.java
@@ -1,894 +1,896 @@
package de.juplo.plugins.hibernate4;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.pyx4j.log4j.MavenLogAppender;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Logger;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.MappedSuperclass;
import org.apache.maven.model.Resource;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.NamingStrategy;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaExport.Type;
import org.hibernate.tool.hbm2ddl.Target;
import org.scannotation.AnnotationDB;
/**
* Goal which extracts the hibernate-mapping-configuration and
* exports an according SQL-database-schema.
*
* @goal export
* @phase process-classes
* @threadSafe
* @requiresDependencyResolution runtime
*/
public class Hbm2DdlMojo extends AbstractMojo
{
public final static String EXPORT_SKIPPED_PROPERTY = "hibernate.export.skipped";
public final static String DRIVER_CLASS = "hibernate.connection.driver_class";
public final static String URL = "hibernate.connection.url";
public final static String USERNAME = "hibernate.connection.username";
public final static String PASSWORD = "hibernate.connection.password";
public final static String DIALECT = "hibernate.dialect";
public final static String NAMING_STRATEGY="hibernate.ejb.naming_strategy";
private final static String MD5S = "schema.md5s";
/**
* The maven project.
* <p>
* Only needed internally.
*
* @parameter property="project"
* @required
* @readonly
*/
private MavenProject project;
/**
* Build-directory.
* <p>
* Only needed internally.
*
* @parameter property="project.build.directory"
* @required
* @readonly
*/
private String buildDirectory;
/**
* Classes-Directory to scan.
* <p>
* This parameter defaults to the maven build-output-directory for classes.
* Additonally, all dependencies are scanned for annotated classes.
*
* @parameter property="project.build.outputDirectory"
*/
private String outputDirectory;
/**
* Wether to scan test-classes too, or not.
* <p>
* If this parameter is set to <code>true</code> the test-classes of the
* artifact will be scanned for hibernate-annotated classes additionally.
*
* @parameter property="hibernate.export.scan_testclasses" default-value="false"
*/
private boolean scanTestClasses;
/**
* Test-Classes-Directory to scan.
* <p>
* This parameter defaults to the maven build-output-directory for
* test-classes.
* <p>
* This parameter is only used, when <code>scanTestClasses</code> is set
* to <code>true</code>!
*
* @parameter property="project.build.testOutputDirectory"
*/
private String testOutputDirectory;
/**
* Skip execution
* <p>
* If set to <code>true</code>, the execution is skipped.
* <p>
* A skipped excecution is signaled via the maven-property
* <code>${hibernate.export.skipped}</code>.
* <p>
* The excecution is skipped automatically, if no modified or newly added
* annotated classes are found and the dialect was not changed.
*
* @parameter property="maven.test.skip" default-value="false"
*/
private boolean skip;
/**
* Force execution
* <p>
* Force execution, even if no modified or newly added annotated classes
* where found and the dialect was not changed.
* <p>
* <code>skip</code> takes precedence over <code>force</code>.
*
* @parameter property="hibernate.export.force" default-value="false"
*/
private boolean force;
/**
* SQL-Driver name.
*
* @parameter property="hibernate.connection.driver_class"
*/
private String driverClassName;
/**
* Database URL.
*
* @parameter property="hibernate.connection.url"
*/
private String url;
/**
* Database username
*
* @parameter property="hibernate.connection.username"
*/
private String username;
/**
* Database password
*
* @parameter property="hibernate.connection.password"
*/
private String password;
/**
* Hibernate dialect.
*
* @parameter property="hibernate.dialect"
*/
private String hibernateDialect;
/**
* Hibernate Naming Strategy
* @parameter property="hibernate.ejb.naming_strategy"
*/
private String hibernateNamingStrategy;
/**
* Path to Hibernate configuration file.
*
* @parameter default-value="${project.build.outputDirectory}/hibernate.properties"
*/
private String hibernateProperties;
/**
* List of Hibernate-Mapping-Files (XML).
* Multiple files can be separated with white-spaces and/or commas.
*
* @parameter property="hibernate.mapping"
*/
private String hibernateMapping;
/**
* Target of execution:
* <ul>
* <li><strong>NONE</strong> only export schema to SQL-script (forces excecution, signals skip)</li>
* <li><strong>EXPORT</strong> create database (<strong>DEFAULT!</strong>). forces excecution, signals skip)</li>
* <li><strong>SCRIPT</strong> export schema to SQL-script and print it to STDOUT</li>
* <li><strong>BOTH</strong></li>
* </ul>
*
* A databaseconnection is only needed for EXPORT and BOTH, but a
* Hibernate-Dialect must always be choosen.
*
* @parameter property="hibernate.export.target" default-value="EXPORT"
*/
private String target;
/**
* Type of execution.
* <ul>
* <li><strong>NONE</strong> do nothing - just validate the configuration</li>
* <li><strong>CREATE</strong> create database-schema</li>
* <li><strong>DROP</strong> drop database-schema</li>
* <li><strong>BOTH</strong> (<strong>DEFAULT!</strong>)</li>
* </ul>
*
* If NONE is choosen, no databaseconnection is needed.
*
* @parameter property="hibernate.export.type" default-value="BOTH"
*/
private String type;
/**
* Output file.
*
* @parameter property="hibernate.export.schema.filename" default-value="${project.build.directory}/schema.sql"
*/
private String outputFile;
/**
* Delimiter in output-file.
*
* @parameter property="hibernate.export.schema.delimiter" default-value=";"
*/
private String delimiter;
/**
* Format output-file.
*
* @parameter property="hibernate.export.schema.format" default-value="true"
*/
private boolean format;
@Override
public void execute()
throws
MojoFailureException,
MojoExecutionException
{
if (skip)
{
getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
return;
}
File dir = new File(outputDirectory);
if (!dir.exists())
throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
Map<String,String> md5s;
boolean modified = false;
File saved = new File(buildDirectory + File.separator + MD5S);
if (saved.exists())
{
try
{
FileInputStream fis = new FileInputStream(saved);
ObjectInputStream ois = new ObjectInputStream(fis);
md5s = (HashMap<String,String>)ois.readObject();
ois.close();
}
catch (Exception e)
{
md5s = new HashMap<String,String>();
getLog().warn("Cannot read timestamps from saved: " + e);
}
}
else
{
md5s = new HashMap<String,String>();
try
{
saved.createNewFile();
}
catch (IOException e)
{
getLog().warn("Cannot create saved for timestamps: " + e);
}
}
ClassLoader classLoader = null;
try
{
getLog().debug("Creating ClassLoader for project-dependencies...");
List<String> classpathFiles = project.getCompileClasspathElements();
if (scanTestClasses)
classpathFiles.addAll(project.getTestClasspathElements());
URL[] urls = new URL[classpathFiles.size()];
for (int i = 0; i < classpathFiles.size(); ++i)
{
getLog().debug("Dependency: " + classpathFiles.get(i));
urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
}
classLoader = new URLClassLoader(urls, getClass().getClassLoader());
}
catch (Exception e)
{
getLog().error("Error while creating ClassLoader!", e);
throw new MojoExecutionException(e.getMessage());
}
Set<Class<?>> classes =
new TreeSet<Class<?>>(
new Comparator<Class<?>>() {
@Override
public int compare(Class<?> a, Class<?> b)
{
return a.getName().compareTo(b.getName());
}
}
);
try
{
AnnotationDB db = new AnnotationDB();
getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
URL dirUrl = dir.toURI().toURL();
db.scanArchives(dirUrl);
if (scanTestClasses)
{
dir = new File(testOutputDirectory);
if (!dir.exists())
throw new MojoExecutionException("Cannot scan for annotated test-classes in " + testOutputDirectory + ": directory does not exist!");
getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
dirUrl = dir.toURI().toURL();
db.scanArchives(dirUrl);
}
Set<String> classNames = new HashSet<String>();
if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
for (String name : classNames)
{
Class<?> annotatedClass = classLoader.loadClass(name);
classes.add(annotatedClass);
+ String resourceName = annotatedClass.getName();
+ resourceName = resourceName.substring(resourceName.lastIndexOf(".") + 1, resourceName.length()) + ".class";
InputStream is =
annotatedClass
- .getResourceAsStream(annotatedClass.getSimpleName() + ".class");
+ .getResourceAsStream(resourceName);
byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
int i;
while((i = is.read(buffer)) > -1)
digest.update(buffer, 0, i);
is.close();
byte[] bytes = digest.digest();
BigInteger bi = new BigInteger(1, bytes);
String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
if (!newMd5.equals(oldMd5))
{
getLog().debug("Found new or modified annotated class: " + name);
modified = true;
md5s.put(name, newMd5);
}
else
{
getLog().debug(oldMd5 + " -> class unchanged: " + name);
}
}
}
catch (ClassNotFoundException e)
{
getLog().error("Error while adding annotated classes!", e);
throw new MojoExecutionException(e.getMessage());
}
catch (Exception e)
{
getLog().error("Error while scanning!", e);
throw new MojoFailureException(e.getMessage());
}
if (classes.isEmpty())
{
if (hibernateMapping == null || hibernateMapping.isEmpty())
throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
}
else
{
getLog().debug("Detected classes with mapping-annotations:");
for (Class<?> annotatedClass : classes)
getLog().debug(" " + annotatedClass.getName());
}
Properties properties = new Properties();
/** Try to read configuration from properties-file */
try
{
File file = new File(hibernateProperties);
if (file.exists())
{
getLog().info("Reading properties from file " + hibernateProperties + "...");
properties.load(new FileInputStream(file));
}
else
getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
}
catch (IOException e)
{
getLog().error("Error while reading properties!", e);
throw new MojoExecutionException(e.getMessage());
}
/** Overwrite values from propertie-file or set, if given */
if (driverClassName != null)
{
if (properties.containsKey(DRIVER_CLASS))
getLog().debug(
"Overwriting property " +
DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
" with the value " + driverClassName
);
else
getLog().debug("Using the value " + driverClassName);
properties.setProperty(DRIVER_CLASS, driverClassName);
}
if (url != null)
{
if (properties.containsKey(URL))
getLog().debug(
"Overwriting property " +
URL + "=" + properties.getProperty(URL) +
" with the value " + url
);
else
getLog().debug("Using the value " + url);
properties.setProperty(URL, url);
}
if (username != null)
{
if (properties.containsKey(USERNAME))
getLog().debug(
"Overwriting property " +
USERNAME + "=" + properties.getProperty(USERNAME) +
" with the value " + username
);
else
getLog().debug("Using the value " + username);
properties.setProperty(USERNAME, username);
}
if (password != null)
{
if (properties.containsKey(PASSWORD))
getLog().debug(
"Overwriting property " +
PASSWORD + "=" + properties.getProperty(PASSWORD) +
" with the value " + password
);
else
getLog().debug("Using the value " + password);
properties.setProperty(PASSWORD, password);
}
if (hibernateDialect != null)
{
if (properties.containsKey(DIALECT))
getLog().debug(
"Overwriting property " +
DIALECT + "=" + properties.getProperty(DIALECT) +
" with the value " + hibernateDialect
);
else
getLog().debug("Using the value " + hibernateDialect);
properties.setProperty(DIALECT, hibernateDialect);
}
if ( hibernateNamingStrategy != null )
{
if ( properties.contains(NAMING_STRATEGY))
getLog().debug(
"Overwriting property " +
NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
" with the value " + hibernateNamingStrategy
);
else
getLog().debug("Using the value " + hibernateNamingStrategy);
properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
}
/** The generated SQL varies with the dialect! */
if (md5s.containsKey(DIALECT))
{
String dialect = properties.getProperty(DIALECT);
if (md5s.get(DIALECT).equals(dialect))
getLog().debug("SQL-dialect unchanged.");
else
{
getLog().debug("SQL-dialect changed: " + dialect);
modified = true;
md5s.put(DIALECT, dialect);
}
}
else
{
modified = true;
md5s.put(DIALECT, properties.getProperty(DIALECT));
}
if (properties.isEmpty())
{
getLog().error("No properties set!");
throw new MojoFailureException("Hibernate-Configuration is missing!");
}
Configuration config = new Configuration();
config.setProperties(properties);
if ( properties.containsKey(NAMING_STRATEGY))
{
String namingStrategy = properties.getProperty(NAMING_STRATEGY);
getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
try
{
@SuppressWarnings("unchecked")
Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
config.setNamingStrategy(namingStrategyClass.newInstance());
}
catch (Exception e)
{
getLog().error("Error setting NamingStrategy", e);
throw new MojoExecutionException(e.getMessage());
}
}
getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
for (Class<?> annotatedClass : classes)
{
getLog().debug("Class " + annotatedClass);
config.addAnnotatedClass(annotatedClass);
}
if (hibernateMapping != null)
{
try
{
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
for (String filename : hibernateMapping.split("[\\s,]+"))
{
// First try the filename as absolute/relative path
File file = new File(filename);
if (!file.exists())
{
// If the file was not found, search for it in the resource-directories
for (Resource resource : project.getResources())
{
file = new File(resource.getDirectory() + File.separator + filename);
if (file.exists())
break;
}
}
if (file != null && file.exists())
{
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
int i;
while((i = is.read(buffer)) > -1)
digest.update(buffer, 0, i);
is.close();
byte[] bytes = digest.digest();
BigInteger bi = new BigInteger(1, bytes);
String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
if (!newMd5.equals(oldMd5))
{
getLog().debug("Found new or modified mapping-file: " + filename);
modified = true;
md5s.put(filename, newMd5);
}
else
{
getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
}
getLog().debug("Adding mappings from XML-configurationfile: " + file);
config.addFile(file);
}
else
throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
}
}
catch (NoSuchAlgorithmException e)
{
throw new MojoFailureException("Cannot calculate MD5-summs!", e);
}
catch (FileNotFoundException e)
{
throw new MojoFailureException("Cannot calculate MD5-summs!", e);
}
catch (IOException e)
{
throw new MojoFailureException("Cannot calculate MD5-summs!", e);
}
}
Target target = null;
try
{
target = Target.valueOf(this.target.toUpperCase());
}
catch (IllegalArgumentException e)
{
getLog().error("Invalid value for configuration-option \"target\": " + this.target);
getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
}
Type type = null;
try
{
type = Type.valueOf(this.type.toUpperCase());
}
catch (IllegalArgumentException e)
{
getLog().error("Invalid value for configuration-option \"type\": " + this.type);
getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
}
if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
{
project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
}
if (
!modified
&& !target.equals(Target.SCRIPT)
&& !target.equals(Target.NONE)
&& !force
)
{
getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
getLog().info("Skipping schema generation!");
project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
return;
}
getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
for (Entry<Object,Object> entry : properties.entrySet())
getLog().info(" " + entry.getKey() + " = " + entry.getValue());
Connection connection = null;
try
{
/**
* The connection must be established outside of hibernate, because
* hibernate does not use the context-classloader of the current
* thread and, hence, would not be able to resolve the driver-class!
*/
getLog().debug("Target: " + target + ", Type: " + type);
switch (target)
{
case EXPORT:
case BOTH:
switch (type)
{
case CREATE:
case DROP:
case BOTH:
Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
getLog().debug("Registering JDBC-driver " + driverClass.getName());
DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
getLog().debug(
"Opening JDBC-connection to "
+ properties.getProperty(URL)
+ " as "
+ properties.getProperty(USERNAME)
+ " with password "
+ properties.getProperty(PASSWORD)
);
connection = DriverManager.getConnection(
properties.getProperty(URL),
properties.getProperty(USERNAME),
properties.getProperty(PASSWORD)
);
}
}
}
catch (ClassNotFoundException e)
{
getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
throw new MojoExecutionException(e.getMessage());
}
catch (Exception e)
{
getLog().error("Cannot establish connection to database!");
Enumeration<Driver> drivers = DriverManager.getDrivers();
if (!drivers.hasMoreElements())
getLog().error("No drivers registered!");
while (drivers.hasMoreElements())
getLog().debug("Driver: " + drivers.nextElement());
throw new MojoExecutionException(e.getMessage());
}
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
MavenLogAppender.startPluginLog(this);
try
{
/**
* Change class-loader of current thread, so that hibernate can
* see all dependencies!
*/
Thread.currentThread().setContextClassLoader(classLoader);
SchemaExport export = new SchemaExport(config, connection);
export.setOutputFile(outputFile);
export.setDelimiter(delimiter);
export.setFormat(format);
export.execute(target, type);
for (Object exception : export.getExceptions())
getLog().debug(exception.toString());
}
finally
{
/** Stop Log-Capturing */
MavenLogAppender.endPluginLog(this);
/** Restore the old class-loader (TODO: is this really necessary?) */
Thread.currentThread().setContextClassLoader(contextClassLoader);
/** Close the connection */
try
{
if (connection != null)
connection.close();
}
catch (SQLException e)
{
getLog().error("Error while closing connection: " + e.getMessage());
}
}
/** Write md5-sums for annotated classes to file */
try
{
FileOutputStream fos = new FileOutputStream(saved);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(md5s);
oos.close();
fos.close();
}
catch (Exception e)
{
getLog().error("Cannot write md5-sums to file: " + e);
}
}
/**
* Needed, because DriverManager won't pick up drivers, that were not
* loaded by the system-classloader!
* See:
* http://stackoverflow.com/questions/288828/how-to-use-a-jdbc-driver-fromodifiedm-an-arbitrary-location
*/
static final class DriverProxy implements Driver
{
private final Driver target;
DriverProxy(Driver target)
{
if (target == null)
throw new NullPointerException();
this.target = target;
}
public java.sql.Driver getTarget()
{
return target;
}
@Override
public boolean acceptsURL(String url) throws SQLException
{
return target.acceptsURL(url);
}
@Override
public java.sql.Connection connect(
String url,
java.util.Properties info
)
throws
SQLException
{
return target.connect(url, info);
}
@Override
public int getMajorVersion()
{
return target.getMajorVersion();
}
@Override
public int getMinorVersion()
{
return target.getMinorVersion();
}
@Override
public DriverPropertyInfo[] getPropertyInfo(
String url,
Properties info
)
throws
SQLException
{
return target.getPropertyInfo(url, info);
}
@Override
public boolean jdbcCompliant()
{
return target.jdbcCompliant();
}
/**
* This Method cannot be annotated with @Override, becaus the plugin
* will not compile then under Java 1.6!
*/
public Logger getParentLogger() throws SQLFeatureNotSupportedException
{
throw new SQLFeatureNotSupportedException("Not supported, for backward-compatibility with Java 1.6");
}
@Override
public String toString()
{
return "Proxy: " + target;
}
@Override
public int hashCode()
{
return target.hashCode();
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof DriverProxy))
return false;
DriverProxy other = (DriverProxy) obj;
return this.target.equals(other.target);
}
}
}
| false | true | public void execute()
throws
MojoFailureException,
MojoExecutionException
{
if (skip)
{
getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
return;
}
File dir = new File(outputDirectory);
if (!dir.exists())
throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
Map<String,String> md5s;
boolean modified = false;
File saved = new File(buildDirectory + File.separator + MD5S);
if (saved.exists())
{
try
{
FileInputStream fis = new FileInputStream(saved);
ObjectInputStream ois = new ObjectInputStream(fis);
md5s = (HashMap<String,String>)ois.readObject();
ois.close();
}
catch (Exception e)
{
md5s = new HashMap<String,String>();
getLog().warn("Cannot read timestamps from saved: " + e);
}
}
else
{
md5s = new HashMap<String,String>();
try
{
saved.createNewFile();
}
catch (IOException e)
{
getLog().warn("Cannot create saved for timestamps: " + e);
}
}
ClassLoader classLoader = null;
try
{
getLog().debug("Creating ClassLoader for project-dependencies...");
List<String> classpathFiles = project.getCompileClasspathElements();
if (scanTestClasses)
classpathFiles.addAll(project.getTestClasspathElements());
URL[] urls = new URL[classpathFiles.size()];
for (int i = 0; i < classpathFiles.size(); ++i)
{
getLog().debug("Dependency: " + classpathFiles.get(i));
urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
}
classLoader = new URLClassLoader(urls, getClass().getClassLoader());
}
catch (Exception e)
{
getLog().error("Error while creating ClassLoader!", e);
throw new MojoExecutionException(e.getMessage());
}
Set<Class<?>> classes =
new TreeSet<Class<?>>(
new Comparator<Class<?>>() {
@Override
public int compare(Class<?> a, Class<?> b)
{
return a.getName().compareTo(b.getName());
}
}
);
try
{
AnnotationDB db = new AnnotationDB();
getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
URL dirUrl = dir.toURI().toURL();
db.scanArchives(dirUrl);
if (scanTestClasses)
{
dir = new File(testOutputDirectory);
if (!dir.exists())
throw new MojoExecutionException("Cannot scan for annotated test-classes in " + testOutputDirectory + ": directory does not exist!");
getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
dirUrl = dir.toURI().toURL();
db.scanArchives(dirUrl);
}
Set<String> classNames = new HashSet<String>();
if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
for (String name : classNames)
{
Class<?> annotatedClass = classLoader.loadClass(name);
classes.add(annotatedClass);
InputStream is =
annotatedClass
.getResourceAsStream(annotatedClass.getSimpleName() + ".class");
byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
int i;
while((i = is.read(buffer)) > -1)
digest.update(buffer, 0, i);
is.close();
byte[] bytes = digest.digest();
BigInteger bi = new BigInteger(1, bytes);
String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
if (!newMd5.equals(oldMd5))
{
getLog().debug("Found new or modified annotated class: " + name);
modified = true;
md5s.put(name, newMd5);
}
else
{
getLog().debug(oldMd5 + " -> class unchanged: " + name);
}
}
}
catch (ClassNotFoundException e)
{
getLog().error("Error while adding annotated classes!", e);
throw new MojoExecutionException(e.getMessage());
}
catch (Exception e)
{
getLog().error("Error while scanning!", e);
throw new MojoFailureException(e.getMessage());
}
if (classes.isEmpty())
{
if (hibernateMapping == null || hibernateMapping.isEmpty())
throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
}
else
{
getLog().debug("Detected classes with mapping-annotations:");
for (Class<?> annotatedClass : classes)
getLog().debug(" " + annotatedClass.getName());
}
Properties properties = new Properties();
/** Try to read configuration from properties-file */
try
{
File file = new File(hibernateProperties);
if (file.exists())
{
getLog().info("Reading properties from file " + hibernateProperties + "...");
properties.load(new FileInputStream(file));
}
else
getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
}
catch (IOException e)
{
getLog().error("Error while reading properties!", e);
throw new MojoExecutionException(e.getMessage());
}
/** Overwrite values from propertie-file or set, if given */
if (driverClassName != null)
{
if (properties.containsKey(DRIVER_CLASS))
getLog().debug(
"Overwriting property " +
DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
" with the value " + driverClassName
);
else
getLog().debug("Using the value " + driverClassName);
properties.setProperty(DRIVER_CLASS, driverClassName);
}
if (url != null)
{
if (properties.containsKey(URL))
getLog().debug(
"Overwriting property " +
URL + "=" + properties.getProperty(URL) +
" with the value " + url
);
else
getLog().debug("Using the value " + url);
properties.setProperty(URL, url);
}
if (username != null)
{
if (properties.containsKey(USERNAME))
getLog().debug(
"Overwriting property " +
USERNAME + "=" + properties.getProperty(USERNAME) +
" with the value " + username
);
else
getLog().debug("Using the value " + username);
properties.setProperty(USERNAME, username);
}
if (password != null)
{
if (properties.containsKey(PASSWORD))
getLog().debug(
"Overwriting property " +
PASSWORD + "=" + properties.getProperty(PASSWORD) +
" with the value " + password
);
else
getLog().debug("Using the value " + password);
properties.setProperty(PASSWORD, password);
}
if (hibernateDialect != null)
{
if (properties.containsKey(DIALECT))
getLog().debug(
"Overwriting property " +
DIALECT + "=" + properties.getProperty(DIALECT) +
" with the value " + hibernateDialect
);
else
getLog().debug("Using the value " + hibernateDialect);
properties.setProperty(DIALECT, hibernateDialect);
}
if ( hibernateNamingStrategy != null )
{
if ( properties.contains(NAMING_STRATEGY))
getLog().debug(
"Overwriting property " +
NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
" with the value " + hibernateNamingStrategy
);
else
getLog().debug("Using the value " + hibernateNamingStrategy);
properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
}
/** The generated SQL varies with the dialect! */
if (md5s.containsKey(DIALECT))
{
String dialect = properties.getProperty(DIALECT);
if (md5s.get(DIALECT).equals(dialect))
getLog().debug("SQL-dialect unchanged.");
else
{
getLog().debug("SQL-dialect changed: " + dialect);
modified = true;
md5s.put(DIALECT, dialect);
}
}
else
{
modified = true;
md5s.put(DIALECT, properties.getProperty(DIALECT));
}
if (properties.isEmpty())
{
getLog().error("No properties set!");
throw new MojoFailureException("Hibernate-Configuration is missing!");
}
Configuration config = new Configuration();
config.setProperties(properties);
if ( properties.containsKey(NAMING_STRATEGY))
{
String namingStrategy = properties.getProperty(NAMING_STRATEGY);
getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
try
{
@SuppressWarnings("unchecked")
Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
config.setNamingStrategy(namingStrategyClass.newInstance());
}
catch (Exception e)
{
getLog().error("Error setting NamingStrategy", e);
throw new MojoExecutionException(e.getMessage());
}
}
getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
for (Class<?> annotatedClass : classes)
{
getLog().debug("Class " + annotatedClass);
config.addAnnotatedClass(annotatedClass);
}
if (hibernateMapping != null)
{
try
{
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
for (String filename : hibernateMapping.split("[\\s,]+"))
{
// First try the filename as absolute/relative path
File file = new File(filename);
if (!file.exists())
{
// If the file was not found, search for it in the resource-directories
for (Resource resource : project.getResources())
{
file = new File(resource.getDirectory() + File.separator + filename);
if (file.exists())
break;
}
}
if (file != null && file.exists())
{
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
int i;
while((i = is.read(buffer)) > -1)
digest.update(buffer, 0, i);
is.close();
byte[] bytes = digest.digest();
BigInteger bi = new BigInteger(1, bytes);
String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
if (!newMd5.equals(oldMd5))
{
getLog().debug("Found new or modified mapping-file: " + filename);
modified = true;
md5s.put(filename, newMd5);
}
else
{
getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
}
getLog().debug("Adding mappings from XML-configurationfile: " + file);
config.addFile(file);
}
else
throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
}
}
catch (NoSuchAlgorithmException e)
{
throw new MojoFailureException("Cannot calculate MD5-summs!", e);
}
catch (FileNotFoundException e)
{
throw new MojoFailureException("Cannot calculate MD5-summs!", e);
}
catch (IOException e)
{
throw new MojoFailureException("Cannot calculate MD5-summs!", e);
}
}
Target target = null;
try
{
target = Target.valueOf(this.target.toUpperCase());
}
catch (IllegalArgumentException e)
{
getLog().error("Invalid value for configuration-option \"target\": " + this.target);
getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
}
Type type = null;
try
{
type = Type.valueOf(this.type.toUpperCase());
}
catch (IllegalArgumentException e)
{
getLog().error("Invalid value for configuration-option \"type\": " + this.type);
getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
}
if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
{
project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
}
if (
!modified
&& !target.equals(Target.SCRIPT)
&& !target.equals(Target.NONE)
&& !force
)
{
getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
getLog().info("Skipping schema generation!");
project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
return;
}
getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
for (Entry<Object,Object> entry : properties.entrySet())
getLog().info(" " + entry.getKey() + " = " + entry.getValue());
Connection connection = null;
try
{
/**
* The connection must be established outside of hibernate, because
* hibernate does not use the context-classloader of the current
* thread and, hence, would not be able to resolve the driver-class!
*/
getLog().debug("Target: " + target + ", Type: " + type);
switch (target)
{
case EXPORT:
case BOTH:
switch (type)
{
case CREATE:
case DROP:
case BOTH:
Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
getLog().debug("Registering JDBC-driver " + driverClass.getName());
DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
getLog().debug(
"Opening JDBC-connection to "
+ properties.getProperty(URL)
+ " as "
+ properties.getProperty(USERNAME)
+ " with password "
+ properties.getProperty(PASSWORD)
);
connection = DriverManager.getConnection(
properties.getProperty(URL),
properties.getProperty(USERNAME),
properties.getProperty(PASSWORD)
);
}
}
}
catch (ClassNotFoundException e)
{
getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
throw new MojoExecutionException(e.getMessage());
}
catch (Exception e)
{
getLog().error("Cannot establish connection to database!");
Enumeration<Driver> drivers = DriverManager.getDrivers();
if (!drivers.hasMoreElements())
getLog().error("No drivers registered!");
while (drivers.hasMoreElements())
getLog().debug("Driver: " + drivers.nextElement());
throw new MojoExecutionException(e.getMessage());
}
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
MavenLogAppender.startPluginLog(this);
try
{
/**
* Change class-loader of current thread, so that hibernate can
* see all dependencies!
*/
Thread.currentThread().setContextClassLoader(classLoader);
SchemaExport export = new SchemaExport(config, connection);
export.setOutputFile(outputFile);
export.setDelimiter(delimiter);
export.setFormat(format);
export.execute(target, type);
for (Object exception : export.getExceptions())
getLog().debug(exception.toString());
}
finally
{
/** Stop Log-Capturing */
MavenLogAppender.endPluginLog(this);
/** Restore the old class-loader (TODO: is this really necessary?) */
Thread.currentThread().setContextClassLoader(contextClassLoader);
/** Close the connection */
try
{
if (connection != null)
connection.close();
}
catch (SQLException e)
{
getLog().error("Error while closing connection: " + e.getMessage());
}
}
/** Write md5-sums for annotated classes to file */
try
{
FileOutputStream fos = new FileOutputStream(saved);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(md5s);
oos.close();
fos.close();
}
catch (Exception e)
{
getLog().error("Cannot write md5-sums to file: " + e);
}
}
| public void execute()
throws
MojoFailureException,
MojoExecutionException
{
if (skip)
{
getLog().info("Exectuion of hibernate4-maven-plugin:export was skipped!");
project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
return;
}
File dir = new File(outputDirectory);
if (!dir.exists())
throw new MojoExecutionException("Cannot scan for annotated classes in " + outputDirectory + ": directory does not exist!");
Map<String,String> md5s;
boolean modified = false;
File saved = new File(buildDirectory + File.separator + MD5S);
if (saved.exists())
{
try
{
FileInputStream fis = new FileInputStream(saved);
ObjectInputStream ois = new ObjectInputStream(fis);
md5s = (HashMap<String,String>)ois.readObject();
ois.close();
}
catch (Exception e)
{
md5s = new HashMap<String,String>();
getLog().warn("Cannot read timestamps from saved: " + e);
}
}
else
{
md5s = new HashMap<String,String>();
try
{
saved.createNewFile();
}
catch (IOException e)
{
getLog().warn("Cannot create saved for timestamps: " + e);
}
}
ClassLoader classLoader = null;
try
{
getLog().debug("Creating ClassLoader for project-dependencies...");
List<String> classpathFiles = project.getCompileClasspathElements();
if (scanTestClasses)
classpathFiles.addAll(project.getTestClasspathElements());
URL[] urls = new URL[classpathFiles.size()];
for (int i = 0; i < classpathFiles.size(); ++i)
{
getLog().debug("Dependency: " + classpathFiles.get(i));
urls[i] = new File(classpathFiles.get(i)).toURI().toURL();
}
classLoader = new URLClassLoader(urls, getClass().getClassLoader());
}
catch (Exception e)
{
getLog().error("Error while creating ClassLoader!", e);
throw new MojoExecutionException(e.getMessage());
}
Set<Class<?>> classes =
new TreeSet<Class<?>>(
new Comparator<Class<?>>() {
@Override
public int compare(Class<?> a, Class<?> b)
{
return a.getName().compareTo(b.getName());
}
}
);
try
{
AnnotationDB db = new AnnotationDB();
getLog().info("Scanning directory " + outputDirectory + " for annotated classes...");
URL dirUrl = dir.toURI().toURL();
db.scanArchives(dirUrl);
if (scanTestClasses)
{
dir = new File(testOutputDirectory);
if (!dir.exists())
throw new MojoExecutionException("Cannot scan for annotated test-classes in " + testOutputDirectory + ": directory does not exist!");
getLog().info("Scanning directory " + testOutputDirectory + " for annotated classes...");
dirUrl = dir.toURI().toURL();
db.scanArchives(dirUrl);
}
Set<String> classNames = new HashSet<String>();
if (db.getAnnotationIndex().containsKey(Entity.class.getName()))
classNames.addAll(db.getAnnotationIndex().get(Entity.class.getName()));
if (db.getAnnotationIndex().containsKey(MappedSuperclass.class.getName()))
classNames.addAll(db.getAnnotationIndex().get(MappedSuperclass.class.getName()));
if (db.getAnnotationIndex().containsKey(Embeddable.class.getName()))
classNames.addAll(db.getAnnotationIndex().get(Embeddable.class.getName()));
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
for (String name : classNames)
{
Class<?> annotatedClass = classLoader.loadClass(name);
classes.add(annotatedClass);
String resourceName = annotatedClass.getName();
resourceName = resourceName.substring(resourceName.lastIndexOf(".") + 1, resourceName.length()) + ".class";
InputStream is =
annotatedClass
.getResourceAsStream(resourceName);
byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
int i;
while((i = is.read(buffer)) > -1)
digest.update(buffer, 0, i);
is.close();
byte[] bytes = digest.digest();
BigInteger bi = new BigInteger(1, bytes);
String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
String oldMd5 = !md5s.containsKey(name) ? "" : md5s.get(name);
if (!newMd5.equals(oldMd5))
{
getLog().debug("Found new or modified annotated class: " + name);
modified = true;
md5s.put(name, newMd5);
}
else
{
getLog().debug(oldMd5 + " -> class unchanged: " + name);
}
}
}
catch (ClassNotFoundException e)
{
getLog().error("Error while adding annotated classes!", e);
throw new MojoExecutionException(e.getMessage());
}
catch (Exception e)
{
getLog().error("Error while scanning!", e);
throw new MojoFailureException(e.getMessage());
}
if (classes.isEmpty())
{
if (hibernateMapping == null || hibernateMapping.isEmpty())
throw new MojoFailureException("No annotated classes found in directory " + outputDirectory);
}
else
{
getLog().debug("Detected classes with mapping-annotations:");
for (Class<?> annotatedClass : classes)
getLog().debug(" " + annotatedClass.getName());
}
Properties properties = new Properties();
/** Try to read configuration from properties-file */
try
{
File file = new File(hibernateProperties);
if (file.exists())
{
getLog().info("Reading properties from file " + hibernateProperties + "...");
properties.load(new FileInputStream(file));
}
else
getLog().info("No hibernate-properties-file found! (Checked path: " + hibernateProperties + ")");
}
catch (IOException e)
{
getLog().error("Error while reading properties!", e);
throw new MojoExecutionException(e.getMessage());
}
/** Overwrite values from propertie-file or set, if given */
if (driverClassName != null)
{
if (properties.containsKey(DRIVER_CLASS))
getLog().debug(
"Overwriting property " +
DRIVER_CLASS + "=" + properties.getProperty(DRIVER_CLASS) +
" with the value " + driverClassName
);
else
getLog().debug("Using the value " + driverClassName);
properties.setProperty(DRIVER_CLASS, driverClassName);
}
if (url != null)
{
if (properties.containsKey(URL))
getLog().debug(
"Overwriting property " +
URL + "=" + properties.getProperty(URL) +
" with the value " + url
);
else
getLog().debug("Using the value " + url);
properties.setProperty(URL, url);
}
if (username != null)
{
if (properties.containsKey(USERNAME))
getLog().debug(
"Overwriting property " +
USERNAME + "=" + properties.getProperty(USERNAME) +
" with the value " + username
);
else
getLog().debug("Using the value " + username);
properties.setProperty(USERNAME, username);
}
if (password != null)
{
if (properties.containsKey(PASSWORD))
getLog().debug(
"Overwriting property " +
PASSWORD + "=" + properties.getProperty(PASSWORD) +
" with the value " + password
);
else
getLog().debug("Using the value " + password);
properties.setProperty(PASSWORD, password);
}
if (hibernateDialect != null)
{
if (properties.containsKey(DIALECT))
getLog().debug(
"Overwriting property " +
DIALECT + "=" + properties.getProperty(DIALECT) +
" with the value " + hibernateDialect
);
else
getLog().debug("Using the value " + hibernateDialect);
properties.setProperty(DIALECT, hibernateDialect);
}
if ( hibernateNamingStrategy != null )
{
if ( properties.contains(NAMING_STRATEGY))
getLog().debug(
"Overwriting property " +
NAMING_STRATEGY + "=" + properties.getProperty(NAMING_STRATEGY) +
" with the value " + hibernateNamingStrategy
);
else
getLog().debug("Using the value " + hibernateNamingStrategy);
properties.setProperty(NAMING_STRATEGY, hibernateNamingStrategy);
}
/** The generated SQL varies with the dialect! */
if (md5s.containsKey(DIALECT))
{
String dialect = properties.getProperty(DIALECT);
if (md5s.get(DIALECT).equals(dialect))
getLog().debug("SQL-dialect unchanged.");
else
{
getLog().debug("SQL-dialect changed: " + dialect);
modified = true;
md5s.put(DIALECT, dialect);
}
}
else
{
modified = true;
md5s.put(DIALECT, properties.getProperty(DIALECT));
}
if (properties.isEmpty())
{
getLog().error("No properties set!");
throw new MojoFailureException("Hibernate-Configuration is missing!");
}
Configuration config = new Configuration();
config.setProperties(properties);
if ( properties.containsKey(NAMING_STRATEGY))
{
String namingStrategy = properties.getProperty(NAMING_STRATEGY);
getLog().debug("Explicitly set NamingStrategy: " + namingStrategy);
try
{
@SuppressWarnings("unchecked")
Class<NamingStrategy> namingStrategyClass = (Class<NamingStrategy>) Class.forName(namingStrategy);
config.setNamingStrategy(namingStrategyClass.newInstance());
}
catch (Exception e)
{
getLog().error("Error setting NamingStrategy", e);
throw new MojoExecutionException(e.getMessage());
}
}
getLog().debug("Adding annotated classes to hibernate-mapping-configuration...");
for (Class<?> annotatedClass : classes)
{
getLog().debug("Class " + annotatedClass);
config.addAnnotatedClass(annotatedClass);
}
if (hibernateMapping != null)
{
try
{
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
for (String filename : hibernateMapping.split("[\\s,]+"))
{
// First try the filename as absolute/relative path
File file = new File(filename);
if (!file.exists())
{
// If the file was not found, search for it in the resource-directories
for (Resource resource : project.getResources())
{
file = new File(resource.getDirectory() + File.separator + filename);
if (file.exists())
break;
}
}
if (file != null && file.exists())
{
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[1024*4]; // copy data in 4MB-chunks
int i;
while((i = is.read(buffer)) > -1)
digest.update(buffer, 0, i);
is.close();
byte[] bytes = digest.digest();
BigInteger bi = new BigInteger(1, bytes);
String newMd5 = String.format("%0" + (bytes.length << 1) + "x", bi);
String oldMd5 = !md5s.containsKey(filename) ? "" : md5s.get(filename);
if (!newMd5.equals(oldMd5))
{
getLog().debug("Found new or modified mapping-file: " + filename);
modified = true;
md5s.put(filename, newMd5);
}
else
{
getLog().debug(oldMd5 + " -> mapping-file unchanged: " + filename);
}
getLog().debug("Adding mappings from XML-configurationfile: " + file);
config.addFile(file);
}
else
throw new MojoFailureException("File " + filename + " could not be found in any of the configured resource-directories!");
}
}
catch (NoSuchAlgorithmException e)
{
throw new MojoFailureException("Cannot calculate MD5-summs!", e);
}
catch (FileNotFoundException e)
{
throw new MojoFailureException("Cannot calculate MD5-summs!", e);
}
catch (IOException e)
{
throw new MojoFailureException("Cannot calculate MD5-summs!", e);
}
}
Target target = null;
try
{
target = Target.valueOf(this.target.toUpperCase());
}
catch (IllegalArgumentException e)
{
getLog().error("Invalid value for configuration-option \"target\": " + this.target);
getLog().error("Valid values are: NONE, SCRIPT, EXPORT, BOTH");
throw new MojoExecutionException("Invalid value for configuration-option \"target\"");
}
Type type = null;
try
{
type = Type.valueOf(this.type.toUpperCase());
}
catch (IllegalArgumentException e)
{
getLog().error("Invalid value for configuration-option \"type\": " + this.type);
getLog().error("Valid values are: NONE, CREATE, DROP, BOTH");
throw new MojoExecutionException("Invalid value for configuration-option \"type\"");
}
if (target.equals(Target.SCRIPT) || target.equals(Target.NONE))
{
project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
}
if (
!modified
&& !target.equals(Target.SCRIPT)
&& !target.equals(Target.NONE)
&& !force
)
{
getLog().info("No modified annotated classes or mapping-files found and dialect unchanged.");
getLog().info("Skipping schema generation!");
project.getProperties().setProperty(EXPORT_SKIPPED_PROPERTY, "true");
return;
}
getLog().info("Gathered hibernate-configuration (turn on debugging for details):");
for (Entry<Object,Object> entry : properties.entrySet())
getLog().info(" " + entry.getKey() + " = " + entry.getValue());
Connection connection = null;
try
{
/**
* The connection must be established outside of hibernate, because
* hibernate does not use the context-classloader of the current
* thread and, hence, would not be able to resolve the driver-class!
*/
getLog().debug("Target: " + target + ", Type: " + type);
switch (target)
{
case EXPORT:
case BOTH:
switch (type)
{
case CREATE:
case DROP:
case BOTH:
Class driverClass = classLoader.loadClass(properties.getProperty(DRIVER_CLASS));
getLog().debug("Registering JDBC-driver " + driverClass.getName());
DriverManager.registerDriver(new DriverProxy((Driver)driverClass.newInstance()));
getLog().debug(
"Opening JDBC-connection to "
+ properties.getProperty(URL)
+ " as "
+ properties.getProperty(USERNAME)
+ " with password "
+ properties.getProperty(PASSWORD)
);
connection = DriverManager.getConnection(
properties.getProperty(URL),
properties.getProperty(USERNAME),
properties.getProperty(PASSWORD)
);
}
}
}
catch (ClassNotFoundException e)
{
getLog().error("Dependency for driver-class " + properties.getProperty(DRIVER_CLASS) + " is missing!");
throw new MojoExecutionException(e.getMessage());
}
catch (Exception e)
{
getLog().error("Cannot establish connection to database!");
Enumeration<Driver> drivers = DriverManager.getDrivers();
if (!drivers.hasMoreElements())
getLog().error("No drivers registered!");
while (drivers.hasMoreElements())
getLog().debug("Driver: " + drivers.nextElement());
throw new MojoExecutionException(e.getMessage());
}
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
MavenLogAppender.startPluginLog(this);
try
{
/**
* Change class-loader of current thread, so that hibernate can
* see all dependencies!
*/
Thread.currentThread().setContextClassLoader(classLoader);
SchemaExport export = new SchemaExport(config, connection);
export.setOutputFile(outputFile);
export.setDelimiter(delimiter);
export.setFormat(format);
export.execute(target, type);
for (Object exception : export.getExceptions())
getLog().debug(exception.toString());
}
finally
{
/** Stop Log-Capturing */
MavenLogAppender.endPluginLog(this);
/** Restore the old class-loader (TODO: is this really necessary?) */
Thread.currentThread().setContextClassLoader(contextClassLoader);
/** Close the connection */
try
{
if (connection != null)
connection.close();
}
catch (SQLException e)
{
getLog().error("Error while closing connection: " + e.getMessage());
}
}
/** Write md5-sums for annotated classes to file */
try
{
FileOutputStream fos = new FileOutputStream(saved);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(md5s);
oos.close();
fos.close();
}
catch (Exception e)
{
getLog().error("Cannot write md5-sums to file: " + e);
}
}
|
diff --git a/app/controllers/Feeds.java b/app/controllers/Feeds.java
index bd83dd4..704bbae 100644
--- a/app/controllers/Feeds.java
+++ b/app/controllers/Feeds.java
@@ -1,101 +1,101 @@
package controllers;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedOutput;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import models.blog.Post;
import play.Play;
import play.mvc.Controller;
import utils.LangProperties;
/**
*
* @author waxzce
*/
@SuppressWarnings("unchecked")
public class Feeds extends Controller {
/**
* Get the blog feed
* @param lang The lang
*/
public static void main(String lang) {
if (lang == null) {
return;
}
Locale locale = null;
String[] s = lang.split("_");
switch (s.length) {
case 0:
break;
case 1:
locale = new Locale(s[0]);
break;
case 2:
locale = new Locale(s[0], s[1].substring(0, 2));
break;
}
SyndFeed feed = new SyndFeedImpl();
LangProperties p = new LangProperties();
try {
p.load(new FileReader(Play.getVirtualFile("conf/feed.properties").getRealFile()));
} catch (IOException ex) {
Logger.getLogger(Feeds.class.getName()).log(Level.SEVERE, null, ex);
}
feed.setAuthor(p.getProperty("feed.author", locale));
feed.setFeedType("rss_2.0");
feed.setCopyright(p.getProperty("feed.copyright", locale));
feed.setDescription(p.getProperty("feed.description", locale));
feed.setLink(request.getBase() + "/" + p.getProperty("feed.link", locale));
feed.setTitle(p.getProperty("feed.title", locale));
feed.setLanguage(locale.toString());
feed.setPublishedDate(new Date());
List<Post> posts = Post.getLatestPostsByLocale(locale, 20, 1);
List<SyndEntry> entries = new ArrayList<SyndEntry>();
SyndEntry item = null;
SyndContent content = null;
for (Post post : posts) {
item = new SyndEntryImpl();
item.setPublishedDate(post.postedAt);
item.setTitle(post.title);
content = new SyndContentImpl();
content.setType("text/html");
content.setValue(post.content);
item.setDescription(content);
- item.setLink(request.getBase() + "/post/" + post.title);
+ item.setLink(request.getBase() +"/blog"+ "/post/" + post.urlId);
entries.add(item);
}
feed.setEntries(entries);
StringWriter writer = new StringWriter();
SyndFeedOutput out = new SyndFeedOutput();
try {
out.output(feed, writer);
} catch (IOException e) {
flash("error", "Erreur d'entré/sortie (StringWriter) lors de la sérialisation du flux : " + e.getMessage());
} catch (FeedException e) {
flash("error", "Erreur lors de la sérialisation du flux : " + e.getMessage());
}
response.contentType = "application/rss+xml";
renderXml(writer.toString());
}
}
| true | true | public static void main(String lang) {
if (lang == null) {
return;
}
Locale locale = null;
String[] s = lang.split("_");
switch (s.length) {
case 0:
break;
case 1:
locale = new Locale(s[0]);
break;
case 2:
locale = new Locale(s[0], s[1].substring(0, 2));
break;
}
SyndFeed feed = new SyndFeedImpl();
LangProperties p = new LangProperties();
try {
p.load(new FileReader(Play.getVirtualFile("conf/feed.properties").getRealFile()));
} catch (IOException ex) {
Logger.getLogger(Feeds.class.getName()).log(Level.SEVERE, null, ex);
}
feed.setAuthor(p.getProperty("feed.author", locale));
feed.setFeedType("rss_2.0");
feed.setCopyright(p.getProperty("feed.copyright", locale));
feed.setDescription(p.getProperty("feed.description", locale));
feed.setLink(request.getBase() + "/" + p.getProperty("feed.link", locale));
feed.setTitle(p.getProperty("feed.title", locale));
feed.setLanguage(locale.toString());
feed.setPublishedDate(new Date());
List<Post> posts = Post.getLatestPostsByLocale(locale, 20, 1);
List<SyndEntry> entries = new ArrayList<SyndEntry>();
SyndEntry item = null;
SyndContent content = null;
for (Post post : posts) {
item = new SyndEntryImpl();
item.setPublishedDate(post.postedAt);
item.setTitle(post.title);
content = new SyndContentImpl();
content.setType("text/html");
content.setValue(post.content);
item.setDescription(content);
item.setLink(request.getBase() + "/post/" + post.title);
entries.add(item);
}
feed.setEntries(entries);
StringWriter writer = new StringWriter();
SyndFeedOutput out = new SyndFeedOutput();
try {
out.output(feed, writer);
} catch (IOException e) {
flash("error", "Erreur d'entré/sortie (StringWriter) lors de la sérialisation du flux : " + e.getMessage());
} catch (FeedException e) {
flash("error", "Erreur lors de la sérialisation du flux : " + e.getMessage());
}
response.contentType = "application/rss+xml";
renderXml(writer.toString());
}
| public static void main(String lang) {
if (lang == null) {
return;
}
Locale locale = null;
String[] s = lang.split("_");
switch (s.length) {
case 0:
break;
case 1:
locale = new Locale(s[0]);
break;
case 2:
locale = new Locale(s[0], s[1].substring(0, 2));
break;
}
SyndFeed feed = new SyndFeedImpl();
LangProperties p = new LangProperties();
try {
p.load(new FileReader(Play.getVirtualFile("conf/feed.properties").getRealFile()));
} catch (IOException ex) {
Logger.getLogger(Feeds.class.getName()).log(Level.SEVERE, null, ex);
}
feed.setAuthor(p.getProperty("feed.author", locale));
feed.setFeedType("rss_2.0");
feed.setCopyright(p.getProperty("feed.copyright", locale));
feed.setDescription(p.getProperty("feed.description", locale));
feed.setLink(request.getBase() + "/" + p.getProperty("feed.link", locale));
feed.setTitle(p.getProperty("feed.title", locale));
feed.setLanguage(locale.toString());
feed.setPublishedDate(new Date());
List<Post> posts = Post.getLatestPostsByLocale(locale, 20, 1);
List<SyndEntry> entries = new ArrayList<SyndEntry>();
SyndEntry item = null;
SyndContent content = null;
for (Post post : posts) {
item = new SyndEntryImpl();
item.setPublishedDate(post.postedAt);
item.setTitle(post.title);
content = new SyndContentImpl();
content.setType("text/html");
content.setValue(post.content);
item.setDescription(content);
item.setLink(request.getBase() +"/blog"+ "/post/" + post.urlId);
entries.add(item);
}
feed.setEntries(entries);
StringWriter writer = new StringWriter();
SyndFeedOutput out = new SyndFeedOutput();
try {
out.output(feed, writer);
} catch (IOException e) {
flash("error", "Erreur d'entré/sortie (StringWriter) lors de la sérialisation du flux : " + e.getMessage());
} catch (FeedException e) {
flash("error", "Erreur lors de la sérialisation du flux : " + e.getMessage());
}
response.contentType = "application/rss+xml";
renderXml(writer.toString());
}
|
diff --git a/src/to/joe/vanish/VanishCommand.java b/src/to/joe/vanish/VanishCommand.java
index b67fafa..77ffbee 100644
--- a/src/to/joe/vanish/VanishCommand.java
+++ b/src/to/joe/vanish/VanishCommand.java
@@ -1,113 +1,113 @@
package to.joe.vanish;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class VanishCommand implements CommandExecutor {
private final VanishPlugin plugin;
public VanishCommand(VanishPlugin plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if ((sender instanceof Player)) {
final Player player = (Player) sender;
if ((args.length == 0)) {
if (VanishPerms.canVanish((Player) sender)) {
this.plugin.getManager().toggleVanish(player);
}
} else if (args[0].equalsIgnoreCase("check") && VanishPerms.canVanish((Player) sender)) {
if (this.plugin.getManager().isVanished(player)) {
player.sendMessage(ChatColor.DARK_AQUA + "You are invisible.");
} else {
player.sendMessage(ChatColor.DARK_AQUA + "You are not invisible.");
}
- } else if (args[0].equalsIgnoreCase("toggle")) {
+ } else if (args[0].equalsIgnoreCase("toggle")||args[0].equalsIgnoreCase("t")) {
if (args.length == 1) {
final StringBuilder toggleList = new StringBuilder();
if (VanishPerms.canToggleSee(player)) {
toggleList.append(this.colorize(VanishPerms.canSeeAll(player)) + "see" + ChatColor.DARK_AQUA);
this.plugin.getManager().resetSeeing(player);
}
if (VanishPerms.canToggleNoPickup(player)) {
this.comma(toggleList, this.colorize(VanishPerms.canNotPickUp(player)) + "nopickup" + ChatColor.DARK_AQUA);
}
if (VanishPerms.canToggleNoFollow(player)) {
this.comma(toggleList, this.colorize(VanishPerms.canNotFollow(player)) + "nofollow" + ChatColor.DARK_AQUA);
}
if (VanishPerms.canToggleDamageIn(player)) {
this.comma(toggleList, this.colorize(VanishPerms.blockIncomingDamage(player)) + "damage-in" + ChatColor.DARK_AQUA);
}
if (VanishPerms.canToggleDamageOut(player)) {
this.comma(toggleList, this.colorize(VanishPerms.blockOutgoingDamage(player)) + "damage-out" + ChatColor.DARK_AQUA);
}
if (toggleList.length() > 0) {
toggleList.insert(0, ChatColor.DARK_AQUA + "You can toggle: ");
} else {
if (VanishPerms.canVanish((Player) sender)) {
toggleList.append(ChatColor.DARK_AQUA + "You cannot toggle anything");
}
}
player.sendMessage(toggleList.toString());
} else {
final StringBuilder message = new StringBuilder();
boolean status = false;;
if (args[1].equalsIgnoreCase("see") && VanishPerms.canToggleSee(player)) {
status = VanishPerms.toggleSeeAll(player);
message.append("see all");
} else if (args[1].equalsIgnoreCase("nopickup") && VanishPerms.canToggleNoPickup(player)) {
status = VanishPerms.toggleNoPickup(player);
message.append("no pickup");
} else if (args[1].equalsIgnoreCase("nofollow") && VanishPerms.canToggleNoFollow(player)) {
status = VanishPerms.toggleNoFollow(player);
message.append("no mob follow");
} else if (args[1].equalsIgnoreCase("damage-in") && VanishPerms.canToggleDamageIn(player)) {
status = VanishPerms.toggleDamageIn(player);
message.append("block incoming damage");
} else if (args[1].equalsIgnoreCase("damage-out") && VanishPerms.canToggleDamageOut(player)) {
status = VanishPerms.toggleDamageOut(player);
message.append("block outgoing damage");
}
if (message.length() > 0) {
message.insert(0, ChatColor.DARK_AQUA + "Status: ");
message.append(": ");
if (status) {
message.append("enabled");
} else {
message.append("disabled");
}
player.sendMessage(message.toString());
} else if (VanishPerms.canVanish(player)) {
player.sendMessage(ChatColor.DARK_AQUA + "You can't toggle that!");
}
}
} else if ((args[0].equalsIgnoreCase("fakequit") || args[0].equalsIgnoreCase("fq")) && VanishPerms.canFakeAnnounce(player)) {
this.plugin.getManager().getAnnounceManipulator().fakeQuit(player.getName());
} else if ((args[0].equalsIgnoreCase("fakejoin") || args[0].equalsIgnoreCase("fj")) && VanishPerms.canFakeAnnounce(player)) {
this.plugin.getManager().getAnnounceManipulator().fakeJoin(player.getName());
}
}
return true;
}
private void comma(StringBuilder builder, String string) {
if (builder.length() > 0) {
builder.append(", ");
}
builder.append(string);
}
private String colorize(boolean has) {
if (has) {
return ChatColor.GREEN.toString();
} else {
return ChatColor.RED.toString();
}
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if ((sender instanceof Player)) {
final Player player = (Player) sender;
if ((args.length == 0)) {
if (VanishPerms.canVanish((Player) sender)) {
this.plugin.getManager().toggleVanish(player);
}
} else if (args[0].equalsIgnoreCase("check") && VanishPerms.canVanish((Player) sender)) {
if (this.plugin.getManager().isVanished(player)) {
player.sendMessage(ChatColor.DARK_AQUA + "You are invisible.");
} else {
player.sendMessage(ChatColor.DARK_AQUA + "You are not invisible.");
}
} else if (args[0].equalsIgnoreCase("toggle")) {
if (args.length == 1) {
final StringBuilder toggleList = new StringBuilder();
if (VanishPerms.canToggleSee(player)) {
toggleList.append(this.colorize(VanishPerms.canSeeAll(player)) + "see" + ChatColor.DARK_AQUA);
this.plugin.getManager().resetSeeing(player);
}
if (VanishPerms.canToggleNoPickup(player)) {
this.comma(toggleList, this.colorize(VanishPerms.canNotPickUp(player)) + "nopickup" + ChatColor.DARK_AQUA);
}
if (VanishPerms.canToggleNoFollow(player)) {
this.comma(toggleList, this.colorize(VanishPerms.canNotFollow(player)) + "nofollow" + ChatColor.DARK_AQUA);
}
if (VanishPerms.canToggleDamageIn(player)) {
this.comma(toggleList, this.colorize(VanishPerms.blockIncomingDamage(player)) + "damage-in" + ChatColor.DARK_AQUA);
}
if (VanishPerms.canToggleDamageOut(player)) {
this.comma(toggleList, this.colorize(VanishPerms.blockOutgoingDamage(player)) + "damage-out" + ChatColor.DARK_AQUA);
}
if (toggleList.length() > 0) {
toggleList.insert(0, ChatColor.DARK_AQUA + "You can toggle: ");
} else {
if (VanishPerms.canVanish((Player) sender)) {
toggleList.append(ChatColor.DARK_AQUA + "You cannot toggle anything");
}
}
player.sendMessage(toggleList.toString());
} else {
final StringBuilder message = new StringBuilder();
boolean status = false;;
if (args[1].equalsIgnoreCase("see") && VanishPerms.canToggleSee(player)) {
status = VanishPerms.toggleSeeAll(player);
message.append("see all");
} else if (args[1].equalsIgnoreCase("nopickup") && VanishPerms.canToggleNoPickup(player)) {
status = VanishPerms.toggleNoPickup(player);
message.append("no pickup");
} else if (args[1].equalsIgnoreCase("nofollow") && VanishPerms.canToggleNoFollow(player)) {
status = VanishPerms.toggleNoFollow(player);
message.append("no mob follow");
} else if (args[1].equalsIgnoreCase("damage-in") && VanishPerms.canToggleDamageIn(player)) {
status = VanishPerms.toggleDamageIn(player);
message.append("block incoming damage");
} else if (args[1].equalsIgnoreCase("damage-out") && VanishPerms.canToggleDamageOut(player)) {
status = VanishPerms.toggleDamageOut(player);
message.append("block outgoing damage");
}
if (message.length() > 0) {
message.insert(0, ChatColor.DARK_AQUA + "Status: ");
message.append(": ");
if (status) {
message.append("enabled");
} else {
message.append("disabled");
}
player.sendMessage(message.toString());
} else if (VanishPerms.canVanish(player)) {
player.sendMessage(ChatColor.DARK_AQUA + "You can't toggle that!");
}
}
} else if ((args[0].equalsIgnoreCase("fakequit") || args[0].equalsIgnoreCase("fq")) && VanishPerms.canFakeAnnounce(player)) {
this.plugin.getManager().getAnnounceManipulator().fakeQuit(player.getName());
} else if ((args[0].equalsIgnoreCase("fakejoin") || args[0].equalsIgnoreCase("fj")) && VanishPerms.canFakeAnnounce(player)) {
this.plugin.getManager().getAnnounceManipulator().fakeJoin(player.getName());
}
}
return true;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if ((sender instanceof Player)) {
final Player player = (Player) sender;
if ((args.length == 0)) {
if (VanishPerms.canVanish((Player) sender)) {
this.plugin.getManager().toggleVanish(player);
}
} else if (args[0].equalsIgnoreCase("check") && VanishPerms.canVanish((Player) sender)) {
if (this.plugin.getManager().isVanished(player)) {
player.sendMessage(ChatColor.DARK_AQUA + "You are invisible.");
} else {
player.sendMessage(ChatColor.DARK_AQUA + "You are not invisible.");
}
} else if (args[0].equalsIgnoreCase("toggle")||args[0].equalsIgnoreCase("t")) {
if (args.length == 1) {
final StringBuilder toggleList = new StringBuilder();
if (VanishPerms.canToggleSee(player)) {
toggleList.append(this.colorize(VanishPerms.canSeeAll(player)) + "see" + ChatColor.DARK_AQUA);
this.plugin.getManager().resetSeeing(player);
}
if (VanishPerms.canToggleNoPickup(player)) {
this.comma(toggleList, this.colorize(VanishPerms.canNotPickUp(player)) + "nopickup" + ChatColor.DARK_AQUA);
}
if (VanishPerms.canToggleNoFollow(player)) {
this.comma(toggleList, this.colorize(VanishPerms.canNotFollow(player)) + "nofollow" + ChatColor.DARK_AQUA);
}
if (VanishPerms.canToggleDamageIn(player)) {
this.comma(toggleList, this.colorize(VanishPerms.blockIncomingDamage(player)) + "damage-in" + ChatColor.DARK_AQUA);
}
if (VanishPerms.canToggleDamageOut(player)) {
this.comma(toggleList, this.colorize(VanishPerms.blockOutgoingDamage(player)) + "damage-out" + ChatColor.DARK_AQUA);
}
if (toggleList.length() > 0) {
toggleList.insert(0, ChatColor.DARK_AQUA + "You can toggle: ");
} else {
if (VanishPerms.canVanish((Player) sender)) {
toggleList.append(ChatColor.DARK_AQUA + "You cannot toggle anything");
}
}
player.sendMessage(toggleList.toString());
} else {
final StringBuilder message = new StringBuilder();
boolean status = false;;
if (args[1].equalsIgnoreCase("see") && VanishPerms.canToggleSee(player)) {
status = VanishPerms.toggleSeeAll(player);
message.append("see all");
} else if (args[1].equalsIgnoreCase("nopickup") && VanishPerms.canToggleNoPickup(player)) {
status = VanishPerms.toggleNoPickup(player);
message.append("no pickup");
} else if (args[1].equalsIgnoreCase("nofollow") && VanishPerms.canToggleNoFollow(player)) {
status = VanishPerms.toggleNoFollow(player);
message.append("no mob follow");
} else if (args[1].equalsIgnoreCase("damage-in") && VanishPerms.canToggleDamageIn(player)) {
status = VanishPerms.toggleDamageIn(player);
message.append("block incoming damage");
} else if (args[1].equalsIgnoreCase("damage-out") && VanishPerms.canToggleDamageOut(player)) {
status = VanishPerms.toggleDamageOut(player);
message.append("block outgoing damage");
}
if (message.length() > 0) {
message.insert(0, ChatColor.DARK_AQUA + "Status: ");
message.append(": ");
if (status) {
message.append("enabled");
} else {
message.append("disabled");
}
player.sendMessage(message.toString());
} else if (VanishPerms.canVanish(player)) {
player.sendMessage(ChatColor.DARK_AQUA + "You can't toggle that!");
}
}
} else if ((args[0].equalsIgnoreCase("fakequit") || args[0].equalsIgnoreCase("fq")) && VanishPerms.canFakeAnnounce(player)) {
this.plugin.getManager().getAnnounceManipulator().fakeQuit(player.getName());
} else if ((args[0].equalsIgnoreCase("fakejoin") || args[0].equalsIgnoreCase("fj")) && VanishPerms.canFakeAnnounce(player)) {
this.plugin.getManager().getAnnounceManipulator().fakeJoin(player.getName());
}
}
return true;
}
|
diff --git a/java/com/example/testapplication/ContactAdapter.java b/java/com/example/testapplication/ContactAdapter.java
index 6feea67..7cb495f 100644
--- a/java/com/example/testapplication/ContactAdapter.java
+++ b/java/com/example/testapplication/ContactAdapter.java
@@ -1,56 +1,56 @@
package com.example.testapplication;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class ContactAdapter extends ArrayAdapter<Contact> {
private final List<Contact> _contacts;
private final Activity _context;
public ContactAdapter(Activity context, List<Contact> contacts) {
super(context, R.layout.contactlistitem, contacts);
this._contacts = contacts;
this._context = context;
}
static class ViewHolder {
protected TextView text;
private Contact _contact;
protected void setContact(Contact contact) {
text.setText(contact.getDisplayName());
_contact = contact;
}
protected Contact getContact() {
return _contact;
}
}
@Override
public Contact getItem(int position) {
return _contacts.get(position);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
- View view = null;
+ View view = convertView;
if (convertView == null) {
LayoutInflater inflater = _context.getLayoutInflater();
view = inflater.inflate(R.layout.contactlistitem, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.txtDisplayName);
viewHolder.setContact(_contacts.get(position));
view.setTag(viewHolder);
}
return view;
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflater = _context.getLayoutInflater();
view = inflater.inflate(R.layout.contactlistitem, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.txtDisplayName);
viewHolder.setContact(_contacts.get(position));
view.setTag(viewHolder);
}
return view;
}
| public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (convertView == null) {
LayoutInflater inflater = _context.getLayoutInflater();
view = inflater.inflate(R.layout.contactlistitem, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.txtDisplayName);
viewHolder.setContact(_contacts.get(position));
view.setTag(viewHolder);
}
return view;
}
|
diff --git a/src/org/bouncycastle/crypto/engines/HC128Engine.java b/src/org/bouncycastle/crypto/engines/HC128Engine.java
index 19ecefd7..bf9a1b0e 100644
--- a/src/org/bouncycastle/crypto/engines/HC128Engine.java
+++ b/src/org/bouncycastle/crypto/engines/HC128Engine.java
@@ -1,256 +1,256 @@
package org.bouncycastle.crypto.engines;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.StreamCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
/**
* HC-128 is a software-efficient stream cipher created by Hongjun Wu. It
* generates keystream from a 128-bit secret key and a 128-bit initialization
* vector.
* <p>
* http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf
* </p><p>
* It is a third phase candidate in the eStream contest, and is patent-free.
* No attacks are known as of today (April 2007). See
*
* http://www.ecrypt.eu.org/stream/hcp3.html
* </p>
*/
public class HC128Engine
implements StreamCipher
{
private int[] p = new int[512];
private int[] q = new int[512];
private int cnt = 0;
private static int f1(int x)
{
return rotateRight(x, 7) ^ rotateRight(x, 18)
^ (x >>> 3);
}
private static int f2(int x)
{
return rotateRight(x, 17) ^ rotateRight(x, 19)
^ (x >>> 10);
}
private int g1(int x, int y, int z)
{
return (rotateRight(x, 10) ^ rotateRight(z, 23))
+ rotateRight(y, 8);
}
private int g2(int x, int y, int z)
{
return (rotateLeft(x, 10) ^ rotateLeft(z, 23)) + rotateLeft(y, 8);
}
private static int rotateLeft(
int x,
int bits)
{
return (x << bits) | (x >>> -bits);
}
private static int rotateRight(
int x,
int bits)
{
return (x >>> bits) | (x << -bits);
}
private int h1(int x)
{
return q[x & 0xFF] + q[((x >> 16) & 0xFF) + 256];
}
private int h2(int x)
{
return p[x & 0xFF] + p[((x >> 16) & 0xFF) + 256];
}
private static int mod1024(int x)
{
return x & 0x3FF;
}
private static int mod512(int x)
{
return x & 0x1FF;
}
private static int dim(int x, int y)
{
return mod512(x - y);
}
private int step()
{
int j = mod512(cnt);
int ret;
if (cnt < 512)
{
p[j] += g1(p[dim(j, 3)], p[dim(j, 10)], p[dim(j, 511)]);
ret = h1(p[dim(j, 12)]) ^ p[j];
}
else
{
q[j] += g2(q[dim(j, 3)], q[dim(j, 10)], q[dim(j, 511)]);
ret = h2(q[dim(j, 12)]) ^ q[j];
}
cnt = mod1024(cnt + 1);
return ret;
}
private byte[] key, iv;
private boolean initialised;
private void init()
{
if (key.length != 16)
{
throw new java.lang.IllegalArgumentException(
- "The key must be 128 bit long");
+ "The key must be 128 bits long");
}
cnt = 0;
int[] w = new int[1280];
for (int i = 0; i < 16; i++)
{
w[i >> 2] |= (key[i] & 0xff) << (8 * (i & 0x3));
}
System.arraycopy(w, 0, w, 4, 4);
for (int i = 0; i < iv.length && i < 16; i++)
{
w[(i >> 2) + 8] |= (iv[i] & 0xff) << (8 * (i & 0x3));
}
System.arraycopy(w, 8, w, 12, 4);
for (int i = 16; i < 1280; i++)
{
w[i] = f2(w[i - 2]) + w[i - 7] + f1(w[i - 15]) + w[i - 16] + i;
}
System.arraycopy(w, 256, p, 0, 512);
System.arraycopy(w, 768, q, 0, 512);
for (int i = 0; i < 512; i++)
{
p[i] = step();
}
for (int i = 0; i < 512; i++)
{
q[i] = step();
}
cnt = 0;
}
public String getAlgorithmName()
{
return "HC-128";
}
/**
* Initialise a HC-128 cipher.
*
* @param forEncryption whether or not we are for encryption. Irrelevant, as
* encryption and decryption are the same.
* @param params the parameters required to set up the cipher.
* @throws IllegalArgumentException if the params argument is
* inappropriate (ie. the key is not 128 bit long).
*/
public void init(boolean forEncryption, CipherParameters params)
throws IllegalArgumentException
{
CipherParameters keyParam = params;
if (params instanceof ParametersWithIV)
{
iv = ((ParametersWithIV)params).getIV();
keyParam = ((ParametersWithIV)params).getParameters();
}
else
{
iv = new byte[0];
}
if (keyParam instanceof KeyParameter)
{
key = ((KeyParameter)keyParam).getKey();
init();
}
else
{
throw new IllegalArgumentException(
"Invalid parameter passed to HC128 init - "
+ params.getClass().getName());
}
initialised = true;
}
private byte[] buf = new byte[4];
private int idx = 0;
private byte getByte()
{
if (idx == 0)
{
int step = step();
buf[0] = (byte)(step & 0xFF);
step >>= 8;
buf[1] = (byte)(step & 0xFF);
step >>= 8;
buf[2] = (byte)(step & 0xFF);
step >>= 8;
buf[3] = (byte)(step & 0xFF);
}
byte ret = buf[idx];
idx = idx + 1 & 0x3;
return ret;
}
public void processBytes(byte[] in, int inOff, int len, byte[] out,
int outOff) throws DataLengthException
{
if (!initialised)
{
throw new IllegalStateException(getAlgorithmName()
+ " not initialised");
}
if ((inOff + len) > in.length)
{
throw new DataLengthException("input buffer too short");
}
if ((outOff + len) > out.length)
{
throw new DataLengthException("output buffer too short");
}
for (int i = 0; i < len; i++)
{
out[outOff + i] = (byte)(in[inOff + i] ^ getByte());
}
}
public void reset()
{
idx = 0;
init();
}
public byte returnByte(byte in)
{
return (byte)(in ^ getByte());
}
}
| true | true | private void init()
{
if (key.length != 16)
{
throw new java.lang.IllegalArgumentException(
"The key must be 128 bit long");
}
cnt = 0;
int[] w = new int[1280];
for (int i = 0; i < 16; i++)
{
w[i >> 2] |= (key[i] & 0xff) << (8 * (i & 0x3));
}
System.arraycopy(w, 0, w, 4, 4);
for (int i = 0; i < iv.length && i < 16; i++)
{
w[(i >> 2) + 8] |= (iv[i] & 0xff) << (8 * (i & 0x3));
}
System.arraycopy(w, 8, w, 12, 4);
for (int i = 16; i < 1280; i++)
{
w[i] = f2(w[i - 2]) + w[i - 7] + f1(w[i - 15]) + w[i - 16] + i;
}
System.arraycopy(w, 256, p, 0, 512);
System.arraycopy(w, 768, q, 0, 512);
for (int i = 0; i < 512; i++)
{
p[i] = step();
}
for (int i = 0; i < 512; i++)
{
q[i] = step();
}
cnt = 0;
}
| private void init()
{
if (key.length != 16)
{
throw new java.lang.IllegalArgumentException(
"The key must be 128 bits long");
}
cnt = 0;
int[] w = new int[1280];
for (int i = 0; i < 16; i++)
{
w[i >> 2] |= (key[i] & 0xff) << (8 * (i & 0x3));
}
System.arraycopy(w, 0, w, 4, 4);
for (int i = 0; i < iv.length && i < 16; i++)
{
w[(i >> 2) + 8] |= (iv[i] & 0xff) << (8 * (i & 0x3));
}
System.arraycopy(w, 8, w, 12, 4);
for (int i = 16; i < 1280; i++)
{
w[i] = f2(w[i - 2]) + w[i - 7] + f1(w[i - 15]) + w[i - 16] + i;
}
System.arraycopy(w, 256, p, 0, 512);
System.arraycopy(w, 768, q, 0, 512);
for (int i = 0; i < 512; i++)
{
p[i] = step();
}
for (int i = 0; i < 512; i++)
{
q[i] = step();
}
cnt = 0;
}
|
diff --git a/src/TApp.java b/src/TApp.java
index c35afb0..e6be3f7 100644
--- a/src/TApp.java
+++ b/src/TApp.java
@@ -1,34 +1,34 @@
import javax.swing.JFrame;
import javax.swing.WindowConstants;
/** Our entry point for the MBTA Application */
class TApp extends JFrame {
/** Default constructor */
TApp() {
- // Create a new map panel and add it to our content pane
- TMapPanel mapPanel = new TMapPanel();
- getContentPane().add(mapPanel);
+ // Create a new map panel and add it to our content pane
+ TMapPanel mapPanel = new TMapPanel();
+ getContentPane().add(mapPanel);
- // Set up our frame...
+ // Set up our frame...
- // Stop the application when the window is closed
- setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
+ // Stop the application when the window is closed
+ setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
- // Ignore repaint since we will handle that in our map panel ourselves
- setIgnoreRepaint( true );
+ // Ignore repaint since we will handle that in our map panel ourselves
+ setIgnoreRepaint( true );
- pack();
- setVisible( true );
+ pack();
+ setVisible( true );
}
/** Our main function */
public static void main( String strArgs[] ) {
// Start our listener
TDataListener.start();
// Simply create our JFrame
new TApp();
}
}
| false | true | TApp() {
// Create a new map panel and add it to our content pane
TMapPanel mapPanel = new TMapPanel();
getContentPane().add(mapPanel);
// Set up our frame...
// Stop the application when the window is closed
setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
// Ignore repaint since we will handle that in our map panel ourselves
setIgnoreRepaint( true );
pack();
setVisible( true );
}
| TApp() {
// Create a new map panel and add it to our content pane
TMapPanel mapPanel = new TMapPanel();
getContentPane().add(mapPanel);
// Set up our frame...
// Stop the application when the window is closed
setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
// Ignore repaint since we will handle that in our map panel ourselves
setIgnoreRepaint( true );
pack();
setVisible( true );
}
|
diff --git a/src/com/android/calendar/alerts/SnoozeAlarmsService.java b/src/com/android/calendar/alerts/SnoozeAlarmsService.java
index 2eac1a71..6ef983d5 100644
--- a/src/com/android/calendar/alerts/SnoozeAlarmsService.java
+++ b/src/com/android/calendar/alerts/SnoozeAlarmsService.java
@@ -1,88 +1,89 @@
/*
* Copyright (C) 2012 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.calendar.alerts;
import android.app.IntentService;
import android.app.NotificationManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.provider.CalendarContract.CalendarAlerts;
/**
* Service for asynchronously marking a fired alarm as dismissed and scheduling
* a new alarm in the future.
*/
public class SnoozeAlarmsService extends IntentService {
private static final String[] PROJECTION = new String[] {
CalendarAlerts.STATE,
};
private static final int COLUMN_INDEX_STATE = 0;
public SnoozeAlarmsService() {
super("SnoozeAlarmsService");
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onHandleIntent(Intent intent) {
long eventId = intent.getLongExtra(AlertUtils.EVENT_ID_KEY, -1);
long eventStart = intent.getLongExtra(AlertUtils.EVENT_START_KEY, -1);
long eventEnd = intent.getLongExtra(AlertUtils.EVENT_END_KEY, -1);
// The ID reserved for the expired notification digest should never be passed in
// here, so use that as a default.
int notificationId = intent.getIntExtra(AlertUtils.NOTIFICATION_ID_KEY,
AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
if (eventId != -1) {
ContentResolver resolver = getContentResolver();
// Remove notification
if (notificationId != AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
}
// Dismiss current alarm
Uri uri = CalendarAlerts.CONTENT_URI;
String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.STATE_FIRED + " AND " +
CalendarAlerts.EVENT_ID + "=" + eventId;
ContentValues dismissValues = new ContentValues();
dismissValues.put(PROJECTION[COLUMN_INDEX_STATE], CalendarAlerts.STATE_DISMISSED);
resolver.update(uri, dismissValues, selection, null);
// Add a new alarm
long alarmTime = System.currentTimeMillis() + AlertUtils.SNOOZE_DELAY;
ContentValues values = AlertUtils.makeContentValues(eventId, eventStart, eventEnd,
alarmTime, 0);
resolver.insert(uri, values);
- AlertUtils.scheduleAlarm(SnoozeAlarmsService.this, null, alarmTime);
+ AlertUtils.scheduleAlarm(SnoozeAlarmsService.this, AlertUtils.createAlarmManager(this),
+ alarmTime);
}
AlertService.updateAlertNotification(this);
stopSelf();
}
}
| true | true | public void onHandleIntent(Intent intent) {
long eventId = intent.getLongExtra(AlertUtils.EVENT_ID_KEY, -1);
long eventStart = intent.getLongExtra(AlertUtils.EVENT_START_KEY, -1);
long eventEnd = intent.getLongExtra(AlertUtils.EVENT_END_KEY, -1);
// The ID reserved for the expired notification digest should never be passed in
// here, so use that as a default.
int notificationId = intent.getIntExtra(AlertUtils.NOTIFICATION_ID_KEY,
AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
if (eventId != -1) {
ContentResolver resolver = getContentResolver();
// Remove notification
if (notificationId != AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
}
// Dismiss current alarm
Uri uri = CalendarAlerts.CONTENT_URI;
String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.STATE_FIRED + " AND " +
CalendarAlerts.EVENT_ID + "=" + eventId;
ContentValues dismissValues = new ContentValues();
dismissValues.put(PROJECTION[COLUMN_INDEX_STATE], CalendarAlerts.STATE_DISMISSED);
resolver.update(uri, dismissValues, selection, null);
// Add a new alarm
long alarmTime = System.currentTimeMillis() + AlertUtils.SNOOZE_DELAY;
ContentValues values = AlertUtils.makeContentValues(eventId, eventStart, eventEnd,
alarmTime, 0);
resolver.insert(uri, values);
AlertUtils.scheduleAlarm(SnoozeAlarmsService.this, null, alarmTime);
}
AlertService.updateAlertNotification(this);
stopSelf();
}
| public void onHandleIntent(Intent intent) {
long eventId = intent.getLongExtra(AlertUtils.EVENT_ID_KEY, -1);
long eventStart = intent.getLongExtra(AlertUtils.EVENT_START_KEY, -1);
long eventEnd = intent.getLongExtra(AlertUtils.EVENT_END_KEY, -1);
// The ID reserved for the expired notification digest should never be passed in
// here, so use that as a default.
int notificationId = intent.getIntExtra(AlertUtils.NOTIFICATION_ID_KEY,
AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID);
if (eventId != -1) {
ContentResolver resolver = getContentResolver();
// Remove notification
if (notificationId != AlertUtils.EXPIRED_GROUP_NOTIFICATION_ID) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(notificationId);
}
// Dismiss current alarm
Uri uri = CalendarAlerts.CONTENT_URI;
String selection = CalendarAlerts.STATE + "=" + CalendarAlerts.STATE_FIRED + " AND " +
CalendarAlerts.EVENT_ID + "=" + eventId;
ContentValues dismissValues = new ContentValues();
dismissValues.put(PROJECTION[COLUMN_INDEX_STATE], CalendarAlerts.STATE_DISMISSED);
resolver.update(uri, dismissValues, selection, null);
// Add a new alarm
long alarmTime = System.currentTimeMillis() + AlertUtils.SNOOZE_DELAY;
ContentValues values = AlertUtils.makeContentValues(eventId, eventStart, eventEnd,
alarmTime, 0);
resolver.insert(uri, values);
AlertUtils.scheduleAlarm(SnoozeAlarmsService.this, AlertUtils.createAlarmManager(this),
alarmTime);
}
AlertService.updateAlertNotification(this);
stopSelf();
}
|
diff --git a/lucene/src/test/org/apache/lucene/index/TestDeletionPolicy.java b/lucene/src/test/org/apache/lucene/index/TestDeletionPolicy.java
index e6166355a..8e71ca8d1 100644
--- a/lucene/src/test/org/apache/lucene/index/TestDeletionPolicy.java
+++ b/lucene/src/test/org/apache/lucene/index/TestDeletionPolicy.java
@@ -1,846 +1,847 @@
package org.apache.lucene.index;
/**
* 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.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Collection;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.LuceneTestCase;
/*
Verify we can read the pre-2.1 file format, do searches
against it, and add documents to it.
*/
public class TestDeletionPolicy extends LuceneTestCase {
private void verifyCommitOrder(List<? extends IndexCommit> commits) throws IOException {
final IndexCommit firstCommit = commits.get(0);
long last = SegmentInfos.generationFromSegmentsFileName(firstCommit.getSegmentsFileName());
assertEquals(last, firstCommit.getGeneration());
long lastVersion = firstCommit.getVersion();
long lastTimestamp = firstCommit.getTimestamp();
for(int i=1;i<commits.size();i++) {
final IndexCommit commit = commits.get(i);
long now = SegmentInfos.generationFromSegmentsFileName(commit.getSegmentsFileName());
long nowVersion = commit.getVersion();
long nowTimestamp = commit.getTimestamp();
assertTrue("SegmentInfos commits are out-of-order", now > last);
assertTrue("SegmentInfos versions are out-of-order", nowVersion > lastVersion);
assertTrue("SegmentInfos timestamps are out-of-order: now=" + nowTimestamp + " vs last=" + lastTimestamp, nowTimestamp >= lastTimestamp);
assertEquals(now, commit.getGeneration());
last = now;
lastVersion = nowVersion;
lastTimestamp = nowTimestamp;
}
}
class KeepAllDeletionPolicy implements IndexDeletionPolicy {
int numOnInit;
int numOnCommit;
Directory dir;
public void onInit(List<? extends IndexCommit> commits) throws IOException {
verifyCommitOrder(commits);
numOnInit++;
}
public void onCommit(List<? extends IndexCommit> commits) throws IOException {
IndexCommit lastCommit = commits.get(commits.size()-1);
IndexReader r = IndexReader.open(dir, true);
assertEquals("lastCommit.isOptimized()=" + lastCommit.isOptimized() + " vs IndexReader.isOptimized=" + r.isOptimized(), r.isOptimized(), lastCommit.isOptimized());
r.close();
verifyCommitOrder(commits);
numOnCommit++;
}
}
/**
* This is useful for adding to a big index when you know
* readers are not using it.
*/
class KeepNoneOnInitDeletionPolicy implements IndexDeletionPolicy {
int numOnInit;
int numOnCommit;
public void onInit(List<? extends IndexCommit> commits) throws IOException {
verifyCommitOrder(commits);
numOnInit++;
// On init, delete all commit points:
for (final IndexCommit commit : commits) {
commit.delete();
assertTrue(commit.isDeleted());
}
}
public void onCommit(List<? extends IndexCommit> commits) throws IOException {
verifyCommitOrder(commits);
int size = commits.size();
// Delete all but last one:
for(int i=0;i<size-1;i++) {
((IndexCommit) commits.get(i)).delete();
}
numOnCommit++;
}
}
class KeepLastNDeletionPolicy implements IndexDeletionPolicy {
int numOnInit;
int numOnCommit;
int numToKeep;
int numDelete;
Set<String> seen = new HashSet<String>();
public KeepLastNDeletionPolicy(int numToKeep) {
this.numToKeep = numToKeep;
}
public void onInit(List<? extends IndexCommit> commits) throws IOException {
if (VERBOSE) {
System.out.println("TEST: onInit");
}
verifyCommitOrder(commits);
numOnInit++;
// do no deletions on init
doDeletes(commits, false);
}
public void onCommit(List<? extends IndexCommit> commits) throws IOException {
if (VERBOSE) {
System.out.println("TEST: onCommit");
}
verifyCommitOrder(commits);
doDeletes(commits, true);
}
private void doDeletes(List<? extends IndexCommit> commits, boolean isCommit) {
// Assert that we really are only called for each new
// commit:
if (isCommit) {
String fileName = ((IndexCommit) commits.get(commits.size()-1)).getSegmentsFileName();
if (seen.contains(fileName)) {
throw new RuntimeException("onCommit was called twice on the same commit point: " + fileName);
}
seen.add(fileName);
numOnCommit++;
}
int size = commits.size();
for(int i=0;i<size-numToKeep;i++) {
((IndexCommit) commits.get(i)).delete();
numDelete++;
}
}
}
/*
* Delete a commit only when it has been obsoleted by N
* seconds.
*/
class ExpirationTimeDeletionPolicy implements IndexDeletionPolicy {
Directory dir;
double expirationTimeSeconds;
int numDelete;
public ExpirationTimeDeletionPolicy(Directory dir, double seconds) {
this.dir = dir;
this.expirationTimeSeconds = seconds;
}
public void onInit(List<? extends IndexCommit> commits) throws IOException {
verifyCommitOrder(commits);
onCommit(commits);
}
public void onCommit(List<? extends IndexCommit> commits) throws IOException {
verifyCommitOrder(commits);
IndexCommit lastCommit = commits.get(commits.size()-1);
// Any commit older than expireTime should be deleted:
double expireTime = dir.fileModified(lastCommit.getSegmentsFileName())/1000.0 - expirationTimeSeconds;
for (final IndexCommit commit : commits) {
double modTime = dir.fileModified(commit.getSegmentsFileName())/1000.0;
if (commit != lastCommit && modTime < expireTime) {
commit.delete();
numDelete += 1;
}
}
}
}
/*
* Test "by time expiration" deletion policy:
*/
public void testExpirationTimeDeletionPolicy() throws IOException, InterruptedException {
final double SECONDS = 2.0;
Directory dir = newDirectory();
ExpirationTimeDeletionPolicy policy = new ExpirationTimeDeletionPolicy(dir, SECONDS);
IndexWriterConfig conf = newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random))
.setIndexDeletionPolicy(policy);
MergePolicy mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(true);
}
IndexWriter writer = new IndexWriter(dir, conf);
writer.close();
final int ITER = 9;
long lastDeleteTime = 0;
for(int i=0;i<ITER;i++) {
// Record last time when writer performed deletes of
// past commits
lastDeleteTime = System.currentTimeMillis();
conf = newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setOpenMode(
OpenMode.APPEND).setIndexDeletionPolicy(policy);
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(true);
}
writer = new IndexWriter(dir, conf);
for(int j=0;j<17;j++) {
addDoc(writer);
}
writer.close();
if (i < ITER-1) {
// Make sure to sleep long enough so that some commit
// points will be deleted:
Thread.sleep((int) (1000.0*(SECONDS/5.0)));
}
}
// First, make sure the policy in fact deleted something:
assertTrue("no commits were deleted", policy.numDelete > 0);
// Then simplistic check: just verify that the
// segments_N's that still exist are in fact within SECONDS
// seconds of the last one's mod time, and, that I can
// open a reader on each:
long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
String fileName = IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS,
"",
gen);
dir.deleteFile(IndexFileNames.SEGMENTS_GEN);
boolean oneSecondResolution = true;
while(gen > 0) {
try {
IndexReader reader = IndexReader.open(dir, true);
reader.close();
fileName = IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS,
"",
gen);
// if we are on a filesystem that seems to have only
// 1 second resolution, allow +1 second in commit
// age tolerance:
long modTime = dir.fileModified(fileName);
oneSecondResolution &= (modTime % 1000) == 0;
final long leeway = (long) ((SECONDS + (oneSecondResolution ? 1.0:0.0))*1000);
assertTrue("commit point was older than " + SECONDS + " seconds (" + (lastDeleteTime - modTime) + " msec) but did not get deleted ", lastDeleteTime - modTime <= leeway);
} catch (IOException e) {
// OK
break;
}
dir.deleteFile(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen));
gen--;
}
dir.close();
}
/*
* Test a silly deletion policy that keeps all commits around.
*/
public void testKeepAllDeletionPolicy() throws IOException {
for(int pass=0;pass<2;pass++) {
if (VERBOSE) {
System.out.println("TEST: cycle pass=" + pass);
}
boolean useCompoundFile = (pass % 2) != 0;
// Never deletes a commit
KeepAllDeletionPolicy policy = new KeepAllDeletionPolicy();
Directory dir = newDirectory();
policy.dir = dir;
IndexWriterConfig conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setIndexDeletionPolicy(policy).setMaxBufferedDocs(10)
.setMergeScheduler(new SerialMergeScheduler());
MergePolicy mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexWriter writer = new IndexWriter(dir, conf);
for(int i=0;i<107;i++) {
addDoc(writer);
}
writer.close();
final boolean isOptimized;
{
IndexReader r = IndexReader.open(dir);
isOptimized = r.isOptimized();
r.close();
}
if (!isOptimized) {
conf = newIndexWriterConfig(TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setOpenMode(
OpenMode.APPEND).setIndexDeletionPolicy(policy);
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
if (VERBOSE) {
System.out.println("TEST: open writer for optimize");
}
writer = new IndexWriter(dir, conf);
writer.setInfoStream(VERBOSE ? System.out : null);
writer.optimize();
writer.close();
}
assertEquals(isOptimized ? 0:1, policy.numOnInit);
// If we are not auto committing then there should
// be exactly 2 commits (one per close above):
assertEquals(1 + (isOptimized ? 0:1), policy.numOnCommit);
// Test listCommits
Collection<IndexCommit> commits = IndexReader.listCommits(dir);
// 2 from closing writer
assertEquals(1 + (isOptimized ? 0:1), commits.size());
// Make sure we can open a reader on each commit:
for (final IndexCommit commit : commits) {
IndexReader r = IndexReader.open(commit, null, false);
r.close();
}
// Simplistic check: just verify all segments_N's still
// exist, and, I can open a reader on each:
dir.deleteFile(IndexFileNames.SEGMENTS_GEN);
long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
while(gen > 0) {
IndexReader reader = IndexReader.open(dir, true);
reader.close();
dir.deleteFile(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen));
gen--;
if (gen > 0) {
// Now that we've removed a commit point, which
// should have orphan'd at least one index file.
// Open & close a writer and assert that it
// actually removed something:
int preCount = dir.listAll().length;
writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT,
new MockAnalyzer(random)).setOpenMode(
OpenMode.APPEND).setIndexDeletionPolicy(policy));
writer.close();
int postCount = dir.listAll().length;
assertTrue(postCount < preCount);
}
}
dir.close();
}
}
/* Uses KeepAllDeletionPolicy to keep all commits around,
* then, opens a new IndexWriter on a previous commit
* point. */
public void testOpenPriorSnapshot() throws IOException {
// Never deletes a commit
KeepAllDeletionPolicy policy = new KeepAllDeletionPolicy();
Directory dir = newDirectory();
policy.dir = dir;
IndexWriter writer = new IndexWriter(
dir,
newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).
setIndexDeletionPolicy(policy).
setMaxBufferedDocs(2).
setMergePolicy(newLogMergePolicy(10))
);
for(int i=0;i<10;i++) {
addDoc(writer);
if ((1+i)%2 == 0)
writer.commit();
}
writer.close();
Collection<IndexCommit> commits = IndexReader.listCommits(dir);
assertEquals(5, commits.size());
IndexCommit lastCommit = null;
for (final IndexCommit commit : commits) {
if (lastCommit == null || commit.getGeneration() > lastCommit.getGeneration())
lastCommit = commit;
}
assertTrue(lastCommit != null);
// Now add 1 doc and optimize
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setIndexDeletionPolicy(policy));
addDoc(writer);
assertEquals(11, writer.numDocs());
writer.optimize();
writer.close();
assertEquals(6, IndexReader.listCommits(dir).size());
// Now open writer on the commit just before optimize:
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setIndexDeletionPolicy(policy).setIndexCommit(lastCommit));
assertEquals(10, writer.numDocs());
// Should undo our rollback:
writer.rollback();
IndexReader r = IndexReader.open(dir, true);
// Still optimized, still 11 docs
assertTrue(r.isOptimized());
assertEquals(11, r.numDocs());
r.close();
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setIndexDeletionPolicy(policy).setIndexCommit(lastCommit));
assertEquals(10, writer.numDocs());
// Commits the rollback:
writer.close();
// Now 8 because we made another commit
assertEquals(7, IndexReader.listCommits(dir).size());
r = IndexReader.open(dir, true);
// Not optimized because we rolled it back, and now only
// 10 docs
assertTrue(!r.isOptimized());
assertEquals(10, r.numDocs());
r.close();
// Reoptimize
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setIndexDeletionPolicy(policy));
writer.optimize();
writer.close();
r = IndexReader.open(dir, true);
assertTrue(r.isOptimized());
assertEquals(10, r.numDocs());
r.close();
// Now open writer on the commit just before optimize,
// but this time keeping only the last commit:
writer = new IndexWriter(dir, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random)).setIndexCommit(lastCommit));
assertEquals(10, writer.numDocs());
// Reader still sees optimized index, because writer
// opened on the prior commit has not yet committed:
r = IndexReader.open(dir, true);
assertTrue(r.isOptimized());
assertEquals(10, r.numDocs());
r.close();
writer.close();
// Now reader sees unoptimized index:
r = IndexReader.open(dir, true);
assertTrue(!r.isOptimized());
assertEquals(10, r.numDocs());
r.close();
dir.close();
}
/* Test keeping NO commit points. This is a viable and
* useful case eg where you want to build a big index and
* you know there are no readers.
*/
public void testKeepNoneOnInitDeletionPolicy() throws IOException {
for(int pass=0;pass<2;pass++) {
boolean useCompoundFile = (pass % 2) != 0;
KeepNoneOnInitDeletionPolicy policy = new KeepNoneOnInitDeletionPolicy();
Directory dir = newDirectory();
IndexWriterConfig conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.CREATE).setIndexDeletionPolicy(policy)
.setMaxBufferedDocs(10);
MergePolicy mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexWriter writer = new IndexWriter(dir, conf);
for(int i=0;i<107;i++) {
addDoc(writer);
}
writer.close();
conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.APPEND).setIndexDeletionPolicy(policy);
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(true);
}
writer = new IndexWriter(dir, conf);
writer.optimize();
writer.close();
assertEquals(1, policy.numOnInit);
// If we are not auto committing then there should
// be exactly 2 commits (one per close above):
assertEquals(2, policy.numOnCommit);
// Simplistic check: just verify the index is in fact
// readable:
IndexReader reader = IndexReader.open(dir, true);
reader.close();
dir.close();
}
}
/*
* Test a deletion policy that keeps last N commits.
*/
public void testKeepLastNDeletionPolicy() throws IOException {
final int N = 5;
for(int pass=0;pass<2;pass++) {
boolean useCompoundFile = (pass % 2) != 0;
Directory dir = newDirectory();
KeepLastNDeletionPolicy policy = new KeepLastNDeletionPolicy(N);
for(int j=0;j<N+1;j++) {
IndexWriterConfig conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.CREATE).setIndexDeletionPolicy(policy)
.setMaxBufferedDocs(10);
MergePolicy mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexWriter writer = new IndexWriter(dir, conf);
for(int i=0;i<17;i++) {
addDoc(writer);
}
writer.optimize();
writer.close();
}
assertTrue(policy.numDelete > 0);
assertEquals(N, policy.numOnInit);
assertEquals(N+1, policy.numOnCommit);
// Simplistic check: just verify only the past N segments_N's still
// exist, and, I can open a reader on each:
dir.deleteFile(IndexFileNames.SEGMENTS_GEN);
long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
for(int i=0;i<N+1;i++) {
try {
IndexReader reader = IndexReader.open(dir, true);
reader.close();
if (i == N) {
fail("should have failed on commits prior to last " + N);
}
} catch (IOException e) {
if (i != N) {
throw e;
}
}
if (i < N) {
dir.deleteFile(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen));
}
gen--;
}
dir.close();
}
}
/*
* Test a deletion policy that keeps last N commits
* around, with reader doing deletes.
*/
public void testKeepLastNDeletionPolicyWithReader() throws IOException {
final int N = 10;
for(int pass=0;pass<2;pass++) {
boolean useCompoundFile = (pass % 2) != 0;
KeepLastNDeletionPolicy policy = new KeepLastNDeletionPolicy(N);
Directory dir = newDirectory();
IndexWriterConfig conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.CREATE).setIndexDeletionPolicy(policy).setMergePolicy(newLogMergePolicy());
MergePolicy mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexWriter writer = new IndexWriter(dir, conf);
writer.close();
Term searchTerm = new Term("content", "aaa");
Query query = new TermQuery(searchTerm);
for(int i=0;i<N+1;i++) {
if (VERBOSE) {
System.out.println("\nTEST: cycle i=" + i);
}
conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
- .setOpenMode(OpenMode.APPEND).setIndexDeletionPolicy(policy);
+ .setOpenMode(OpenMode.APPEND).setIndexDeletionPolicy(policy).setMergePolicy(newLogMergePolicy());
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
writer = new IndexWriter(dir, conf);
+ writer.setInfoStream(VERBOSE ? System.out : null);
for(int j=0;j<17;j++) {
addDoc(writer);
}
// this is a commit
if (VERBOSE) {
System.out.println("TEST: close writer");
}
writer.close();
IndexReader reader = IndexReader.open(dir, policy, false);
reader.deleteDocument(3*i+1);
reader.setNorm(4*i+1, "content", conf.getSimilarityProvider().get("content").encodeNormValue(2.0F));
IndexSearcher searcher = newSearcher(reader);
ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals(16*(1+i), hits.length);
// this is a commit
if (VERBOSE) {
System.out.println("TEST: close reader numOnCommit=" + policy.numOnCommit);
}
reader.close();
searcher.close();
}
conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.APPEND).setIndexDeletionPolicy(policy);
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexReader r = IndexReader.open(dir);
final boolean wasOptimized = r.isOptimized();
r.close();
writer = new IndexWriter(dir, conf);
writer.optimize();
// this is a commit
writer.close();
assertEquals(2*(N+1)+1, policy.numOnInit);
assertEquals(2*(N+2) - (wasOptimized ? 1:0), policy.numOnCommit);
IndexSearcher searcher = new IndexSearcher(dir, false);
ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals(176, hits.length);
// Simplistic check: just verify only the past N segments_N's still
// exist, and, I can open a reader on each:
long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
dir.deleteFile(IndexFileNames.SEGMENTS_GEN);
int expectedCount = 176;
searcher.close();
for(int i=0;i<N+1;i++) {
try {
IndexReader reader = IndexReader.open(dir, true);
// Work backwards in commits on what the expected
// count should be.
searcher = newSearcher(reader);
hits = searcher.search(query, null, 1000).scoreDocs;
if (i > 1) {
if (i % 2 == 0) {
expectedCount += 1;
} else {
expectedCount -= 17;
}
}
assertEquals(expectedCount, hits.length);
searcher.close();
reader.close();
if (i == N) {
fail("should have failed on commits before last 5");
}
} catch (IOException e) {
if (i != N) {
throw e;
}
}
if (i < N) {
dir.deleteFile(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen));
}
gen--;
}
dir.close();
}
}
/*
* Test a deletion policy that keeps last N commits
* around, through creates.
*/
public void testKeepLastNDeletionPolicyWithCreates() throws IOException {
final int N = 10;
for(int pass=0;pass<2;pass++) {
boolean useCompoundFile = (pass % 2) != 0;
KeepLastNDeletionPolicy policy = new KeepLastNDeletionPolicy(N);
Directory dir = newDirectory();
IndexWriterConfig conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.CREATE).setIndexDeletionPolicy(policy)
.setMaxBufferedDocs(10);
MergePolicy mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexWriter writer = new IndexWriter(dir, conf);
writer.close();
Term searchTerm = new Term("content", "aaa");
Query query = new TermQuery(searchTerm);
for(int i=0;i<N+1;i++) {
conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.APPEND).setIndexDeletionPolicy(policy)
.setMaxBufferedDocs(10);
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
writer = new IndexWriter(dir, conf);
for(int j=0;j<17;j++) {
addDoc(writer);
}
// this is a commit
writer.close();
IndexReader reader = IndexReader.open(dir, policy, false);
reader.deleteDocument(3);
reader.setNorm(5, "content", conf.getSimilarityProvider().get("content").encodeNormValue(2.0F));
IndexSearcher searcher = newSearcher(reader);
ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals(16, hits.length);
// this is a commit
reader.close();
searcher.close();
writer = new IndexWriter(dir, newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.CREATE).setIndexDeletionPolicy(policy));
// This will not commit: there are no changes
// pending because we opened for "create":
writer.close();
}
assertEquals(3*(N+1), policy.numOnInit);
assertEquals(3*(N+1)+1, policy.numOnCommit);
IndexSearcher searcher = new IndexSearcher(dir, false);
ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals(0, hits.length);
// Simplistic check: just verify only the past N segments_N's still
// exist, and, I can open a reader on each:
long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
dir.deleteFile(IndexFileNames.SEGMENTS_GEN);
int expectedCount = 0;
for(int i=0;i<N+1;i++) {
try {
IndexReader reader = IndexReader.open(dir, true);
// Work backwards in commits on what the expected
// count should be.
searcher = newSearcher(reader);
hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals(expectedCount, hits.length);
searcher.close();
if (expectedCount == 0) {
expectedCount = 16;
} else if (expectedCount == 16) {
expectedCount = 17;
} else if (expectedCount == 17) {
expectedCount = 0;
}
reader.close();
if (i == N) {
fail("should have failed on commits before last " + N);
}
} catch (IOException e) {
if (i != N) {
throw e;
}
}
if (i < N) {
dir.deleteFile(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen));
}
gen--;
}
dir.close();
}
}
private void addDoc(IndexWriter writer) throws IOException
{
Document doc = new Document();
doc.add(newField("content", "aaa", Field.Store.NO, Field.Index.ANALYZED));
writer.addDocument(doc);
}
}
| false | true | public void testKeepLastNDeletionPolicyWithReader() throws IOException {
final int N = 10;
for(int pass=0;pass<2;pass++) {
boolean useCompoundFile = (pass % 2) != 0;
KeepLastNDeletionPolicy policy = new KeepLastNDeletionPolicy(N);
Directory dir = newDirectory();
IndexWriterConfig conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.CREATE).setIndexDeletionPolicy(policy).setMergePolicy(newLogMergePolicy());
MergePolicy mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexWriter writer = new IndexWriter(dir, conf);
writer.close();
Term searchTerm = new Term("content", "aaa");
Query query = new TermQuery(searchTerm);
for(int i=0;i<N+1;i++) {
if (VERBOSE) {
System.out.println("\nTEST: cycle i=" + i);
}
conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.APPEND).setIndexDeletionPolicy(policy);
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
writer = new IndexWriter(dir, conf);
for(int j=0;j<17;j++) {
addDoc(writer);
}
// this is a commit
if (VERBOSE) {
System.out.println("TEST: close writer");
}
writer.close();
IndexReader reader = IndexReader.open(dir, policy, false);
reader.deleteDocument(3*i+1);
reader.setNorm(4*i+1, "content", conf.getSimilarityProvider().get("content").encodeNormValue(2.0F));
IndexSearcher searcher = newSearcher(reader);
ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals(16*(1+i), hits.length);
// this is a commit
if (VERBOSE) {
System.out.println("TEST: close reader numOnCommit=" + policy.numOnCommit);
}
reader.close();
searcher.close();
}
conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.APPEND).setIndexDeletionPolicy(policy);
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexReader r = IndexReader.open(dir);
final boolean wasOptimized = r.isOptimized();
r.close();
writer = new IndexWriter(dir, conf);
writer.optimize();
// this is a commit
writer.close();
assertEquals(2*(N+1)+1, policy.numOnInit);
assertEquals(2*(N+2) - (wasOptimized ? 1:0), policy.numOnCommit);
IndexSearcher searcher = new IndexSearcher(dir, false);
ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals(176, hits.length);
// Simplistic check: just verify only the past N segments_N's still
// exist, and, I can open a reader on each:
long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
dir.deleteFile(IndexFileNames.SEGMENTS_GEN);
int expectedCount = 176;
searcher.close();
for(int i=0;i<N+1;i++) {
try {
IndexReader reader = IndexReader.open(dir, true);
// Work backwards in commits on what the expected
// count should be.
searcher = newSearcher(reader);
hits = searcher.search(query, null, 1000).scoreDocs;
if (i > 1) {
if (i % 2 == 0) {
expectedCount += 1;
} else {
expectedCount -= 17;
}
}
assertEquals(expectedCount, hits.length);
searcher.close();
reader.close();
if (i == N) {
fail("should have failed on commits before last 5");
}
} catch (IOException e) {
if (i != N) {
throw e;
}
}
if (i < N) {
dir.deleteFile(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen));
}
gen--;
}
dir.close();
}
}
| public void testKeepLastNDeletionPolicyWithReader() throws IOException {
final int N = 10;
for(int pass=0;pass<2;pass++) {
boolean useCompoundFile = (pass % 2) != 0;
KeepLastNDeletionPolicy policy = new KeepLastNDeletionPolicy(N);
Directory dir = newDirectory();
IndexWriterConfig conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.CREATE).setIndexDeletionPolicy(policy).setMergePolicy(newLogMergePolicy());
MergePolicy mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexWriter writer = new IndexWriter(dir, conf);
writer.close();
Term searchTerm = new Term("content", "aaa");
Query query = new TermQuery(searchTerm);
for(int i=0;i<N+1;i++) {
if (VERBOSE) {
System.out.println("\nTEST: cycle i=" + i);
}
conf = newIndexWriterConfig(
TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.APPEND).setIndexDeletionPolicy(policy).setMergePolicy(newLogMergePolicy());
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
writer = new IndexWriter(dir, conf);
writer.setInfoStream(VERBOSE ? System.out : null);
for(int j=0;j<17;j++) {
addDoc(writer);
}
// this is a commit
if (VERBOSE) {
System.out.println("TEST: close writer");
}
writer.close();
IndexReader reader = IndexReader.open(dir, policy, false);
reader.deleteDocument(3*i+1);
reader.setNorm(4*i+1, "content", conf.getSimilarityProvider().get("content").encodeNormValue(2.0F));
IndexSearcher searcher = newSearcher(reader);
ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals(16*(1+i), hits.length);
// this is a commit
if (VERBOSE) {
System.out.println("TEST: close reader numOnCommit=" + policy.numOnCommit);
}
reader.close();
searcher.close();
}
conf = newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random))
.setOpenMode(OpenMode.APPEND).setIndexDeletionPolicy(policy);
mp = conf.getMergePolicy();
if (mp instanceof LogMergePolicy) {
((LogMergePolicy) mp).setUseCompoundFile(useCompoundFile);
}
IndexReader r = IndexReader.open(dir);
final boolean wasOptimized = r.isOptimized();
r.close();
writer = new IndexWriter(dir, conf);
writer.optimize();
// this is a commit
writer.close();
assertEquals(2*(N+1)+1, policy.numOnInit);
assertEquals(2*(N+2) - (wasOptimized ? 1:0), policy.numOnCommit);
IndexSearcher searcher = new IndexSearcher(dir, false);
ScoreDoc[] hits = searcher.search(query, null, 1000).scoreDocs;
assertEquals(176, hits.length);
// Simplistic check: just verify only the past N segments_N's still
// exist, and, I can open a reader on each:
long gen = SegmentInfos.getCurrentSegmentGeneration(dir);
dir.deleteFile(IndexFileNames.SEGMENTS_GEN);
int expectedCount = 176;
searcher.close();
for(int i=0;i<N+1;i++) {
try {
IndexReader reader = IndexReader.open(dir, true);
// Work backwards in commits on what the expected
// count should be.
searcher = newSearcher(reader);
hits = searcher.search(query, null, 1000).scoreDocs;
if (i > 1) {
if (i % 2 == 0) {
expectedCount += 1;
} else {
expectedCount -= 17;
}
}
assertEquals(expectedCount, hits.length);
searcher.close();
reader.close();
if (i == N) {
fail("should have failed on commits before last 5");
}
} catch (IOException e) {
if (i != N) {
throw e;
}
}
if (i < N) {
dir.deleteFile(IndexFileNames.fileNameFromGeneration(IndexFileNames.SEGMENTS, "", gen));
}
gen--;
}
dir.close();
}
}
|
diff --git a/src/cz/muni/stanse/cppparser/CppUnit.java b/src/cz/muni/stanse/cppparser/CppUnit.java
index 6d13605..c10dc37 100644
--- a/src/cz/muni/stanse/cppparser/CppUnit.java
+++ b/src/cz/muni/stanse/cppparser/CppUnit.java
@@ -1,70 +1,70 @@
/* Distributed under GPLv2 */
package cz.muni.stanse.cppparser;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import cz.muni.stanse.Stanse;
import cz.muni.stanse.cfgparser.CfgUnit;
import cz.muni.stanse.codestructures.ParserException;
/**
* Holds all the code-related data for C++ compilation units (files).
*/
public class CppUnit extends CfgUnit {
private List<String> args = null;
public CppUnit(List<String> args) {
super(args);
this.args = args;
this.fileName = new File(args.get(0));
}
public void parse() throws ParserException {
String command = Stanse.getInstance().getRootDirectory()
+ File.separator + "bin" + File.separator + "cpp2sir";
List<String> parserArgs = new ArrayList<String>();
parserArgs.add(command);
parserArgs.add("-J");
parserArgs.addAll(args);
ProcessBuilder builder = new ProcessBuilder(parserArgs);
try {
final Process p = builder.start();
new Thread() {
public void run() {
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getErrorStream());
java.io.BufferedReader br = new java.io.BufferedReader(sr);
try {
String line = br.readLine();
while (line != null) {
System.err.println(line);
line = br.readLine();
}
br.close();
} catch (IOException ex) {
}
}
}.start();
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getInputStream());
JSONTokener jsonTokener = new JSONTokener(sr);
JSONObject jsonUnit = new JSONObject(jsonTokener);
- super.parseUnit(this.fileName.getParentFile(), jsonUnit);
+ super.parseUnit(new File(System.getProperty("user.dir")), jsonUnit);
} catch (IOException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
} catch (JSONException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
}
}
}
| true | true | public void parse() throws ParserException {
String command = Stanse.getInstance().getRootDirectory()
+ File.separator + "bin" + File.separator + "cpp2sir";
List<String> parserArgs = new ArrayList<String>();
parserArgs.add(command);
parserArgs.add("-J");
parserArgs.addAll(args);
ProcessBuilder builder = new ProcessBuilder(parserArgs);
try {
final Process p = builder.start();
new Thread() {
public void run() {
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getErrorStream());
java.io.BufferedReader br = new java.io.BufferedReader(sr);
try {
String line = br.readLine();
while (line != null) {
System.err.println(line);
line = br.readLine();
}
br.close();
} catch (IOException ex) {
}
}
}.start();
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getInputStream());
JSONTokener jsonTokener = new JSONTokener(sr);
JSONObject jsonUnit = new JSONObject(jsonTokener);
super.parseUnit(this.fileName.getParentFile(), jsonUnit);
} catch (IOException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
} catch (JSONException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
}
}
| public void parse() throws ParserException {
String command = Stanse.getInstance().getRootDirectory()
+ File.separator + "bin" + File.separator + "cpp2sir";
List<String> parserArgs = new ArrayList<String>();
parserArgs.add(command);
parserArgs.add("-J");
parserArgs.addAll(args);
ProcessBuilder builder = new ProcessBuilder(parserArgs);
try {
final Process p = builder.start();
new Thread() {
public void run() {
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getErrorStream());
java.io.BufferedReader br = new java.io.BufferedReader(sr);
try {
String line = br.readLine();
while (line != null) {
System.err.println(line);
line = br.readLine();
}
br.close();
} catch (IOException ex) {
}
}
}.start();
java.io.InputStreamReader sr = new java.io.InputStreamReader(
p.getInputStream());
JSONTokener jsonTokener = new JSONTokener(sr);
JSONObject jsonUnit = new JSONObject(jsonTokener);
super.parseUnit(new File(System.getProperty("user.dir")), jsonUnit);
} catch (IOException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
} catch (JSONException e) {
throw new ParserException("parser: " + e.getLocalizedMessage(), e);
}
}
|
diff --git a/gdms/src/main/java/org/gdms/model/FeatureCollectionModelUtils.java b/gdms/src/main/java/org/gdms/model/FeatureCollectionModelUtils.java
index 1527467f2..4b5ce2005 100644
--- a/gdms/src/main/java/org/gdms/model/FeatureCollectionModelUtils.java
+++ b/gdms/src/main/java/org/gdms/model/FeatureCollectionModelUtils.java
@@ -1,120 +1,118 @@
package org.gdms.model;
import java.util.Date;
import java.util.Iterator;
import org.gdms.data.metadata.DefaultMetadata;
import org.gdms.data.metadata.Metadata;
import org.gdms.data.types.Type;
import org.gdms.data.types.TypeFactory;
import org.gdms.data.values.Value;
import org.gdms.data.values.ValueFactory;
import org.gdms.driver.DriverException;
import org.gdms.driver.memory.ObjectMemoryDriver;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.MultiLineString;
import com.vividsolutions.jts.geom.MultiPoint;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
public class FeatureCollectionModelUtils {
public static Metadata getMetadata(FeatureSchema fs) throws DriverException {
DefaultMetadata metadata = new DefaultMetadata();
for (int i = 0; i < fs.getAttributeCount(); i++) {
metadata.addField(getFieldName(fs, i), getFieldType(fs, i));
}
return metadata;
}
public static String getFieldName(FeatureSchema fs, int fieldId)
throws DriverException {
return fs.getAttributeName(fieldId);
}
public static Type getFieldType(FeatureSchema fs, int i)
throws DriverException {
AttributeType at = fs.getAttributeType(i);
if (at == AttributeType.DATE) {
return TypeFactory.createType(Type.DATE);
} else if (at == AttributeType.DOUBLE) {
return TypeFactory.createType(Type.DOUBLE);
} else if (at == AttributeType.GEOMETRY) {
return TypeFactory.createType(Type.GEOMETRY);
} else if (at == AttributeType.INTEGER) {
return TypeFactory.createType(Type.INT);
} else if (at == AttributeType.STRING) {
return TypeFactory.createType(Type.STRING);
} else if (at == AttributeType.OBJECT) {
return TypeFactory.createType(Type.STRING);
}
throw new RuntimeException("OpenUMP attribute type unknow"); //$NON-NLS-1$
}
static Value[] getValues(Feature feature) {
FeatureSchema fs = feature.getSchema();
Value[] values = new Value[fs.getAttributeCount()];
for (int i = 0; i < feature.getAttributes().length; i++) {
Object o = feature.getAttribute(i);
if (o == null) {
values[i] = ValueFactory.createNullValue();
} else {
if (o instanceof Geometry) {
if (((Geometry) o).isEmpty()) {
values[i] = ValueFactory.createNullValue();
} else {
values[i] = ValueFactory.createValue((Geometry) o);
}
} else if (o instanceof Value) {
values[i] = (Value) o;
} else {
AttributeType at = fs.getAttributeType(i);
if (at == AttributeType.DATE) {
values[i] = ValueFactory.createValue((Date) o);
} else if (at == AttributeType.DOUBLE) {
values[i] = ValueFactory.createValue((Double) o);
} else if (at == AttributeType.INTEGER) {
values[i] = ValueFactory.createValue((Integer) o);
} else if (at == AttributeType.STRING) {
values[i] = ValueFactory.createValue((String) o);
} else if (at == AttributeType.OBJECT) {
values[i] = ValueFactory.createValue(o.toString());
}
- throw new RuntimeException(
- "OpenJUMP attribute type unknown");
}
}
}
return values;
}
public static ObjectMemoryDriver getObjectMemoryDriver(FeatureCollection fc)
throws DriverException {
ObjectMemoryDriver driver = new ObjectMemoryDriver(getMetadata(fc
.getFeatureSchema()));
Iterator iterator = fc.iterator();
for (Iterator ia = iterator; ia.hasNext();) {
Feature feature = (Feature) ia.next();
driver.addValues(FeatureCollectionModelUtils.getValues(feature));
}
return driver;
}
}
| true | true | static Value[] getValues(Feature feature) {
FeatureSchema fs = feature.getSchema();
Value[] values = new Value[fs.getAttributeCount()];
for (int i = 0; i < feature.getAttributes().length; i++) {
Object o = feature.getAttribute(i);
if (o == null) {
values[i] = ValueFactory.createNullValue();
} else {
if (o instanceof Geometry) {
if (((Geometry) o).isEmpty()) {
values[i] = ValueFactory.createNullValue();
} else {
values[i] = ValueFactory.createValue((Geometry) o);
}
} else if (o instanceof Value) {
values[i] = (Value) o;
} else {
AttributeType at = fs.getAttributeType(i);
if (at == AttributeType.DATE) {
values[i] = ValueFactory.createValue((Date) o);
} else if (at == AttributeType.DOUBLE) {
values[i] = ValueFactory.createValue((Double) o);
} else if (at == AttributeType.INTEGER) {
values[i] = ValueFactory.createValue((Integer) o);
} else if (at == AttributeType.STRING) {
values[i] = ValueFactory.createValue((String) o);
} else if (at == AttributeType.OBJECT) {
values[i] = ValueFactory.createValue(o.toString());
}
throw new RuntimeException(
"OpenJUMP attribute type unknown");
}
}
}
return values;
}
| static Value[] getValues(Feature feature) {
FeatureSchema fs = feature.getSchema();
Value[] values = new Value[fs.getAttributeCount()];
for (int i = 0; i < feature.getAttributes().length; i++) {
Object o = feature.getAttribute(i);
if (o == null) {
values[i] = ValueFactory.createNullValue();
} else {
if (o instanceof Geometry) {
if (((Geometry) o).isEmpty()) {
values[i] = ValueFactory.createNullValue();
} else {
values[i] = ValueFactory.createValue((Geometry) o);
}
} else if (o instanceof Value) {
values[i] = (Value) o;
} else {
AttributeType at = fs.getAttributeType(i);
if (at == AttributeType.DATE) {
values[i] = ValueFactory.createValue((Date) o);
} else if (at == AttributeType.DOUBLE) {
values[i] = ValueFactory.createValue((Double) o);
} else if (at == AttributeType.INTEGER) {
values[i] = ValueFactory.createValue((Integer) o);
} else if (at == AttributeType.STRING) {
values[i] = ValueFactory.createValue((String) o);
} else if (at == AttributeType.OBJECT) {
values[i] = ValueFactory.createValue(o.toString());
}
}
}
}
return values;
}
|
diff --git a/src/b/tree/BTree.java b/src/b/tree/BTree.java
index 0e95bc5..73934e3 100644
--- a/src/b/tree/BTree.java
+++ b/src/b/tree/BTree.java
@@ -1,335 +1,333 @@
package b.tree;
import java.util.Arrays;
import exception.NullFather;
import exception.PageFull;
public class BTree {
/** The root of this tree */
Page root;
/** A temporary 'pointer' to keep where is the key */
Page page; //pt
/** Order of the tree */
int order;
/** 2*order of the tree */
int doubleorder;
/** A boolean to indicate success or fail */
boolean found; //f
/** The position of the key in the page 'returned' by findB*/
int pos; //g
public BTree(int order) {
this.root = new Page(order);
this.order = order;
this.doubleorder = 2 * this.order;
}
/**
* Find a registry
* @param reg a registry to find
* @return a registry or null if it fails
*/
public Registry find(Registry reg)
{
return find(reg, this.root);
}
/**
* Find a registry recursively
* @param reg a registry to look for
* @param p a page where look for reg
* @return the registry or null if it was not found
*/
private Registry find(Registry reg, Page p)
{
// System.out.println("find(Registry " + reg + ", Page " + p + ")");
//Page not found!
if(p == null)
{
return null;
}
int i = 0;
//Get all registries from p
Registry pageregistries[] = p.getRegistries();
//Look for reg in pages of p until find a registry bigger then reg
while( (i < p.getNumRegs()) && (reg.compareTo(pageregistries[i]) > 0) )
{
/* It only walk through array pageregistries,
* until find a registry with key bigger or equal to reg
*/
i++;
}
//If reg was found! return the registry
if(reg.compareTo(pageregistries[i]) == 0)
{
return pageregistries[i];
}
//Other wise, go search in p[i]
else
{
// System.out.println("\tCalling recursively from p " + p.toString() + " to " + "p.getChild("+ i + ") " + p.getChild(i));
return find(reg, p.getChild(i));
}
}
/**
* Insert a registry into the B-tree
* @param reg a registry to insert
* @throws Exception
*/
public void insert(Registry reg) throws Exception
{
insert(reg, this.root);
}
/**
* Insert a registry into the B-tree recursively
* @param reg reg a registry to insert
* @param p the page where try to insert reg
* @throws Exception Registry already exist!
*/
public void insert(Registry reg, Page p) throws Exception
{
//This index will be used in all method
int i = 0;
//Keep the father of p
Page father = p;
//DEBUG
// System.out.println("insert(Registry " + reg + ", Page " + p.toString() + ")");
while(p != null)
{
//Searching where insert reg
for(i = 0; i < p.getNumRegs(); i++)
{
//If the registry to be inserted already exist, throws exception
if(reg.compareTo(p.getRegistry(i)) == 0)
{
throw new Exception(String.format("Registry with key " + reg.getKey() + " already exist!"));
}
//If it found a registry bigger then reg, so insert reg in page previous the bigger registry
else if(reg.compareTo(p.getRegistry(i)) > 0)
{
//Skip the loop to insert reg
break;
}
}
//If p is a Leaf, then try insert reg into p
if(p.isLeaf())
{
//DEBUG
// System.out.println("Page " + p.toString() + " is a leaf, inserting " + reg + " here");
father = p;
break;
}
//other wise, look for a leaf to insert reg
else
{
father = p;
p = p.getChild(i);
}
}
//Trying to insert, if the page is full, split it!
try
{
father.insertReg(reg);
//DEBUG
// System.out.println("After insert: " + father.toString());
}
catch(PageFull e)
{
//DEBUG
System.out.println("\nSplitting...");
split(father, reg);
}
}
/**
* Splits a page to insert a registry
* @param p a page to be split
* @param r the registry to insert
*/
//TODO: implement a split into a split
private void split(Page p, Registry r)
{
//Number of registries in a page + 1 */
int nregs = p.getOrder() * 2 + 1;
//To store registries from p and the new one
Registry[] regs = new Registry[nregs];
//The middle of regs
int middle = (int) Math.floor((nregs)/2f);
//The middle registry
Registry mreg = null;
//New pages that will be created
Page n1 = null, n2 = null;
//The p's father
Page father = p.getFather();
//DEBUG
System.out.print("Page.split(Page " + p.toString() + "Registry " + r.toString() + "): ");
System.out.print("nregs " + nregs + ", middle.index " + middle);
//Put all registries from p into regs
for(int i = 0; i < p.getNumRegs(); i++)
regs[i] = p.getRegistry(i);
//Put r in the last position of regs
regs[nregs - 1] = r;
//Sort regs
Arrays.sort(regs);
//DEBUG
System.out.println(", middle.value " + regs[middle]);
/* Creating new tow pages */
//Middle registry, it will go to page above
mreg = regs[middle];
//removing mreg from regs
regs[middle] = null;
//Sorting regs
Arrays.sort(regs, new CompareRegistries());
//Creating new pages, them father is the same as p
try {
- /* Erase all registries stored in p
- * they will be replaced
- */
+ // Erases all registries stored in p they will be replaced
p.eraseRegistries();
-// n1 = new Page(father);
+ //One of the new pages is the page p
n1 = p;
n2 = new Page(father);
-// father.insertPage(n1);
father.insertPage(n2);
}
/* If a NullFather was thrown,
* it means that p is the root of this tree!
* and it was thrown by 'n1 = new Page(p.getFather());',
* so n1 and n2 still being null!
* Then create a new root!
*/
catch (NullFather e1) {
//Creating a new root
Page newroot = new Page(p.getOrder());
/* Set variable 'father' to the father of new pages,
* it means, set 'father' as new root
*/
father = newroot;
try
{
- //Creating new pages with newroot as father
- n1 = new Page(newroot);
+ //Setting newroot as n1 father
+ n1.setFather(newroot);
+ //Creating new page with newroot as father
n2 = new Page(newroot);
//Putting new pages into new root
newroot.insertPage(n1);
newroot.insertPage(n2);
}
catch(PageFull e2)
{
e2.printStackTrace();
}
/* if it happens, newroot is null,
* so we have a big problem!
* Because it should never happens!
*/
catch (NullFather e) {
System.err.println("BTree.splitsplit(Page p, Registry r): newroot is null, it is a BIG problem!");
e.printStackTrace();
}
//Setting BTree.root as newroot
this.root = newroot;
} catch (PageFull e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Putting registries into new pages
try
{
for(int i = 0; i < middle; i++)
n1.insertReg(regs[i]);
for(int i = middle; i < nregs - 1; i++)
n2.insertReg(regs[i]);
}
catch (PageFull e)
{
System.err.println("Must slipt during a split!!!!");
System.out.println("TODO: IMPLEMENT IT!!");
System.err.flush();
e.printStackTrace();
System.exit(1);
}
/* Insert the middle registry into p.father
* if it was not possible, split father.
*/
try
{
father.insertReg(mreg);
}
catch(PageFull e)
{
System.err.println("Must slipt father during a split!!!!");
System.out.println("TODO: IMPLEMENT IT!!");
System.err.flush();
e.printStackTrace();
System.exit(1);
}
/*
* I do not remember why I caught NullPinterException...
* It was because I understood that it happened when
* the page that is been split is a root, but now
* it does not make sense...
*/
catch (NullPointerException e)
{
/*
//Creating a new root
Page newroot = new Page(p.getOrder());
this.root.setFather(newroot);
try
{
newroot.insertPage(n1);
newroot.insertPage(n2);
}
catch(PageFull e1)
{
e1.printStackTrace();
}*/
e.printStackTrace();
}catch (Exception e) {e.printStackTrace();}
//DEBUG
System.out.println("father: " + father.toString());
System.out.println("newpage1: " + n1.toString());
System.out.println("newpage2: " + n2.toString());
System.out.println();
}
/**
* Remove a registry
* @param reg a registry to remove
*/
public void removeReg(Registry reg) {
}
/**
* List all elements in-order
*/
public void listInOrder() {
}
public String toString()
{
return this.root.toStringChildren();
}
}
| false | true | private void split(Page p, Registry r)
{
//Number of registries in a page + 1 */
int nregs = p.getOrder() * 2 + 1;
//To store registries from p and the new one
Registry[] regs = new Registry[nregs];
//The middle of regs
int middle = (int) Math.floor((nregs)/2f);
//The middle registry
Registry mreg = null;
//New pages that will be created
Page n1 = null, n2 = null;
//The p's father
Page father = p.getFather();
//DEBUG
System.out.print("Page.split(Page " + p.toString() + "Registry " + r.toString() + "): ");
System.out.print("nregs " + nregs + ", middle.index " + middle);
//Put all registries from p into regs
for(int i = 0; i < p.getNumRegs(); i++)
regs[i] = p.getRegistry(i);
//Put r in the last position of regs
regs[nregs - 1] = r;
//Sort regs
Arrays.sort(regs);
//DEBUG
System.out.println(", middle.value " + regs[middle]);
/* Creating new tow pages */
//Middle registry, it will go to page above
mreg = regs[middle];
//removing mreg from regs
regs[middle] = null;
//Sorting regs
Arrays.sort(regs, new CompareRegistries());
//Creating new pages, them father is the same as p
try {
/* Erase all registries stored in p
* they will be replaced
*/
p.eraseRegistries();
// n1 = new Page(father);
n1 = p;
n2 = new Page(father);
// father.insertPage(n1);
father.insertPage(n2);
}
/* If a NullFather was thrown,
* it means that p is the root of this tree!
* and it was thrown by 'n1 = new Page(p.getFather());',
* so n1 and n2 still being null!
* Then create a new root!
*/
catch (NullFather e1) {
//Creating a new root
Page newroot = new Page(p.getOrder());
/* Set variable 'father' to the father of new pages,
* it means, set 'father' as new root
*/
father = newroot;
try
{
//Creating new pages with newroot as father
n1 = new Page(newroot);
n2 = new Page(newroot);
//Putting new pages into new root
newroot.insertPage(n1);
newroot.insertPage(n2);
}
catch(PageFull e2)
{
e2.printStackTrace();
}
/* if it happens, newroot is null,
* so we have a big problem!
* Because it should never happens!
*/
catch (NullFather e) {
System.err.println("BTree.splitsplit(Page p, Registry r): newroot is null, it is a BIG problem!");
e.printStackTrace();
}
//Setting BTree.root as newroot
this.root = newroot;
} catch (PageFull e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Putting registries into new pages
try
{
for(int i = 0; i < middle; i++)
n1.insertReg(regs[i]);
for(int i = middle; i < nregs - 1; i++)
n2.insertReg(regs[i]);
}
catch (PageFull e)
{
System.err.println("Must slipt during a split!!!!");
System.out.println("TODO: IMPLEMENT IT!!");
System.err.flush();
e.printStackTrace();
System.exit(1);
}
/* Insert the middle registry into p.father
* if it was not possible, split father.
*/
try
{
father.insertReg(mreg);
}
catch(PageFull e)
{
System.err.println("Must slipt father during a split!!!!");
System.out.println("TODO: IMPLEMENT IT!!");
System.err.flush();
e.printStackTrace();
System.exit(1);
}
/*
* I do not remember why I caught NullPinterException...
* It was because I understood that it happened when
* the page that is been split is a root, but now
* it does not make sense...
*/
catch (NullPointerException e)
{
/*
//Creating a new root
Page newroot = new Page(p.getOrder());
this.root.setFather(newroot);
try
{
newroot.insertPage(n1);
newroot.insertPage(n2);
}
catch(PageFull e1)
{
e1.printStackTrace();
}*/
e.printStackTrace();
}catch (Exception e) {e.printStackTrace();}
//DEBUG
System.out.println("father: " + father.toString());
System.out.println("newpage1: " + n1.toString());
System.out.println("newpage2: " + n2.toString());
System.out.println();
}
| private void split(Page p, Registry r)
{
//Number of registries in a page + 1 */
int nregs = p.getOrder() * 2 + 1;
//To store registries from p and the new one
Registry[] regs = new Registry[nregs];
//The middle of regs
int middle = (int) Math.floor((nregs)/2f);
//The middle registry
Registry mreg = null;
//New pages that will be created
Page n1 = null, n2 = null;
//The p's father
Page father = p.getFather();
//DEBUG
System.out.print("Page.split(Page " + p.toString() + "Registry " + r.toString() + "): ");
System.out.print("nregs " + nregs + ", middle.index " + middle);
//Put all registries from p into regs
for(int i = 0; i < p.getNumRegs(); i++)
regs[i] = p.getRegistry(i);
//Put r in the last position of regs
regs[nregs - 1] = r;
//Sort regs
Arrays.sort(regs);
//DEBUG
System.out.println(", middle.value " + regs[middle]);
/* Creating new tow pages */
//Middle registry, it will go to page above
mreg = regs[middle];
//removing mreg from regs
regs[middle] = null;
//Sorting regs
Arrays.sort(regs, new CompareRegistries());
//Creating new pages, them father is the same as p
try {
// Erases all registries stored in p they will be replaced
p.eraseRegistries();
//One of the new pages is the page p
n1 = p;
n2 = new Page(father);
father.insertPage(n2);
}
/* If a NullFather was thrown,
* it means that p is the root of this tree!
* and it was thrown by 'n1 = new Page(p.getFather());',
* so n1 and n2 still being null!
* Then create a new root!
*/
catch (NullFather e1) {
//Creating a new root
Page newroot = new Page(p.getOrder());
/* Set variable 'father' to the father of new pages,
* it means, set 'father' as new root
*/
father = newroot;
try
{
//Setting newroot as n1 father
n1.setFather(newroot);
//Creating new page with newroot as father
n2 = new Page(newroot);
//Putting new pages into new root
newroot.insertPage(n1);
newroot.insertPage(n2);
}
catch(PageFull e2)
{
e2.printStackTrace();
}
/* if it happens, newroot is null,
* so we have a big problem!
* Because it should never happens!
*/
catch (NullFather e) {
System.err.println("BTree.splitsplit(Page p, Registry r): newroot is null, it is a BIG problem!");
e.printStackTrace();
}
//Setting BTree.root as newroot
this.root = newroot;
} catch (PageFull e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Putting registries into new pages
try
{
for(int i = 0; i < middle; i++)
n1.insertReg(regs[i]);
for(int i = middle; i < nregs - 1; i++)
n2.insertReg(regs[i]);
}
catch (PageFull e)
{
System.err.println("Must slipt during a split!!!!");
System.out.println("TODO: IMPLEMENT IT!!");
System.err.flush();
e.printStackTrace();
System.exit(1);
}
/* Insert the middle registry into p.father
* if it was not possible, split father.
*/
try
{
father.insertReg(mreg);
}
catch(PageFull e)
{
System.err.println("Must slipt father during a split!!!!");
System.out.println("TODO: IMPLEMENT IT!!");
System.err.flush();
e.printStackTrace();
System.exit(1);
}
/*
* I do not remember why I caught NullPinterException...
* It was because I understood that it happened when
* the page that is been split is a root, but now
* it does not make sense...
*/
catch (NullPointerException e)
{
/*
//Creating a new root
Page newroot = new Page(p.getOrder());
this.root.setFather(newroot);
try
{
newroot.insertPage(n1);
newroot.insertPage(n2);
}
catch(PageFull e1)
{
e1.printStackTrace();
}*/
e.printStackTrace();
}catch (Exception e) {e.printStackTrace();}
//DEBUG
System.out.println("father: " + father.toString());
System.out.println("newpage1: " + n1.toString());
System.out.println("newpage2: " + n2.toString());
System.out.println();
}
|
diff --git a/KalenderProsjekt/src/framePackage/AppointmentOverView.java b/KalenderProsjekt/src/framePackage/AppointmentOverView.java
index 1fde168..4d15026 100644
--- a/KalenderProsjekt/src/framePackage/AppointmentOverView.java
+++ b/KalenderProsjekt/src/framePackage/AppointmentOverView.java
@@ -1,235 +1,241 @@
package framePackage;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import client.Program;
import data.Alarm;
import data.CalendarModel;
import data.Meeting;
import data.MeetingRoom;
import data.Notification;
import data.Person;
import data.Team;
public class AppointmentOverView {
private JFrame frame;
private JLabel headLine, lblMoreInfo, lblParticipant, lblInfo,
lblYourStatus, lblStatus;
private JList participantList;
private DefaultListModel listModel;
private JTextArea moreInfo;
private JComboBox<ImageIcon> yourStatus;
private JPanel overViewPanel;
private Meeting meeting;
private Person user;
private JButton change, delete;
private ImageIcon check, cross, question;
private List<Notification> notifications;
private Notification userNotification;
private NewAppointmentView newAppointment;
private CalendarModel calendarModel;
private Alarm alarm;
public AppointmentOverView(Meeting meeting) {
this.calendarModel = Program.calendarModel;
this.meeting = meeting;
this.user = calendarModel.getUser();
notifications = calendarModel.getAllNotificationsOfMeeting(meeting);
for (Notification n : notifications) {
if(n.getPerson().getUsername().equals(user.getUsername())) {
userNotification = n;
}
}
initialize();
}
private void initialize() {
check = new ImageIcon("res/icons/icon_check.png");
cross = new ImageIcon("res/icons/icon_cross.png");
question = new ImageIcon("res/icons/icon_question.png");
overViewPanel = new JPanel(new GridBagLayout());
overViewPanel.setPreferredSize(new Dimension(700, 450));
overViewPanel.setVisible(true);
GridBagConstraints c = new GridBagConstraints();
headLine = new JLabel(meeting.getTitle());
c.gridx = 0;
c.gridy = 0;
headLine.setPreferredSize(new Dimension(300, 25));
headLine.setFont(new Font(headLine.getFont().getName(),headLine.getFont().getStyle(), 20 ));
overViewPanel.add(headLine, c);
lblInfo = new JLabel(getTime() + " p� rom: " + getLoc());
c.gridx = 0;
c.gridy = 1;
lblInfo.setPreferredSize(new Dimension(300,25));
overViewPanel.add(lblInfo, c);
c.insets = new Insets(10,0,10,0);
lblMoreInfo = new JLabel("Beskrivelse:");
c.gridx = 0;
c.gridy = 2;
overViewPanel.add(lblMoreInfo, c);
lblParticipant = new JLabel("Deltakere:");
c.gridx = 0;
c.gridy = 3;
overViewPanel.add(lblParticipant, c);
lblYourStatus = new JLabel("Din status:");
c.gridx = 0;
c.gridy = 4;
overViewPanel.add(lblYourStatus, c);
change = new JButton("Endre avtale");
c.gridx = 0;
c.gridy = 5;
overViewPanel.add(change, c);
change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newAppointment = new NewAppointmentView(meeting);
frame.setVisible(false);
overViewPanel.setVisible(true);
}
});
delete = new JButton("Slett avtale");
c.gridx = 1;
c.gridy = 5;
overViewPanel.add(delete, c);
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
- //sett inn hva du skal sende her
+ calendarModel.removeMeeting(meeting.getMeetingID());
}
});
+ if(meeting.getCreator().getUsername() != calendarModel.getUser().getUsername()){
+ delete.setEnabled(false);
+ change.setEnabled(false);
+ }
yourStatus = new JComboBox<ImageIcon>();
yourStatus.addItem(check);
yourStatus.addItem(cross);
yourStatus.addItem(question);
c.gridx = 1;
c.gridy = 4;
overViewPanel.add(yourStatus, c);
c.gridx = 2;
c.gridy = 4;
lblStatus = new JLabel();
lblStatus.setPreferredSize(new Dimension(70, 25));
overViewPanel.add(lblStatus, c);
if (userNotification != null) {
if (userNotification.getApproved() == 'y') {
yourStatus.setSelectedItem(check);
lblStatus.setText("Deltar");
}
if (userNotification.getApproved() == 'n') {
yourStatus.setSelectedItem(cross);
lblStatus.setText("Deltar Ikke");
}
if (userNotification.getApproved() == 'w') {
yourStatus.setSelectedItem(question);
lblStatus.setText("Vet Ikke");
}
}
if(calendarModel.getUser().getUsername().equals(meeting.getCreator().getUsername()) ){
System.out.println(calendarModel.getUser().getUsername());
System.out.println(meeting.getCreator().getUsername());
yourStatus.setEnabled(false);
}
yourStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (yourStatus.getSelectedItem() == check) {
lblStatus.setText("Deltar");
- //skrive inn hvor du skal sende det til
+ calendarModel.setStatus('y',userNotification);
}
if (yourStatus.getSelectedItem() == cross) {
lblStatus.setText("Deltar Ikke");
+ calendarModel.setStatus('n',userNotification);
}
if (yourStatus.getSelectedItem() == question) {
lblStatus.setText("Ikke svart");
+ calendarModel.setStatus('w',userNotification);
}
}
});
moreInfo = new JTextArea(meeting.getDescription());
moreInfo.setEditable(false);
moreInfo.setFocusable(false);
moreInfo.setPreferredSize(new Dimension(320, 100));
c.gridx = 1;
c.gridy = 2;
overViewPanel.add(moreInfo, c);
listModel = new DefaultListModel();
for (int i = 0; i < notifications.size(); i++) {
listModel.addElement(notifications.get(i));
}
participantList = new JList<Notification>();
participantList.setModel(listModel);
participantList.setFixedCellWidth(300);
participantList.setCellRenderer(new overViewRender());
JScrollPane myJScrollPane = new JScrollPane(participantList);
myJScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
c.gridx = 1;
c.gridy = 3;
overViewPanel.add(myJScrollPane, c);
frame = new JFrame();
frame.setContentPane(overViewPanel);
frame.pack();
frame.setVisible(true);
}
private String getTime() {
GregorianCalendar cal = new GregorianCalendar();
GregorianCalendar cal2 = new GregorianCalendar();
cal.setTimeInMillis(meeting.getStartTime());
cal2.setTimeInMillis(meeting.getEndTime());
SimpleDateFormat spl1 = new SimpleDateFormat("dd.MMMM");
SimpleDateFormat spl2 = new SimpleDateFormat("HH:mm");
String time = spl1.format(cal.getTime()) + ". Fra kl "
+ spl2.format(cal.getTime()) + " til "
+ spl2.format(cal2.getTime());
return time;
}
private String getLoc() {
return meeting.getLocation();
}
public JPanel getPanel() {
return overViewPanel;
}
public void showFrame(){
frame.setVisible(true);
}
}
| false | true | private void initialize() {
check = new ImageIcon("res/icons/icon_check.png");
cross = new ImageIcon("res/icons/icon_cross.png");
question = new ImageIcon("res/icons/icon_question.png");
overViewPanel = new JPanel(new GridBagLayout());
overViewPanel.setPreferredSize(new Dimension(700, 450));
overViewPanel.setVisible(true);
GridBagConstraints c = new GridBagConstraints();
headLine = new JLabel(meeting.getTitle());
c.gridx = 0;
c.gridy = 0;
headLine.setPreferredSize(new Dimension(300, 25));
headLine.setFont(new Font(headLine.getFont().getName(),headLine.getFont().getStyle(), 20 ));
overViewPanel.add(headLine, c);
lblInfo = new JLabel(getTime() + " p� rom: " + getLoc());
c.gridx = 0;
c.gridy = 1;
lblInfo.setPreferredSize(new Dimension(300,25));
overViewPanel.add(lblInfo, c);
c.insets = new Insets(10,0,10,0);
lblMoreInfo = new JLabel("Beskrivelse:");
c.gridx = 0;
c.gridy = 2;
overViewPanel.add(lblMoreInfo, c);
lblParticipant = new JLabel("Deltakere:");
c.gridx = 0;
c.gridy = 3;
overViewPanel.add(lblParticipant, c);
lblYourStatus = new JLabel("Din status:");
c.gridx = 0;
c.gridy = 4;
overViewPanel.add(lblYourStatus, c);
change = new JButton("Endre avtale");
c.gridx = 0;
c.gridy = 5;
overViewPanel.add(change, c);
change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newAppointment = new NewAppointmentView(meeting);
frame.setVisible(false);
overViewPanel.setVisible(true);
}
});
delete = new JButton("Slett avtale");
c.gridx = 1;
c.gridy = 5;
overViewPanel.add(delete, c);
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//sett inn hva du skal sende her
}
});
yourStatus = new JComboBox<ImageIcon>();
yourStatus.addItem(check);
yourStatus.addItem(cross);
yourStatus.addItem(question);
c.gridx = 1;
c.gridy = 4;
overViewPanel.add(yourStatus, c);
c.gridx = 2;
c.gridy = 4;
lblStatus = new JLabel();
lblStatus.setPreferredSize(new Dimension(70, 25));
overViewPanel.add(lblStatus, c);
if (userNotification != null) {
if (userNotification.getApproved() == 'y') {
yourStatus.setSelectedItem(check);
lblStatus.setText("Deltar");
}
if (userNotification.getApproved() == 'n') {
yourStatus.setSelectedItem(cross);
lblStatus.setText("Deltar Ikke");
}
if (userNotification.getApproved() == 'w') {
yourStatus.setSelectedItem(question);
lblStatus.setText("Vet Ikke");
}
}
if(calendarModel.getUser().getUsername().equals(meeting.getCreator().getUsername()) ){
System.out.println(calendarModel.getUser().getUsername());
System.out.println(meeting.getCreator().getUsername());
yourStatus.setEnabled(false);
}
yourStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (yourStatus.getSelectedItem() == check) {
lblStatus.setText("Deltar");
//skrive inn hvor du skal sende det til
}
if (yourStatus.getSelectedItem() == cross) {
lblStatus.setText("Deltar Ikke");
}
if (yourStatus.getSelectedItem() == question) {
lblStatus.setText("Ikke svart");
}
}
});
moreInfo = new JTextArea(meeting.getDescription());
moreInfo.setEditable(false);
moreInfo.setFocusable(false);
moreInfo.setPreferredSize(new Dimension(320, 100));
c.gridx = 1;
c.gridy = 2;
overViewPanel.add(moreInfo, c);
listModel = new DefaultListModel();
for (int i = 0; i < notifications.size(); i++) {
listModel.addElement(notifications.get(i));
}
participantList = new JList<Notification>();
participantList.setModel(listModel);
participantList.setFixedCellWidth(300);
participantList.setCellRenderer(new overViewRender());
JScrollPane myJScrollPane = new JScrollPane(participantList);
myJScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
c.gridx = 1;
c.gridy = 3;
overViewPanel.add(myJScrollPane, c);
frame = new JFrame();
frame.setContentPane(overViewPanel);
frame.pack();
frame.setVisible(true);
}
| private void initialize() {
check = new ImageIcon("res/icons/icon_check.png");
cross = new ImageIcon("res/icons/icon_cross.png");
question = new ImageIcon("res/icons/icon_question.png");
overViewPanel = new JPanel(new GridBagLayout());
overViewPanel.setPreferredSize(new Dimension(700, 450));
overViewPanel.setVisible(true);
GridBagConstraints c = new GridBagConstraints();
headLine = new JLabel(meeting.getTitle());
c.gridx = 0;
c.gridy = 0;
headLine.setPreferredSize(new Dimension(300, 25));
headLine.setFont(new Font(headLine.getFont().getName(),headLine.getFont().getStyle(), 20 ));
overViewPanel.add(headLine, c);
lblInfo = new JLabel(getTime() + " p� rom: " + getLoc());
c.gridx = 0;
c.gridy = 1;
lblInfo.setPreferredSize(new Dimension(300,25));
overViewPanel.add(lblInfo, c);
c.insets = new Insets(10,0,10,0);
lblMoreInfo = new JLabel("Beskrivelse:");
c.gridx = 0;
c.gridy = 2;
overViewPanel.add(lblMoreInfo, c);
lblParticipant = new JLabel("Deltakere:");
c.gridx = 0;
c.gridy = 3;
overViewPanel.add(lblParticipant, c);
lblYourStatus = new JLabel("Din status:");
c.gridx = 0;
c.gridy = 4;
overViewPanel.add(lblYourStatus, c);
change = new JButton("Endre avtale");
c.gridx = 0;
c.gridy = 5;
overViewPanel.add(change, c);
change.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newAppointment = new NewAppointmentView(meeting);
frame.setVisible(false);
overViewPanel.setVisible(true);
}
});
delete = new JButton("Slett avtale");
c.gridx = 1;
c.gridy = 5;
overViewPanel.add(delete, c);
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calendarModel.removeMeeting(meeting.getMeetingID());
}
});
if(meeting.getCreator().getUsername() != calendarModel.getUser().getUsername()){
delete.setEnabled(false);
change.setEnabled(false);
}
yourStatus = new JComboBox<ImageIcon>();
yourStatus.addItem(check);
yourStatus.addItem(cross);
yourStatus.addItem(question);
c.gridx = 1;
c.gridy = 4;
overViewPanel.add(yourStatus, c);
c.gridx = 2;
c.gridy = 4;
lblStatus = new JLabel();
lblStatus.setPreferredSize(new Dimension(70, 25));
overViewPanel.add(lblStatus, c);
if (userNotification != null) {
if (userNotification.getApproved() == 'y') {
yourStatus.setSelectedItem(check);
lblStatus.setText("Deltar");
}
if (userNotification.getApproved() == 'n') {
yourStatus.setSelectedItem(cross);
lblStatus.setText("Deltar Ikke");
}
if (userNotification.getApproved() == 'w') {
yourStatus.setSelectedItem(question);
lblStatus.setText("Vet Ikke");
}
}
if(calendarModel.getUser().getUsername().equals(meeting.getCreator().getUsername()) ){
System.out.println(calendarModel.getUser().getUsername());
System.out.println(meeting.getCreator().getUsername());
yourStatus.setEnabled(false);
}
yourStatus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (yourStatus.getSelectedItem() == check) {
lblStatus.setText("Deltar");
calendarModel.setStatus('y',userNotification);
}
if (yourStatus.getSelectedItem() == cross) {
lblStatus.setText("Deltar Ikke");
calendarModel.setStatus('n',userNotification);
}
if (yourStatus.getSelectedItem() == question) {
lblStatus.setText("Ikke svart");
calendarModel.setStatus('w',userNotification);
}
}
});
moreInfo = new JTextArea(meeting.getDescription());
moreInfo.setEditable(false);
moreInfo.setFocusable(false);
moreInfo.setPreferredSize(new Dimension(320, 100));
c.gridx = 1;
c.gridy = 2;
overViewPanel.add(moreInfo, c);
listModel = new DefaultListModel();
for (int i = 0; i < notifications.size(); i++) {
listModel.addElement(notifications.get(i));
}
participantList = new JList<Notification>();
participantList.setModel(listModel);
participantList.setFixedCellWidth(300);
participantList.setCellRenderer(new overViewRender());
JScrollPane myJScrollPane = new JScrollPane(participantList);
myJScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
c.gridx = 1;
c.gridy = 3;
overViewPanel.add(myJScrollPane, c);
frame = new JFrame();
frame.setContentPane(overViewPanel);
frame.pack();
frame.setVisible(true);
}
|
diff --git a/search-impl/impl/src/java/org/sakaiproject/search/component/dao/impl/SearchIndexBuilderWorkerDaoImpl.java b/search-impl/impl/src/java/org/sakaiproject/search/component/dao/impl/SearchIndexBuilderWorkerDaoImpl.java
index 6bed39be..b4db5e19 100644
--- a/search-impl/impl/src/java/org/sakaiproject/search/component/dao/impl/SearchIndexBuilderWorkerDaoImpl.java
+++ b/search-impl/impl/src/java/org/sakaiproject/search/component/dao/impl/SearchIndexBuilderWorkerDaoImpl.java
@@ -1,979 +1,979 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 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.search.component.dao.impl;
import java.io.IOException;
import java.io.Reader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.type.Type;
import org.sakaiproject.component.api.ComponentManager;
import org.sakaiproject.component.cover.ServerConfigurationService;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.EntityManager;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.event.api.EventTrackingService;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.search.api.EntityContentProducer;
import org.sakaiproject.search.api.SearchIndexBuilder;
import org.sakaiproject.search.api.SearchIndexBuilderWorker;
import org.sakaiproject.search.api.SearchService;
import org.sakaiproject.search.api.rdf.RDFIndexException;
import org.sakaiproject.search.api.rdf.RDFSearchService;
import org.sakaiproject.search.dao.SearchIndexBuilderWorkerDao;
import org.sakaiproject.search.index.IndexStorage;
import org.sakaiproject.search.model.SearchBuilderItem;
import org.sakaiproject.search.model.impl.SearchBuilderItemImpl;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class SearchIndexBuilderWorkerDaoImpl extends HibernateDaoSupport
implements SearchIndexBuilderWorkerDao
{
private static Log log = LogFactory
.getLog(SearchIndexBuilderWorkerDaoImpl.class);
/**
* sync object
*/
// private Object threadStartLock = new Object();
/**
* dependency: the search index builder that is accepting new items
*/
private SearchIndexBuilder searchIndexBuilder = null;
/**
* The number of items to process in a batch, default = 100
*/
private int indexBatchSize = 100;
private boolean enabled = false;
private EntityManager entityManager;
private EventTrackingService eventTrackingService;
private RDFSearchService rdfSearchService = null;
/**
* injected to abstract the storage impl
*/
private IndexStorage indexStorage = null;
public void init()
{
ComponentManager cm = org.sakaiproject.component.cover.ComponentManager
.getInstance();
eventTrackingService = (EventTrackingService) load(cm,
EventTrackingService.class.getName(),true);
entityManager = (EntityManager) load(cm, EntityManager.class.getName(),true);
searchIndexBuilder = (SearchIndexBuilder) load(cm,
SearchIndexBuilder.class.getName(),true);
rdfSearchService = (RDFSearchService) load(cm, RDFSearchService.class.getName(),false);
enabled = "true".equals(ServerConfigurationService.getString(
"search.experimental", "true"));
try
{
if (searchIndexBuilder == null)
{
log.error("Search Index Worker needs searchIndexBuilder ");
}
if (eventTrackingService == null)
{
log.error("Search Index Worker needs EventTrackingService ");
}
if (entityManager == null)
{
log.error("Search Index Worker needs EntityManager ");
}
if (indexStorage == null)
{
log.error("Search Index Worker needs indexStorage ");
}
if (rdfSearchService == null)
{
log.info("No RDFSearchService has been defined, RDF Indexing not enabled");
} else {
log.warn("Experimental RDF Search Service is enabled using implementation "+rdfSearchService);
}
}
catch (Throwable t)
{
log.error("Failed to init ", t);
}
}
private Object load(ComponentManager cm, String name, boolean aserror)
{
Object o = cm.get(name);
if (o == null)
{
if ( aserror ) {
log.error("Cant find Spring component named " + name);
}
}
return o;
}
/*
* (non-Javadoc)
*
* @see org.sakaiproject.search.component.dao.impl.SearchIndexBuilderWorkerDao#processToDoListTransaction()
*/
public void processToDoListTransaction(final SearchIndexBuilderWorker worker)
{
long startTime = System.currentTimeMillis();
HibernateCallback callback = new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
int totalDocs = 0;
try
{
IndexWriter indexWrite = null;
// Load the list
List runtimeToDo = findPending(indexBatchSize, session);
totalDocs = runtimeToDo.size();
log.debug("Processing " + totalDocs + " documents");
if (totalDocs > 0)
{
try
{
indexStorage.doPreIndexUpdate();
if (indexStorage.indexExists())
{
IndexReader indexReader = null;
try
{
indexReader = indexStorage.getIndexReader();
// Open the index
for (Iterator tditer = runtimeToDo
.iterator(); worker.isRunning()
&& tditer.hasNext();)
{
SearchBuilderItem sbi = (SearchBuilderItem) tditer
.next();
if (!SearchBuilderItem.STATE_PENDING
.equals(sbi.getSearchstate()))
{
// should only be getting pending
// items
log
.warn(" Found Item that was not pending "
+ sbi.getName());
continue;
}
if (SearchBuilderItem.ACTION_UNKNOWN
.equals(sbi.getSearchaction()))
{
sbi
.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
continue;
}
// remove document
try
{
indexReader
.deleteDocuments(new Term(
SearchService.FIELD_REFERENCE,
sbi.getName()));
if (SearchBuilderItem.ACTION_DELETE
.equals(sbi
.getSearchaction()))
{
sbi
.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
}
else
{
sbi
.setSearchstate(SearchBuilderItem.STATE_PENDING_2);
}
}
catch (IOException ex)
{
log.warn("Failed to delete Page ",
ex);
}
}
}
finally
{
if (indexReader != null)
{
indexReader.close();
indexReader = null;
}
}
if (worker.isRunning())
{
indexWrite = indexStorage
.getIndexWriter(false);
}
}
else
{
// create for update
if (worker.isRunning())
{
indexWrite = indexStorage
.getIndexWriter(true);
}
}
for (Iterator tditer = runtimeToDo.iterator(); worker
.isRunning()
&& tditer.hasNext();)
{
Reader contentReader = null;
try
{
SearchBuilderItem sbi = (SearchBuilderItem) tditer
.next();
// only add adds, that have been deleted
// sucessfully
if (!SearchBuilderItem.STATE_PENDING_2
.equals(sbi.getSearchstate()))
{
continue;
}
Reference ref = entityManager
.newReference(sbi.getName());
if (ref == null)
{
log
.error("Unrecognised trigger object presented to index builder "
+ sbi);
}
- Entity entity = ref.getEntity();
try
{
+ Entity entity = ref.getEntity();
EntityContentProducer sep = searchIndexBuilder
.newEntityContentProducer(ref);
if (sep != null && sep.isForIndex(ref) && ref.getContext() != null)
{
Document doc = new Document();
String container = ref
.getContainer();
if (container == null)
container = "";
doc
.add(new Field(
SearchService.DATE_STAMP,
String.valueOf(System.currentTimeMillis()),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_CONTAINER,
container,
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field(
SearchService.FIELD_ID, ref
.getId(),
Field.Store.YES,
Field.Index.NO));
doc.add(new Field(
SearchService.FIELD_TYPE,
ref.getType(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_SUBTYPE,
ref.getSubType(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_REFERENCE,
ref.getReference(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_CONTEXT,
sep.getSiteId(ref),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
if (sep.isContentFromReader(entity))
{
contentReader = sep
.getContentReader(entity);
doc
.add(new Field(
SearchService.FIELD_CONTENTS,
contentReader,
Field.TermVector.YES));
}
else
{
doc
.add(new Field(
SearchService.FIELD_CONTENTS,
sep
.getContent(entity),
Field.Store.YES,
Field.Index.TOKENIZED,
Field.TermVector.YES));
}
doc.add(new Field(
SearchService.FIELD_TITLE,
sep.getTitle(entity),
Field.Store.YES,
Field.Index.TOKENIZED,
Field.TermVector.YES));
doc.add(new Field(
SearchService.FIELD_TOOL,
sep.getTool(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field(
SearchService.FIELD_URL,
sep.getUrl(entity),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field(
SearchService.FIELD_SITEID,
sep.getSiteId(ref),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
// add the custom properties
Map m = sep.getCustomProperties();
if (m != null)
{
for (Iterator cprops = m
.keySet().iterator(); cprops
.hasNext();)
{
String key = (String) cprops
.next();
Object value = m.get(key);
String[] values = null;
if (value instanceof String)
{
values = new String[1];
values[0] = (String) value;
}
if (value instanceof String[])
{
values = (String[]) value;
}
if (values == null)
{
log
.info("Null Custom Properties value has been suppled by "
+ sep
+ " in index "
+ key);
}
else
{
for (int i = 0; i < values.length; i++)
{
doc
.add(new Field(
key,
values[i],
Field.Store.YES,
Field.Index.UN_TOKENIZED));
}
}
}
}
log.debug("Indexing Document "
+ doc);
indexWrite.addDocument(doc);
log.debug("Done Indexing Document "
+ doc);
processRDF(sep);
}
else
{
log.debug("Ignored Document "
+ ref.getId());
}
sbi
.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
}
catch (Exception e1)
{
log
.debug(" Failed to index document cause: "
+ e1.getMessage());
}
// update this node lock to indicate its
// still alove, no document should
// take more than 2 mins to process
worker.updateNodeLock();
}
finally
{
if (contentReader != null)
{
try
{
contentReader.close();
}
catch (IOException ioex)
{
}
}
}
}
}
finally
{
if (indexWrite != null)
{
indexWrite.close();
indexWrite = null;
}
}
totalDocs = 0;
try
{
for (Iterator tditer = runtimeToDo.iterator(); worker
.isRunning()
&& tditer.hasNext();)
{
SearchBuilderItem sbi = (SearchBuilderItem) tditer
.next();
if (SearchBuilderItem.STATE_COMPLETED
.equals(sbi.getSearchstate()))
{
if (SearchBuilderItem.ACTION_DELETE
.equals(sbi.getSearchaction()))
{
session.delete(sbi);
}
else
{
session.saveOrUpdate(sbi);
}
}
}
session.flush();
totalDocs = runtimeToDo.size();
}
catch (Exception ex)
{
log
.warn("Failed to update state in database due to "
+ ex.getMessage()
+ " this will be corrected on the next run of the IndexBuilder, no cause for alarm");
}
}
return new Integer(totalDocs);
}
catch (IOException ex)
{
throw new HibernateException(" Failed to create index ", ex);
}
}
};
int totalDocs = 0;
if (worker.isRunning())
{
Integer nprocessed = (Integer) getHibernateTemplate().execute(
callback);
if (nprocessed == null)
{
return;
}
totalDocs = nprocessed.intValue();
}
try
{
indexStorage.doPostIndexUpdate();
}
catch (IOException e)
{
log.error("Failed to do Post Index Update", e);
}
if (worker.isRunning())
{
eventTrackingService.post(eventTrackingService.newEvent(
SearchService.EVENT_TRIGGER_INDEX_RELOAD,
"/searchindexreload", true,
NotificationService.PREF_IMMEDIATE));
long endTime = System.currentTimeMillis();
float totalTime = endTime - startTime;
float ndocs = totalDocs;
if (totalDocs > 0)
{
float docspersec = 1000 * ndocs / totalTime;
log.info("Completed Process List of " + totalDocs + " at "
+ docspersec + " documents/per second");
}
}
}
private void processRDF(EntityContentProducer sep) throws RDFIndexException
{
if ( rdfSearchService != null ) {
String s = sep.getCustomRDF();
if ( s != null ) {
rdfSearchService.addData(s);
}
}
}
/**
* Gets a list of all SiteMasterItems
*
* @return
* @throws HibernateException
*/
private List getSiteMasterItems(Session session) throws HibernateException
{
log.debug("Site Master Items with " + session);
List masterList = (List) session.createCriteria(
SearchBuilderItemImpl.class).add(
Expression.like("name", SearchBuilderItem.SITE_MASTER_PATTERN))
.add(
Expression.not(Expression.eq("context",
SearchBuilderItem.GLOBAL_CONTEXT))).list();
if (masterList == null || masterList.size() == 0)
{
return new ArrayList();
}
else
{
return masterList;
}
}
/**
* get the Instance Master
*
* @return
* @throws HibernateException
*/
private SearchBuilderItem getMasterItem(Session session)
throws HibernateException
{
log.debug("get Master Items with " + session);
List master = (List) session
.createCriteria(SearchBuilderItemImpl.class).add(
Expression.eq("name", SearchBuilderItem.GLOBAL_MASTER))
.list();
if (master != null && master.size() != 0)
{
return (SearchBuilderItem) master.get(0);
}
SearchBuilderItem sbi = new SearchBuilderItemImpl();
sbi.setName(SearchBuilderItem.INDEX_MASTER);
sbi.setContext(SearchBuilderItem.GLOBAL_CONTEXT);
sbi.setSearchaction(SearchBuilderItem.ACTION_UNKNOWN);
sbi.setSearchstate(SearchBuilderItem.STATE_UNKNOWN);
return sbi;
}
/**
* get the action for the site master
*
* @param siteMaster
* @return
*/
private Integer getSiteMasterAction(SearchBuilderItem siteMaster)
{
if (siteMaster.getName().startsWith(SearchBuilderItem.INDEX_MASTER)
&& !SearchBuilderItem.GLOBAL_CONTEXT.equals(siteMaster
.getContext()))
{
if (SearchBuilderItem.STATE_PENDING.equals(siteMaster
.getSearchstate()))
{
return siteMaster.getSearchaction();
}
}
return SearchBuilderItem.STATE_UNKNOWN;
}
/**
* Get the site that the siteMaster references
*
* @param siteMaster
* @return
*/
private String getSiteMasterSite(SearchBuilderItem siteMaster)
{
if (siteMaster.getName().startsWith(SearchBuilderItem.INDEX_MASTER)
&& !SearchBuilderItem.GLOBAL_CONTEXT.equals(siteMaster
.getContext()))
{
// this depends on the pattern, perhapse it should be a parse
return siteMaster.getName().substring(
SearchBuilderItem.INDEX_MASTER.length() + 1);
}
return null;
}
/**
* get the action of the master item
*
* @return
*/
private Integer getMasterAction(Session session) throws HibernateException
{
return getMasterAction(getMasterItem(session));
}
/**
* get the master action of known master item
*
* @param master
* @return
*/
private Integer getMasterAction(SearchBuilderItem master)
{
if (master.getName().equals(SearchBuilderItem.GLOBAL_MASTER))
{
if (SearchBuilderItem.STATE_PENDING.equals(master.getSearchstate()))
{
return master.getSearchaction();
}
}
return SearchBuilderItem.STATE_UNKNOWN;
}
/**
* get the next x pending items If there is a master record with index
* refresh, the list will come back with only items existing before the
* index refresh was requested, those requested after the index refresh will
* be processed once the refresh has been completed. If a rebuild is
* request, then the index queue will be deleted, and all the
* entitiescontentproviders polled to get all their entities
*
* @return
* @throws HibernateException
*/
private List findPending(int batchSize, Session session)
throws HibernateException
{
// Pending is the first 100 items
// State == PENDING
// Action != Unknown
long start = System.currentTimeMillis();
try
{
log.debug("TXFind pending with " + session);
SearchBuilderItem masterItem = getMasterItem(session);
Integer masterAction = getMasterAction(masterItem);
log.debug(" Master Item is " + masterItem.getName() + ":"
+ masterItem.getSearchaction() + ":"
+ masterItem.getSearchstate() + "::"
+ masterItem.getVersion());
if (SearchBuilderItem.ACTION_REFRESH.equals(masterAction))
{
log.debug(" Master Action is " + masterAction);
log.debug(" REFRESH = " + SearchBuilderItem.ACTION_REFRESH);
log.debug(" RELOAD = " + SearchBuilderItem.ACTION_REBUILD);
// get a complete list of all items, before the master
// action version
// if there are none, update the master action action to
// completed
// and return a blank list
refreshIndex(session, masterItem);
}
else if (SearchBuilderItem.ACTION_REBUILD.equals(masterAction))
{
rebuildIndex(session, masterItem);
}
else
{
// get all site masters and perform the required action.
List siteMasters = getSiteMasterItems(session);
for (Iterator i = siteMasters.iterator(); i.hasNext();)
{
SearchBuilderItem siteMaster = (SearchBuilderItem) i.next();
Integer action = getSiteMasterAction(siteMaster);
if (SearchBuilderItem.ACTION_REBUILD.equals(action))
{
rebuildIndex(session, siteMaster);
}
else if (SearchBuilderItem.ACTION_REFRESH.equals(action))
{
refreshIndex(session, siteMaster);
}
}
}
return session.createCriteria(SearchBuilderItemImpl.class).add(
Expression.eq("searchstate",
SearchBuilderItem.STATE_PENDING)).add(
Expression.not(Expression.eq("searchaction",
SearchBuilderItem.ACTION_UNKNOWN))).add(
Expression.not(Expression.like("name",
SearchBuilderItem.SITE_MASTER_PATTERN))).addOrder(
Order.asc("version")).setMaxResults(batchSize).list();
}
finally
{
long finish = System.currentTimeMillis();
log.debug(" findPending took " + (finish - start) + " ms");
}
}
public int countPending()
{
HibernateCallback callback = new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
List l = session
.createQuery(
"select count(*) from "
+ SearchBuilderItemImpl.class.getName()
+ " where searchstate = ? and searchaction <> ?")
.setParameters(
new Object[] { SearchBuilderItem.STATE_PENDING,
SearchBuilderItem.ACTION_UNKNOWN },
new Type[] { Hibernate.INTEGER,
Hibernate.INTEGER }).list();
if (l == null || l.size() == 0)
{
return new Integer(0);
}
else
{
log.debug("Found " + l.get(0) + " Pending Documents ");
return l.get(0);
}
}
};
Integer np = (Integer) getHibernateTemplate().execute(callback);
return np.intValue();
}
private void rebuildIndex(Session session, SearchBuilderItem controlItem)
throws HibernateException
{
// delete all and return the master action only
// the caller will then rebuild the index from scratch
log
.debug("DELETE ALL RECORDS ==========================================================");
session.flush();
try
{
if (SearchBuilderItem.GLOBAL_CONTEXT.equals(controlItem
.getContext()))
{
session.connection().createStatement().execute(
"delete from searchbuilderitem where name <> '"
+ SearchBuilderItem.GLOBAL_MASTER + "' ");
}
else
{
session.connection().createStatement().execute(
"delete from searchbuilderitem where context = '"
+ controlItem.getContext() + "' and name <> '"
+ controlItem.getName() + "' ");
}
}
catch (SQLException e)
{
throw new HibernateException("Failed to perform delete ", e);
}
// THIS DOES NOT WORK IN H 2.1 session.delete("from
// "+SearchBuilderItemImpl.class.getName());
log
.debug("DONE DELETE ALL RECORDS ===========================================================");
log
.debug("ADD ALL RECORDS ===========================================================");
for (Iterator i = searchIndexBuilder.getContentProducers().iterator(); i
.hasNext();)
{
EntityContentProducer ecp = (EntityContentProducer) i.next();
List contentList = null;
if (SearchBuilderItem.GLOBAL_CONTEXT.equals(controlItem
.getContext()))
{
contentList = ecp.getAllContent();
}
else
{
contentList = ecp.getSiteContent(controlItem.getContext());
}
int added = 0;
for (Iterator ci = contentList.iterator(); ci.hasNext();)
{
String resourceName = (String) ci.next();
List lx = session.createQuery(
" from " + SearchBuilderItemImpl.class.getName()
+ " where name = ? ").setParameter(0,
resourceName, Hibernate.STRING).list();
if (lx == null || lx.size() == 0)
{
added++;
SearchBuilderItem sbi = new SearchBuilderItemImpl();
sbi.setName(resourceName);
sbi.setSearchaction(SearchBuilderItem.ACTION_ADD);
sbi.setSearchstate(SearchBuilderItem.STATE_PENDING);
String context = ecp.getSiteId(resourceName);
if ( context == null || context.length() == 0 ) {
context = "none";
}
sbi.setContext(context);
session.saveOrUpdate(sbi);
}
}
log.debug(" Added " + added);
}
log
.debug("DONE ADD ALL RECORDS ===========================================================");
controlItem.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
session.saveOrUpdate(controlItem);
}
private void refreshIndex(Session session, SearchBuilderItem controlItem)
throws HibernateException
{
// delete all and return the master action only
// the caller will then rebuild the index from scratch
log
.debug("UPDATE ALL RECORDS ==========================================================");
session.flush();
try
{
if (SearchBuilderItem.GLOBAL_CONTEXT.equals(controlItem
.getContext()))
{
session.connection().createStatement().execute(
"update searchbuilderitem set searchstate = "
+ SearchBuilderItem.STATE_PENDING
+ " where name not like '"
+ SearchBuilderItem.SITE_MASTER_PATTERN
+ "' and name <> '"
+ SearchBuilderItem.GLOBAL_MASTER + "' ");
}
else
{
session.connection().createStatement().execute(
"update searchbuilderitem set searchstate = "
+ SearchBuilderItem.STATE_PENDING
+ " where context = '"
+ controlItem.getContext() + "' and name <> '"
+ controlItem.getName() + "'");
}
}
catch (SQLException e)
{
throw new HibernateException("Failed to perform delete ", e);
}
controlItem.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
session.saveOrUpdate(controlItem);
}
/**
* @return Returns the indexStorage.
*/
public IndexStorage getIndexStorage()
{
return indexStorage;
}
/**
* @param indexStorage
* The indexStorage to set.
*/
public void setIndexStorage(IndexStorage indexStorage)
{
this.indexStorage = indexStorage;
}
}
| false | true | public void processToDoListTransaction(final SearchIndexBuilderWorker worker)
{
long startTime = System.currentTimeMillis();
HibernateCallback callback = new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
int totalDocs = 0;
try
{
IndexWriter indexWrite = null;
// Load the list
List runtimeToDo = findPending(indexBatchSize, session);
totalDocs = runtimeToDo.size();
log.debug("Processing " + totalDocs + " documents");
if (totalDocs > 0)
{
try
{
indexStorage.doPreIndexUpdate();
if (indexStorage.indexExists())
{
IndexReader indexReader = null;
try
{
indexReader = indexStorage.getIndexReader();
// Open the index
for (Iterator tditer = runtimeToDo
.iterator(); worker.isRunning()
&& tditer.hasNext();)
{
SearchBuilderItem sbi = (SearchBuilderItem) tditer
.next();
if (!SearchBuilderItem.STATE_PENDING
.equals(sbi.getSearchstate()))
{
// should only be getting pending
// items
log
.warn(" Found Item that was not pending "
+ sbi.getName());
continue;
}
if (SearchBuilderItem.ACTION_UNKNOWN
.equals(sbi.getSearchaction()))
{
sbi
.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
continue;
}
// remove document
try
{
indexReader
.deleteDocuments(new Term(
SearchService.FIELD_REFERENCE,
sbi.getName()));
if (SearchBuilderItem.ACTION_DELETE
.equals(sbi
.getSearchaction()))
{
sbi
.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
}
else
{
sbi
.setSearchstate(SearchBuilderItem.STATE_PENDING_2);
}
}
catch (IOException ex)
{
log.warn("Failed to delete Page ",
ex);
}
}
}
finally
{
if (indexReader != null)
{
indexReader.close();
indexReader = null;
}
}
if (worker.isRunning())
{
indexWrite = indexStorage
.getIndexWriter(false);
}
}
else
{
// create for update
if (worker.isRunning())
{
indexWrite = indexStorage
.getIndexWriter(true);
}
}
for (Iterator tditer = runtimeToDo.iterator(); worker
.isRunning()
&& tditer.hasNext();)
{
Reader contentReader = null;
try
{
SearchBuilderItem sbi = (SearchBuilderItem) tditer
.next();
// only add adds, that have been deleted
// sucessfully
if (!SearchBuilderItem.STATE_PENDING_2
.equals(sbi.getSearchstate()))
{
continue;
}
Reference ref = entityManager
.newReference(sbi.getName());
if (ref == null)
{
log
.error("Unrecognised trigger object presented to index builder "
+ sbi);
}
Entity entity = ref.getEntity();
try
{
EntityContentProducer sep = searchIndexBuilder
.newEntityContentProducer(ref);
if (sep != null && sep.isForIndex(ref) && ref.getContext() != null)
{
Document doc = new Document();
String container = ref
.getContainer();
if (container == null)
container = "";
doc
.add(new Field(
SearchService.DATE_STAMP,
String.valueOf(System.currentTimeMillis()),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_CONTAINER,
container,
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field(
SearchService.FIELD_ID, ref
.getId(),
Field.Store.YES,
Field.Index.NO));
doc.add(new Field(
SearchService.FIELD_TYPE,
ref.getType(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_SUBTYPE,
ref.getSubType(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_REFERENCE,
ref.getReference(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_CONTEXT,
sep.getSiteId(ref),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
if (sep.isContentFromReader(entity))
{
contentReader = sep
.getContentReader(entity);
doc
.add(new Field(
SearchService.FIELD_CONTENTS,
contentReader,
Field.TermVector.YES));
}
else
{
doc
.add(new Field(
SearchService.FIELD_CONTENTS,
sep
.getContent(entity),
Field.Store.YES,
Field.Index.TOKENIZED,
Field.TermVector.YES));
}
doc.add(new Field(
SearchService.FIELD_TITLE,
sep.getTitle(entity),
Field.Store.YES,
Field.Index.TOKENIZED,
Field.TermVector.YES));
doc.add(new Field(
SearchService.FIELD_TOOL,
sep.getTool(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field(
SearchService.FIELD_URL,
sep.getUrl(entity),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field(
SearchService.FIELD_SITEID,
sep.getSiteId(ref),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
// add the custom properties
Map m = sep.getCustomProperties();
if (m != null)
{
for (Iterator cprops = m
.keySet().iterator(); cprops
.hasNext();)
{
String key = (String) cprops
.next();
Object value = m.get(key);
String[] values = null;
if (value instanceof String)
{
values = new String[1];
values[0] = (String) value;
}
if (value instanceof String[])
{
values = (String[]) value;
}
if (values == null)
{
log
.info("Null Custom Properties value has been suppled by "
+ sep
+ " in index "
+ key);
}
else
{
for (int i = 0; i < values.length; i++)
{
doc
.add(new Field(
key,
values[i],
Field.Store.YES,
Field.Index.UN_TOKENIZED));
}
}
}
}
log.debug("Indexing Document "
+ doc);
indexWrite.addDocument(doc);
log.debug("Done Indexing Document "
+ doc);
processRDF(sep);
}
else
{
log.debug("Ignored Document "
+ ref.getId());
}
sbi
.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
}
catch (Exception e1)
{
log
.debug(" Failed to index document cause: "
+ e1.getMessage());
}
// update this node lock to indicate its
// still alove, no document should
// take more than 2 mins to process
worker.updateNodeLock();
}
finally
{
if (contentReader != null)
{
try
{
contentReader.close();
}
catch (IOException ioex)
{
}
}
}
}
}
finally
{
if (indexWrite != null)
{
indexWrite.close();
indexWrite = null;
}
}
totalDocs = 0;
try
{
for (Iterator tditer = runtimeToDo.iterator(); worker
.isRunning()
&& tditer.hasNext();)
{
SearchBuilderItem sbi = (SearchBuilderItem) tditer
.next();
if (SearchBuilderItem.STATE_COMPLETED
.equals(sbi.getSearchstate()))
{
if (SearchBuilderItem.ACTION_DELETE
.equals(sbi.getSearchaction()))
{
session.delete(sbi);
}
else
{
session.saveOrUpdate(sbi);
}
}
}
session.flush();
totalDocs = runtimeToDo.size();
}
catch (Exception ex)
{
log
.warn("Failed to update state in database due to "
+ ex.getMessage()
+ " this will be corrected on the next run of the IndexBuilder, no cause for alarm");
}
}
return new Integer(totalDocs);
}
catch (IOException ex)
{
throw new HibernateException(" Failed to create index ", ex);
}
}
};
int totalDocs = 0;
if (worker.isRunning())
{
Integer nprocessed = (Integer) getHibernateTemplate().execute(
callback);
if (nprocessed == null)
{
return;
}
totalDocs = nprocessed.intValue();
}
try
{
indexStorage.doPostIndexUpdate();
}
catch (IOException e)
{
log.error("Failed to do Post Index Update", e);
}
if (worker.isRunning())
{
eventTrackingService.post(eventTrackingService.newEvent(
SearchService.EVENT_TRIGGER_INDEX_RELOAD,
"/searchindexreload", true,
NotificationService.PREF_IMMEDIATE));
long endTime = System.currentTimeMillis();
float totalTime = endTime - startTime;
float ndocs = totalDocs;
if (totalDocs > 0)
{
float docspersec = 1000 * ndocs / totalTime;
log.info("Completed Process List of " + totalDocs + " at "
+ docspersec + " documents/per second");
}
}
}
| public void processToDoListTransaction(final SearchIndexBuilderWorker worker)
{
long startTime = System.currentTimeMillis();
HibernateCallback callback = new HibernateCallback()
{
public Object doInHibernate(Session session)
throws HibernateException, SQLException
{
int totalDocs = 0;
try
{
IndexWriter indexWrite = null;
// Load the list
List runtimeToDo = findPending(indexBatchSize, session);
totalDocs = runtimeToDo.size();
log.debug("Processing " + totalDocs + " documents");
if (totalDocs > 0)
{
try
{
indexStorage.doPreIndexUpdate();
if (indexStorage.indexExists())
{
IndexReader indexReader = null;
try
{
indexReader = indexStorage.getIndexReader();
// Open the index
for (Iterator tditer = runtimeToDo
.iterator(); worker.isRunning()
&& tditer.hasNext();)
{
SearchBuilderItem sbi = (SearchBuilderItem) tditer
.next();
if (!SearchBuilderItem.STATE_PENDING
.equals(sbi.getSearchstate()))
{
// should only be getting pending
// items
log
.warn(" Found Item that was not pending "
+ sbi.getName());
continue;
}
if (SearchBuilderItem.ACTION_UNKNOWN
.equals(sbi.getSearchaction()))
{
sbi
.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
continue;
}
// remove document
try
{
indexReader
.deleteDocuments(new Term(
SearchService.FIELD_REFERENCE,
sbi.getName()));
if (SearchBuilderItem.ACTION_DELETE
.equals(sbi
.getSearchaction()))
{
sbi
.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
}
else
{
sbi
.setSearchstate(SearchBuilderItem.STATE_PENDING_2);
}
}
catch (IOException ex)
{
log.warn("Failed to delete Page ",
ex);
}
}
}
finally
{
if (indexReader != null)
{
indexReader.close();
indexReader = null;
}
}
if (worker.isRunning())
{
indexWrite = indexStorage
.getIndexWriter(false);
}
}
else
{
// create for update
if (worker.isRunning())
{
indexWrite = indexStorage
.getIndexWriter(true);
}
}
for (Iterator tditer = runtimeToDo.iterator(); worker
.isRunning()
&& tditer.hasNext();)
{
Reader contentReader = null;
try
{
SearchBuilderItem sbi = (SearchBuilderItem) tditer
.next();
// only add adds, that have been deleted
// sucessfully
if (!SearchBuilderItem.STATE_PENDING_2
.equals(sbi.getSearchstate()))
{
continue;
}
Reference ref = entityManager
.newReference(sbi.getName());
if (ref == null)
{
log
.error("Unrecognised trigger object presented to index builder "
+ sbi);
}
try
{
Entity entity = ref.getEntity();
EntityContentProducer sep = searchIndexBuilder
.newEntityContentProducer(ref);
if (sep != null && sep.isForIndex(ref) && ref.getContext() != null)
{
Document doc = new Document();
String container = ref
.getContainer();
if (container == null)
container = "";
doc
.add(new Field(
SearchService.DATE_STAMP,
String.valueOf(System.currentTimeMillis()),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_CONTAINER,
container,
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field(
SearchService.FIELD_ID, ref
.getId(),
Field.Store.YES,
Field.Index.NO));
doc.add(new Field(
SearchService.FIELD_TYPE,
ref.getType(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_SUBTYPE,
ref.getSubType(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_REFERENCE,
ref.getReference(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc
.add(new Field(
SearchService.FIELD_CONTEXT,
sep.getSiteId(ref),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
if (sep.isContentFromReader(entity))
{
contentReader = sep
.getContentReader(entity);
doc
.add(new Field(
SearchService.FIELD_CONTENTS,
contentReader,
Field.TermVector.YES));
}
else
{
doc
.add(new Field(
SearchService.FIELD_CONTENTS,
sep
.getContent(entity),
Field.Store.YES,
Field.Index.TOKENIZED,
Field.TermVector.YES));
}
doc.add(new Field(
SearchService.FIELD_TITLE,
sep.getTitle(entity),
Field.Store.YES,
Field.Index.TOKENIZED,
Field.TermVector.YES));
doc.add(new Field(
SearchService.FIELD_TOOL,
sep.getTool(),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field(
SearchService.FIELD_URL,
sep.getUrl(entity),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
doc.add(new Field(
SearchService.FIELD_SITEID,
sep.getSiteId(ref),
Field.Store.YES,
Field.Index.UN_TOKENIZED));
// add the custom properties
Map m = sep.getCustomProperties();
if (m != null)
{
for (Iterator cprops = m
.keySet().iterator(); cprops
.hasNext();)
{
String key = (String) cprops
.next();
Object value = m.get(key);
String[] values = null;
if (value instanceof String)
{
values = new String[1];
values[0] = (String) value;
}
if (value instanceof String[])
{
values = (String[]) value;
}
if (values == null)
{
log
.info("Null Custom Properties value has been suppled by "
+ sep
+ " in index "
+ key);
}
else
{
for (int i = 0; i < values.length; i++)
{
doc
.add(new Field(
key,
values[i],
Field.Store.YES,
Field.Index.UN_TOKENIZED));
}
}
}
}
log.debug("Indexing Document "
+ doc);
indexWrite.addDocument(doc);
log.debug("Done Indexing Document "
+ doc);
processRDF(sep);
}
else
{
log.debug("Ignored Document "
+ ref.getId());
}
sbi
.setSearchstate(SearchBuilderItem.STATE_COMPLETED);
}
catch (Exception e1)
{
log
.debug(" Failed to index document cause: "
+ e1.getMessage());
}
// update this node lock to indicate its
// still alove, no document should
// take more than 2 mins to process
worker.updateNodeLock();
}
finally
{
if (contentReader != null)
{
try
{
contentReader.close();
}
catch (IOException ioex)
{
}
}
}
}
}
finally
{
if (indexWrite != null)
{
indexWrite.close();
indexWrite = null;
}
}
totalDocs = 0;
try
{
for (Iterator tditer = runtimeToDo.iterator(); worker
.isRunning()
&& tditer.hasNext();)
{
SearchBuilderItem sbi = (SearchBuilderItem) tditer
.next();
if (SearchBuilderItem.STATE_COMPLETED
.equals(sbi.getSearchstate()))
{
if (SearchBuilderItem.ACTION_DELETE
.equals(sbi.getSearchaction()))
{
session.delete(sbi);
}
else
{
session.saveOrUpdate(sbi);
}
}
}
session.flush();
totalDocs = runtimeToDo.size();
}
catch (Exception ex)
{
log
.warn("Failed to update state in database due to "
+ ex.getMessage()
+ " this will be corrected on the next run of the IndexBuilder, no cause for alarm");
}
}
return new Integer(totalDocs);
}
catch (IOException ex)
{
throw new HibernateException(" Failed to create index ", ex);
}
}
};
int totalDocs = 0;
if (worker.isRunning())
{
Integer nprocessed = (Integer) getHibernateTemplate().execute(
callback);
if (nprocessed == null)
{
return;
}
totalDocs = nprocessed.intValue();
}
try
{
indexStorage.doPostIndexUpdate();
}
catch (IOException e)
{
log.error("Failed to do Post Index Update", e);
}
if (worker.isRunning())
{
eventTrackingService.post(eventTrackingService.newEvent(
SearchService.EVENT_TRIGGER_INDEX_RELOAD,
"/searchindexreload", true,
NotificationService.PREF_IMMEDIATE));
long endTime = System.currentTimeMillis();
float totalTime = endTime - startTime;
float ndocs = totalDocs;
if (totalDocs > 0)
{
float docspersec = 1000 * ndocs / totalTime;
log.info("Completed Process List of " + totalDocs + " at "
+ docspersec + " documents/per second");
}
}
}
|
diff --git a/eclipse_files/src/DeviceGraphicsDisplay/GantryGraphicsDisplay.java b/eclipse_files/src/DeviceGraphicsDisplay/GantryGraphicsDisplay.java
index 49c19a1b..4354a1a0 100644
--- a/eclipse_files/src/DeviceGraphicsDisplay/GantryGraphicsDisplay.java
+++ b/eclipse_files/src/DeviceGraphicsDisplay/GantryGraphicsDisplay.java
@@ -1,131 +1,132 @@
package DeviceGraphicsDisplay;
import java.awt.Graphics2D;
import java.util.ArrayList;
import javax.swing.JComponent;
import Networking.Client;
import Networking.Request;
import Utils.BinData;
import Utils.Constants;
import Utils.Location;
public class GantryGraphicsDisplay extends DeviceGraphicsDisplay {
Location currentLocation;
Location destinationLocation;
Location binLocation;
ArrayList<BinGraphicsDisplay> binList;
boolean isBinHeld = false; // Determines whether or not the gantry is holding a bin
boolean isMoving = false;
private final int velocity = 5;
BinGraphicsDisplay heldBin;
BinData tempBin;
Client client;
public GantryGraphicsDisplay(Client c) {
currentLocation = new Location(Constants.GANTRY_ROBOT_LOC);
destinationLocation = new Location(Constants.GANTRY_ROBOT_LOC);
binList = new ArrayList<BinGraphicsDisplay>();
client = c;
tempBin = null;
}
@Override
public void draw(JComponent c, Graphics2D g) {
// If robot is at incorrect Y location, first move bot to inital X location
if (currentLocation.getY() != destinationLocation.getY()
&& currentLocation.getX() != Constants.GANTRY_ROBOT_LOC.getX()) {
if (currentLocation.getX() < Constants.GANTRY_ROBOT_LOC.getX()) {
currentLocation.incrementX(velocity);
} else if (currentLocation.getX() > Constants.GANTRY_ROBOT_LOC.getX()) {
currentLocation.incrementX(-velocity);
}
}
// If robot is in initial X, move to correct Y
if (currentLocation.getX() == Constants.GANTRY_ROBOT_LOC.getX()
&& currentLocation.getY() != destinationLocation.getY()) {
if (currentLocation.getY() < destinationLocation.getY()) {
currentLocation.incrementY(velocity);
}
if (currentLocation.getY() > destinationLocation.getY()) {
currentLocation.incrementY(-velocity);
}
}
// If robot is at correct Y and correct rotation, move to correct X
if (currentLocation.getY() == destinationLocation.getY()
&& currentLocation.getX() != destinationLocation.getX()) { // && currentDegree == finalDegree) {
if (currentLocation.getX() < destinationLocation.getX()) {
currentLocation.incrementX(velocity);
} else if (currentLocation.getX() > destinationLocation.getX()) {
currentLocation.incrementX(-velocity);
}
}
if (currentLocation.getY() == destinationLocation.getY()
&& currentLocation.getX() == destinationLocation.getX() && isMoving == true) {
client.sendData(new Request(Constants.GANTRY_ROBOT_DONE_MOVE, Constants.GANTRY_ROBOT_TARGET, null));
isMoving = false;
}
if (isBinHeld) {
binLocation = new Location(currentLocation);
heldBin.setLocation(binLocation);
}
for (int i = 0; i < binList.size(); i++) {
binList.get(i).drawWithOffset(c, g, client.getOffset());
binList.get(i).draw(c, g);
}
g.drawImage(Constants.GANTRY_ROBOT_IMAGE, currentLocation.getX() + client.getOffset(), currentLocation.getY(),
c);
}
@Override
public void receiveData(Request req) {
if (req.getCommand().equals(Constants.GANTRY_ROBOT_GET_BIN_COMMAND)) {
tempBin = (BinData) req.getData();
for (int i = 0; i < binList.size(); i++) {
if (binList.get(i).getPartType().equals(tempBin.getBinPartType())) {
heldBin = binList.get(i);
isBinHeld = true;
}
}
tempBin = null;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_MOVE_TO_LOC_COMMAND)) {
// System.out.println("Received moved to loc command");
destinationLocation = (Location) req.getData();
isMoving = true;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_DROP_BIN_COMMAND)) {
heldBin = null;
isBinHeld = false;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_ADD_NEW_BIN)) {
tempBin = (BinData) req.getData();
+ System.out.println("new bin: " + tempBin.getBinPartType());
binList.add(new BinGraphicsDisplay(new Location(tempBin.getBinLocation()), tempBin.getBinPartType()));
- tempBin = null;
+ // tempBin = null;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_EDIT_BIN)) {
for (int i = 0; i < binList.size(); i++) {
tempBin = (BinData) req.getData();
if (binList.get(i).getPartType().equals(tempBin.getBinPartType())) {
binList.get(i).setPartType(tempBin.getBinPartType());
}
}
}
}
@Override
public void setLocation(Location newLocation) {
destinationLocation = new Location(newLocation);
}
}
| false | true | public void draw(JComponent c, Graphics2D g) {
// If robot is at incorrect Y location, first move bot to inital X location
if (currentLocation.getY() != destinationLocation.getY()
&& currentLocation.getX() != Constants.GANTRY_ROBOT_LOC.getX()) {
if (currentLocation.getX() < Constants.GANTRY_ROBOT_LOC.getX()) {
currentLocation.incrementX(velocity);
} else if (currentLocation.getX() > Constants.GANTRY_ROBOT_LOC.getX()) {
currentLocation.incrementX(-velocity);
}
}
// If robot is in initial X, move to correct Y
if (currentLocation.getX() == Constants.GANTRY_ROBOT_LOC.getX()
&& currentLocation.getY() != destinationLocation.getY()) {
if (currentLocation.getY() < destinationLocation.getY()) {
currentLocation.incrementY(velocity);
}
if (currentLocation.getY() > destinationLocation.getY()) {
currentLocation.incrementY(-velocity);
}
}
// If robot is at correct Y and correct rotation, move to correct X
if (currentLocation.getY() == destinationLocation.getY()
&& currentLocation.getX() != destinationLocation.getX()) { // && currentDegree == finalDegree) {
if (currentLocation.getX() < destinationLocation.getX()) {
currentLocation.incrementX(velocity);
} else if (currentLocation.getX() > destinationLocation.getX()) {
currentLocation.incrementX(-velocity);
}
}
if (currentLocation.getY() == destinationLocation.getY()
&& currentLocation.getX() == destinationLocation.getX() && isMoving == true) {
client.sendData(new Request(Constants.GANTRY_ROBOT_DONE_MOVE, Constants.GANTRY_ROBOT_TARGET, null));
isMoving = false;
}
if (isBinHeld) {
binLocation = new Location(currentLocation);
heldBin.setLocation(binLocation);
}
for (int i = 0; i < binList.size(); i++) {
binList.get(i).drawWithOffset(c, g, client.getOffset());
binList.get(i).draw(c, g);
}
g.drawImage(Constants.GANTRY_ROBOT_IMAGE, currentLocation.getX() + client.getOffset(), currentLocation.getY(),
c);
}
@Override
public void receiveData(Request req) {
if (req.getCommand().equals(Constants.GANTRY_ROBOT_GET_BIN_COMMAND)) {
tempBin = (BinData) req.getData();
for (int i = 0; i < binList.size(); i++) {
if (binList.get(i).getPartType().equals(tempBin.getBinPartType())) {
heldBin = binList.get(i);
isBinHeld = true;
}
}
tempBin = null;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_MOVE_TO_LOC_COMMAND)) {
// System.out.println("Received moved to loc command");
destinationLocation = (Location) req.getData();
isMoving = true;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_DROP_BIN_COMMAND)) {
heldBin = null;
isBinHeld = false;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_ADD_NEW_BIN)) {
tempBin = (BinData) req.getData();
binList.add(new BinGraphicsDisplay(new Location(tempBin.getBinLocation()), tempBin.getBinPartType()));
tempBin = null;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_EDIT_BIN)) {
for (int i = 0; i < binList.size(); i++) {
tempBin = (BinData) req.getData();
if (binList.get(i).getPartType().equals(tempBin.getBinPartType())) {
binList.get(i).setPartType(tempBin.getBinPartType());
}
}
}
}
@Override
public void setLocation(Location newLocation) {
destinationLocation = new Location(newLocation);
}
}
| public void draw(JComponent c, Graphics2D g) {
// If robot is at incorrect Y location, first move bot to inital X location
if (currentLocation.getY() != destinationLocation.getY()
&& currentLocation.getX() != Constants.GANTRY_ROBOT_LOC.getX()) {
if (currentLocation.getX() < Constants.GANTRY_ROBOT_LOC.getX()) {
currentLocation.incrementX(velocity);
} else if (currentLocation.getX() > Constants.GANTRY_ROBOT_LOC.getX()) {
currentLocation.incrementX(-velocity);
}
}
// If robot is in initial X, move to correct Y
if (currentLocation.getX() == Constants.GANTRY_ROBOT_LOC.getX()
&& currentLocation.getY() != destinationLocation.getY()) {
if (currentLocation.getY() < destinationLocation.getY()) {
currentLocation.incrementY(velocity);
}
if (currentLocation.getY() > destinationLocation.getY()) {
currentLocation.incrementY(-velocity);
}
}
// If robot is at correct Y and correct rotation, move to correct X
if (currentLocation.getY() == destinationLocation.getY()
&& currentLocation.getX() != destinationLocation.getX()) { // && currentDegree == finalDegree) {
if (currentLocation.getX() < destinationLocation.getX()) {
currentLocation.incrementX(velocity);
} else if (currentLocation.getX() > destinationLocation.getX()) {
currentLocation.incrementX(-velocity);
}
}
if (currentLocation.getY() == destinationLocation.getY()
&& currentLocation.getX() == destinationLocation.getX() && isMoving == true) {
client.sendData(new Request(Constants.GANTRY_ROBOT_DONE_MOVE, Constants.GANTRY_ROBOT_TARGET, null));
isMoving = false;
}
if (isBinHeld) {
binLocation = new Location(currentLocation);
heldBin.setLocation(binLocation);
}
for (int i = 0; i < binList.size(); i++) {
binList.get(i).drawWithOffset(c, g, client.getOffset());
binList.get(i).draw(c, g);
}
g.drawImage(Constants.GANTRY_ROBOT_IMAGE, currentLocation.getX() + client.getOffset(), currentLocation.getY(),
c);
}
@Override
public void receiveData(Request req) {
if (req.getCommand().equals(Constants.GANTRY_ROBOT_GET_BIN_COMMAND)) {
tempBin = (BinData) req.getData();
for (int i = 0; i < binList.size(); i++) {
if (binList.get(i).getPartType().equals(tempBin.getBinPartType())) {
heldBin = binList.get(i);
isBinHeld = true;
}
}
tempBin = null;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_MOVE_TO_LOC_COMMAND)) {
// System.out.println("Received moved to loc command");
destinationLocation = (Location) req.getData();
isMoving = true;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_DROP_BIN_COMMAND)) {
heldBin = null;
isBinHeld = false;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_ADD_NEW_BIN)) {
tempBin = (BinData) req.getData();
System.out.println("new bin: " + tempBin.getBinPartType());
binList.add(new BinGraphicsDisplay(new Location(tempBin.getBinLocation()), tempBin.getBinPartType()));
// tempBin = null;
} else if (req.getCommand().equals(Constants.GANTRY_ROBOT_EDIT_BIN)) {
for (int i = 0; i < binList.size(); i++) {
tempBin = (BinData) req.getData();
if (binList.get(i).getPartType().equals(tempBin.getBinPartType())) {
binList.get(i).setPartType(tempBin.getBinPartType());
}
}
}
}
@Override
public void setLocation(Location newLocation) {
destinationLocation = new Location(newLocation);
}
}
|
diff --git a/src/main/de/Lathanael/FC/Commands/Attaint.java b/src/main/de/Lathanael/FC/Commands/Attaint.java
index 9159995..a0321c8 100644
--- a/src/main/de/Lathanael/FC/Commands/Attaint.java
+++ b/src/main/de/Lathanael/FC/Commands/Attaint.java
@@ -1,127 +1,130 @@
/************************************************************************
* This file is part of FunCommands.
*
* FunCommands 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.
*
* ExamplePlugin 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 FunCommands. If not, see <http://www.gnu.org/licenses/>.
************************************************************************/
package de.Lathanael.FC.Commands;
import java.util.HashMap;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import de.Lathanael.FC.FunCommands.FunCommands;
import de.Lathanael.FC.Tools.Utilities;
import be.Balor.Manager.Commands.CommandArgs;
import be.Balor.Manager.Commands.CoreCommand;
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;
/**
* @author Lathanael (aka Philippe Leipold)
*
*/
public class Attaint extends CoreCommand {
/**
*
*/
public Attaint() {
super("fc_attaint", "fun.attaint", "FunCommands");
other = true;
}
/*
* (non-Javadoc)
*
* @see
* be.Balor.Manager.ACCommands#execute(org.bukkit.command.CommandSender,
* java.lang.String[])
*/
@Override
public void execute(CommandSender sender, CommandArgs args) throws PlayerNotFound, ActionNotPermitedException {
Player target;
String name = "";
CommandArgs newArgs;
if (FunCommands.players.containsKey(args.getString(0)))
name = FunCommands.players.get(args.getString(0)).getName();
else
name = args.getString(0);
newArgs = new CommandArgs(name);
target = Utils.getUser(sender, newArgs, permNode, 0, true);
+ final ACPlayer acTarget = ACPlayer.getPlayer(target);
if (target == null)
return;
HashMap<String, String> replace = new HashMap<String, String>();
if (args.hasFlag('c')) {
if (!(PermissionManager.hasPerm(sender, "fun.attaint.check")))
return;
replace.put("dname", target.getDisplayName());
replace.put("name", target.getName());
Utils.sI18n(sender, "attaintShowName", replace);
return;
}
if (FunCommands.players.containsKey(args.getString(0)))
FunCommands.players.remove(args.getString(0));
if (args.length < 2) {
target.setDisplayName(target.getName());
+ acTarget.setInformation("displayName", target.getName());
return;
}
FunCommands.players.put(args.getString(1), target);
replace.put("target", target.getName());
replace.put("name", args.getString(1));
if (Utils.isPlayer(sender, false))
replace.put("sender", Utils.getPlayerName((Player) sender));
else
replace.put("sender", "Server Admin");
target.setDisplayName(args.getString(1));
+ acTarget.setInformation("displayName", args.getString(1));
if (!ACPlayer.getPlayer(target).hasPower(Type.INVISIBLE) || !ACPlayer.getPlayer(target).hasPower(Type.FAKEQUIT)) {
target.setPlayerListName(args.getString(1));
//Utilities.createNewPlayerShell(target, args.getString(1));
}
if (!target.equals(sender)) {
Utils.sI18n(target, "attaintTarget", replace);
Utils.sI18n(sender, "attaintSender", replace);
} else {
Utils.sI18n(sender, "attaintYourself", replace);
}
}
/*
* (non-Javadoc)
*
* @see be.Balor.Manager.ACCommands#argsCheck(java.lang.String[])
*/
@Override
public boolean argsCheck(String... args) {
return args != null && args.length >= 1;
}
/* (non-Javadoc)
* @see be.Balor.Manager.Commands.CoreCommand#registerBukkitPerm()
*/
@Override
public void registerBukkitPerm() {
plugin.getPermissionLinker().addPermChild("fun.attaint.check");
super.registerBukkitPerm();
}
}
| false | true | public void execute(CommandSender sender, CommandArgs args) throws PlayerNotFound, ActionNotPermitedException {
Player target;
String name = "";
CommandArgs newArgs;
if (FunCommands.players.containsKey(args.getString(0)))
name = FunCommands.players.get(args.getString(0)).getName();
else
name = args.getString(0);
newArgs = new CommandArgs(name);
target = Utils.getUser(sender, newArgs, permNode, 0, true);
if (target == null)
return;
HashMap<String, String> replace = new HashMap<String, String>();
if (args.hasFlag('c')) {
if (!(PermissionManager.hasPerm(sender, "fun.attaint.check")))
return;
replace.put("dname", target.getDisplayName());
replace.put("name", target.getName());
Utils.sI18n(sender, "attaintShowName", replace);
return;
}
if (FunCommands.players.containsKey(args.getString(0)))
FunCommands.players.remove(args.getString(0));
if (args.length < 2) {
target.setDisplayName(target.getName());
return;
}
FunCommands.players.put(args.getString(1), target);
replace.put("target", target.getName());
replace.put("name", args.getString(1));
if (Utils.isPlayer(sender, false))
replace.put("sender", Utils.getPlayerName((Player) sender));
else
replace.put("sender", "Server Admin");
target.setDisplayName(args.getString(1));
if (!ACPlayer.getPlayer(target).hasPower(Type.INVISIBLE) || !ACPlayer.getPlayer(target).hasPower(Type.FAKEQUIT)) {
target.setPlayerListName(args.getString(1));
//Utilities.createNewPlayerShell(target, args.getString(1));
}
if (!target.equals(sender)) {
Utils.sI18n(target, "attaintTarget", replace);
Utils.sI18n(sender, "attaintSender", replace);
} else {
Utils.sI18n(sender, "attaintYourself", replace);
}
}
| public void execute(CommandSender sender, CommandArgs args) throws PlayerNotFound, ActionNotPermitedException {
Player target;
String name = "";
CommandArgs newArgs;
if (FunCommands.players.containsKey(args.getString(0)))
name = FunCommands.players.get(args.getString(0)).getName();
else
name = args.getString(0);
newArgs = new CommandArgs(name);
target = Utils.getUser(sender, newArgs, permNode, 0, true);
final ACPlayer acTarget = ACPlayer.getPlayer(target);
if (target == null)
return;
HashMap<String, String> replace = new HashMap<String, String>();
if (args.hasFlag('c')) {
if (!(PermissionManager.hasPerm(sender, "fun.attaint.check")))
return;
replace.put("dname", target.getDisplayName());
replace.put("name", target.getName());
Utils.sI18n(sender, "attaintShowName", replace);
return;
}
if (FunCommands.players.containsKey(args.getString(0)))
FunCommands.players.remove(args.getString(0));
if (args.length < 2) {
target.setDisplayName(target.getName());
acTarget.setInformation("displayName", target.getName());
return;
}
FunCommands.players.put(args.getString(1), target);
replace.put("target", target.getName());
replace.put("name", args.getString(1));
if (Utils.isPlayer(sender, false))
replace.put("sender", Utils.getPlayerName((Player) sender));
else
replace.put("sender", "Server Admin");
target.setDisplayName(args.getString(1));
acTarget.setInformation("displayName", args.getString(1));
if (!ACPlayer.getPlayer(target).hasPower(Type.INVISIBLE) || !ACPlayer.getPlayer(target).hasPower(Type.FAKEQUIT)) {
target.setPlayerListName(args.getString(1));
//Utilities.createNewPlayerShell(target, args.getString(1));
}
if (!target.equals(sender)) {
Utils.sI18n(target, "attaintTarget", replace);
Utils.sI18n(sender, "attaintSender", replace);
} else {
Utils.sI18n(sender, "attaintYourself", replace);
}
}
|
diff --git a/staccatissimo-collections/src/main/java/net/sf/staccatocommons/collections/stream/internal/SingleStream.java b/staccatissimo-collections/src/main/java/net/sf/staccatocommons/collections/stream/internal/SingleStream.java
index e388a579..407b3367 100644
--- a/staccatissimo-collections/src/main/java/net/sf/staccatocommons/collections/stream/internal/SingleStream.java
+++ b/staccatissimo-collections/src/main/java/net/sf/staccatocommons/collections/stream/internal/SingleStream.java
@@ -1,71 +1,71 @@
/**
* Copyright (c) 2010-2012, The StaccatoCommons Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; version 3 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 Lesser General Public License for more details.
*/
package net.sf.staccatocommons.collections.stream.internal;
import java.util.NoSuchElementException;
import net.sf.staccatocommons.collections.stream.Stream;
import net.sf.staccatocommons.collections.stream.Streams;
import net.sf.staccatocommons.iterators.thriter.Thriterator;
import net.sf.staccatocommons.iterators.thriter.Thriterators;
/**
* @author flbulgarelli
*
*/
public final class SingleStream<A> extends StrictStream<A> {
private A element;
/**
* Creates a new {@link SingleStream}
*/
public SingleStream(A element) {
this.element = element;
}
@Override
public Thriterator<A> iterator() {
return Thriterators.from(element);
}
@Override
public int size() {
return 1;
}
@Override
public Stream<A> tail() {
return Streams.empty();
}
@Override
public A get(int n) {
if (n == 0)
return element;
- throw new NoSuchElementException("At " + n);
+ throw new IndexOutOfBoundsException("At " + n);
}
@Override
public boolean isBefore(A previous, A next) {
return false;
}
@Override
public boolean isEmpty() {
return false;
}
}
| true | true | public A get(int n) {
if (n == 0)
return element;
throw new NoSuchElementException("At " + n);
}
| public A get(int n) {
if (n == 0)
return element;
throw new IndexOutOfBoundsException("At " + n);
}
|
diff --git a/modules/resin/src/com/caucho/server/resin/ResinArgs.java b/modules/resin/src/com/caucho/server/resin/ResinArgs.java
index 21ce46091..2abb5a11f 100644
--- a/modules/resin/src/com/caucho/server/resin/ResinArgs.java
+++ b/modules/resin/src/com/caucho/server/resin/ResinArgs.java
@@ -1,652 +1,651 @@
/*
* Copyright (c) 1998-2012 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.server.resin;
import java.net.Socket;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.caucho.VersionFactory;
import com.caucho.config.ConfigException;
import com.caucho.log.EnvironmentStream;
import com.caucho.log.RotateStream;
import com.caucho.server.util.JniCauchoSystem;
import com.caucho.util.L10N;
import com.caucho.vfs.Path;
import com.caucho.vfs.QJniServerSocket;
import com.caucho.vfs.QServerSocket;
import com.caucho.vfs.Vfs;
import com.caucho.vfs.WriteStream;
/**
* The parsed Resin command-line arguments
*/
public class ResinArgs
{
private static final Logger log = Logger.getLogger(ResinArgs.class.getName());
private static final L10N L = new L10N(ResinArgs.class);
private String _serverId;
private Path _resinHome;
private Path _rootDirectory;
private Path _dataDirectory;
private Path _licenseDirectory;
private String _resinConf;
private Socket _pingSocket;
private String _homeCluster;
private String _serverAddress;
private int _serverPort;
private ArrayList<BoundPort> _boundPortList
= new ArrayList<BoundPort>();
private boolean _isOpenSource;
private String _stage = "production";
private boolean _isDumpHeapOnExit;
public ResinArgs()
{
this(new String[0]);
}
public ResinArgs(String []args)
throws ConfigException
{
try {
initEnvironmentDefaults();
parseCommandLine(args);
} catch (Exception e) {
throw ConfigException.create(e);
}
}
private void initEnvironmentDefaults()
{
String resinHome = System.getProperty("resin.home");
if (resinHome != null)
_resinHome = Vfs.lookup(resinHome);
else
_resinHome = Vfs.getPwd();
_rootDirectory = _resinHome;
// server.root backwards compat
String resinRoot = System.getProperty("server.root");
if (resinRoot != null)
_rootDirectory = Vfs.lookup(resinRoot);
// resin.root backwards compat
resinRoot = System.getProperty("resin.root");
if (resinRoot != null)
_rootDirectory = Vfs.lookup(resinRoot);
try {
URL.setURLStreamHandlerFactory(ResinURLStreamHandlerFactory.create());
} catch (java.lang.Error e) {
//operation permitted once per jvm; catching for harness.
}
}
public void setServerId(String serverId)
{
if ("".equals(serverId))
serverId = "default";
_serverId = serverId;
}
public String getServerId()
{
return _serverId;
}
public Path getResinHome()
{
return _resinHome;
}
/**
* Gets the root directory.
*/
public Path getRootDirectory()
{
return _rootDirectory;
}
public void setRootDirectory(Path root)
{
_rootDirectory = root;
}
public Path getLicenseDirectory()
{
return _licenseDirectory;
}
public void setLicenseDirectory(Path licenseDirectory)
{
_licenseDirectory = licenseDirectory;
}
/**
* Gets the root directory.
*/
public Path getDataDirectory()
{
return _dataDirectory;
}
/**
* Sets the root directory.
*/
public void setDataDirectory(Path path)
{
_dataDirectory = path;
}
public Socket getPingSocket()
{
return _pingSocket;
}
public void setOpenSource(boolean isOpenSource)
{
_isOpenSource = isOpenSource;
}
public boolean isOpenSource()
{
return _isOpenSource;
}
/**
* The configuration file used to start the server.
*/
public String getResinConf()
{
return _resinConf;
}
public void setResinConf(String resinConf)
{
_resinConf = resinConf;
}
public Path getResinConfPath()
{
Path pwd = Vfs.lookup();
Path resinConf = null;
String resinConfFile = getResinConf();
if (resinConfFile != null) {
if (log.isLoggable(Level.FINER))
log.finer(this + " looking for conf in " + pwd.lookup(resinConfFile));
resinConf = pwd.lookup(resinConfFile);
}
else if (pwd.lookup("conf/resin.xml").canRead())
resinConfFile = "conf/resin.xml";
else { // backward compat
resinConfFile = "conf/resin.conf";
}
Path rootDirectory = getRootDirectory();
if (resinConf == null || ! resinConf.exists()) {
if (log.isLoggable(Level.FINER))
log.finer(this + " looking for conf in "
+ rootDirectory.lookup(resinConfFile));
resinConf = _rootDirectory.lookup(resinConfFile);
}
if (! resinConf.exists() && ! _resinHome.equals(_rootDirectory)) {
if (log.isLoggable(Level.FINER))
log.finer(this + " looking for conf in "
+ _resinHome.lookup(resinConfFile));
resinConf = _resinHome.lookup(resinConfFile);
}
// for error messages, show path relative to rootDirectory
if (! resinConf.exists())
resinConf = rootDirectory.lookup(resinConfFile);
return resinConf;
}
/**
* Returns the bound port list.
*/
public ArrayList<BoundPort> getBoundPortList()
{
return _boundPortList;
}
/**
* Returns the stage to start with.
*/
public String getStage()
{
return _stage;
}
public void setStage(String stage)
{
_stage = stage;
}
public void setHomeCluster(String homeCluster)
{
_homeCluster = homeCluster;
}
public String getHomeCluster()
{
return _homeCluster;
}
public String getServerAddress()
{
return _serverAddress;
}
public void setServerAddress(String address)
{
_serverAddress = address;
}
public int getServerPort()
{
return _serverPort;
}
public void setServerPort(int port)
{
_serverPort = port;
}
public String getUser()
{
return null;
}
public String getPassword()
{
return null;
}
public boolean isDumpHeapOnExit()
{
return _isDumpHeapOnExit;
}
private void parseCommandLine(String []argv)
throws Exception
{
int len = argv.length;
int i = 0;
while (i < len) {
// RandomUtil.addRandom(argv[i]);
String arg = argv[i];
- if (! arg.startsWith("--") || arg.startsWith("-"))
+ if (arg.startsWith("-") && ! arg.startsWith("--"))
arg = "-" + arg;
if (i + 1 < len
&& (argv[i].equals("-stdout")
|| argv[i].equals("--stdout"))) {
Path path = Vfs.lookup(argv[i + 1]);
RotateStream stream = RotateStream.create(path);
stream.init();
WriteStream out = stream.getStream();
out.setDisableClose(true);
EnvironmentStream.setStdout(out);
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-stderr")
|| argv[i].equals("--stderr"))) {
Path path = Vfs.lookup(argv[i + 1]);
RotateStream stream = RotateStream.create(path);
stream.init();
WriteStream out = stream.getStream();
out.setDisableClose(true);
EnvironmentStream.setStderr(out);
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-conf")
|| argv[i].equals("--conf"))) {
_resinConf = argv[i + 1];
i += 2;
}
else if (argv[i].equals("-log-directory")
|| argv[i].equals("--log-directory")) {
i += 2;
}
else if (argv[i].equals("-config-server")
|| argv[i].equals("--config-server")) {
i += 2;
}
else if (argv[i].equals("--dump-heap-on-exit")) {
_isDumpHeapOnExit = true;
i += 1;
}
else if (i + 1 < len
&& (argv[i].equals("-server")
|| argv[i].equals("--server"))) {
_serverId = argv[i + 1];
if (_serverId.equals(""))
_serverId = "default";
i += 2;
}
else if (argv[i].equals("-resin-home")
|| argv[i].equals("--resin-home")) {
_resinHome = Vfs.lookup(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-root-directory")
|| argv[i].equals("--root-directory")
|| argv[i].equals("-resin-root")
|| argv[i].equals("--resin-root")
|| argv[i].equals("-server-root")
|| argv[i].equals("--server-root")) {
_rootDirectory = _resinHome.lookup(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-data-directory")
|| argv[i].equals("--data-directory")) {
_dataDirectory = Vfs.lookup(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-service")) {
JniCauchoSystem.create().initJniBackground();
// windows service
i += 1;
}
else if (i + 1 < len
&& (argv[i].equals("-cluster")
|| argv[i].equals("--cluster")
|| argv[i].equals("-join-cluster")
|| argv[i].equals("--join-cluster"))) {
_homeCluster = argv[i + 1];
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-server-address")
|| argv[i].equals("--server-address"))) {
_serverAddress = argv[i + 1];
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-server-port")
|| argv[i].equals("--server-port"))) {
_serverPort = Integer.parseInt(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-version")
|| argv[i].equals("--version")) {
System.out.println(VersionFactory.getFullVersion());
System.exit(66);
}
else if (argv[i].equals("-watchdog-port")
|| argv[i].equals("--watchdog-port")) {
// watchdog
i += 2;
}
else if (argv[i].equals("-socketwait")
|| argv[i].equals("--socketwait")
|| argv[i].equals("-pingwait")
|| argv[i].equals("--pingwait")) {
int socketport = Integer.parseInt(argv[i + 1]);
Socket socket = null;
for (int k = 0; k < 15 && socket == null; k++) {
try {
socket = new Socket("127.0.0.1", socketport);
} catch (Throwable e) {
System.out.println(new Date());
e.printStackTrace();
}
if (socket == null)
Thread.sleep(1000);
}
if (socket == null) {
System.err.println("Can't connect to parent process through socket " + socketport);
System.err.println("Resin needs to connect to its parent.");
System.exit(1);
}
/*
if (argv[i].equals("-socketwait") || argv[i].equals("--socketwait"))
_waitIn = socket.getInputStream();
*/
_pingSocket = socket;
//socket.setSoTimeout(60000);
i += 2;
}
else if ("-port".equals(argv[i]) || "--port".equals(argv[i])) {
int fd = Integer.parseInt(argv[i + 1]);
String addr = argv[i + 2];
if ("null".equals(addr))
addr = null;
int port = Integer.parseInt(argv[i + 3]);
_boundPortList.add(new BoundPort(QJniServerSocket.openJNI(fd, port),
addr,
port));
i += 4;
}
else if ("start".equals(argv[i])
|| "start-all".equals(argv[i])
|| "restart".equals(argv[i])) {
JniCauchoSystem.create().initJniBackground();
i++;
}
else if (argv[i].equals("-verbose")
|| argv[i].equals("--verbose")) {
i += 1;
}
else if (argv[i].equals("gui")) {
i += 1;
}
else if (argv[i].equals("console")) {
i += 1;
}
else if (argv[i].equals("watchdog")) {
i += 1;
}
else if (argv[i].equals("start-with-foreground")) {
i += 1;
}
else if (argv[i].equals("-fine")
|| argv[i].equals("--fine")) {
i += 1;
}
else if (argv[i].equals("-finer")
|| argv[i].equals("--finer")) {
i += 1;
}
else if (argv[i].startsWith("-D")
|| argv[i].startsWith("-J")
|| argv[i].startsWith("-X")) {
i += 1;
}
else if ("-stage".equals(argv[i])
|| "--stage".equals(argv[i])) {
_stage = argv[i + 1];
i += 2;
}
else if ("-preview".equals(argv[i])
|| "--preview".equals(argv[i])) {
_stage = "preview";
i += 1;
}
else if ("-debug-port".equals(argv[i])
|| "--debug-port".equals(argv[i])) {
i += 2;
}
else if ("-jmx-port".equals(argv[i])
|| "--jmx-port".equals(argv[i])) {
i += 2;
}
else if ("-jmx-port".equals(argv[i])
|| "--jmx-port".equals(argv[i])) {
i += 2;
}
- else if ("-user-properties".equals(argv[i])
- || "--user-properties".equals(argv[i])) {
+ else if ("--user-properties".equals(arg)) {
i += 2;
}
else if ("--mode".equals(arg)) {
i += 2;
}
else {
System.out.println(L.l("unknown argument '{0}'", argv[i]));
System.out.println();
usage();
System.exit(66);
}
}
}
private static void usage()
{
System.err.println(L.l("usage: bin/resin.sh [-options] [start | stop | restart]"));
System.err.println(L.l(""));
System.err.println(L.l("where options include:"));
System.err.println(L.l(" -conf <file> : select a configuration file"));
System.err.println(L.l(" -data-directory <dir> : select a resin-data directory"));
System.err.println(L.l(" -log-directory <dir> : select a logging directory"));
System.err.println(L.l(" -resin-home <dir> : select a resin home directory"));
System.err.println(L.l(" -root-directory <dir> : select a root directory"));
System.err.println(L.l(" -server <id> : select a <server> to run"));
System.err.println(L.l(" -watchdog-port <port> : override the watchdog-port"));
System.err.println(L.l(" -verbose : print verbose starting information"));
System.err.println(L.l(" -preview : run as a preview server"));
}
static class DynamicServer {
private final String _cluster;
private final String _address;
private final int _port;
DynamicServer(String cluster, String address, int port)
{
_cluster = cluster;
_address = address;
_port = port;
}
String getCluster()
{
return _cluster;
}
String getAddress()
{
return _address;
}
int getPort()
{
return _port;
}
}
static class BoundPort {
private QServerSocket _ss;
private String _address;
private int _port;
BoundPort(QServerSocket ss, String address, int port)
{
if (ss == null)
throw new NullPointerException();
_ss = ss;
_address = address;
_port = port;
}
public QServerSocket getServerSocket()
{
return _ss;
}
public int getPort()
{
return _port;
}
public String getAddress()
{
return _address;
}
}
}
| false | true | private void parseCommandLine(String []argv)
throws Exception
{
int len = argv.length;
int i = 0;
while (i < len) {
// RandomUtil.addRandom(argv[i]);
String arg = argv[i];
if (! arg.startsWith("--") || arg.startsWith("-"))
arg = "-" + arg;
if (i + 1 < len
&& (argv[i].equals("-stdout")
|| argv[i].equals("--stdout"))) {
Path path = Vfs.lookup(argv[i + 1]);
RotateStream stream = RotateStream.create(path);
stream.init();
WriteStream out = stream.getStream();
out.setDisableClose(true);
EnvironmentStream.setStdout(out);
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-stderr")
|| argv[i].equals("--stderr"))) {
Path path = Vfs.lookup(argv[i + 1]);
RotateStream stream = RotateStream.create(path);
stream.init();
WriteStream out = stream.getStream();
out.setDisableClose(true);
EnvironmentStream.setStderr(out);
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-conf")
|| argv[i].equals("--conf"))) {
_resinConf = argv[i + 1];
i += 2;
}
else if (argv[i].equals("-log-directory")
|| argv[i].equals("--log-directory")) {
i += 2;
}
else if (argv[i].equals("-config-server")
|| argv[i].equals("--config-server")) {
i += 2;
}
else if (argv[i].equals("--dump-heap-on-exit")) {
_isDumpHeapOnExit = true;
i += 1;
}
else if (i + 1 < len
&& (argv[i].equals("-server")
|| argv[i].equals("--server"))) {
_serverId = argv[i + 1];
if (_serverId.equals(""))
_serverId = "default";
i += 2;
}
else if (argv[i].equals("-resin-home")
|| argv[i].equals("--resin-home")) {
_resinHome = Vfs.lookup(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-root-directory")
|| argv[i].equals("--root-directory")
|| argv[i].equals("-resin-root")
|| argv[i].equals("--resin-root")
|| argv[i].equals("-server-root")
|| argv[i].equals("--server-root")) {
_rootDirectory = _resinHome.lookup(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-data-directory")
|| argv[i].equals("--data-directory")) {
_dataDirectory = Vfs.lookup(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-service")) {
JniCauchoSystem.create().initJniBackground();
// windows service
i += 1;
}
else if (i + 1 < len
&& (argv[i].equals("-cluster")
|| argv[i].equals("--cluster")
|| argv[i].equals("-join-cluster")
|| argv[i].equals("--join-cluster"))) {
_homeCluster = argv[i + 1];
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-server-address")
|| argv[i].equals("--server-address"))) {
_serverAddress = argv[i + 1];
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-server-port")
|| argv[i].equals("--server-port"))) {
_serverPort = Integer.parseInt(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-version")
|| argv[i].equals("--version")) {
System.out.println(VersionFactory.getFullVersion());
System.exit(66);
}
else if (argv[i].equals("-watchdog-port")
|| argv[i].equals("--watchdog-port")) {
// watchdog
i += 2;
}
else if (argv[i].equals("-socketwait")
|| argv[i].equals("--socketwait")
|| argv[i].equals("-pingwait")
|| argv[i].equals("--pingwait")) {
int socketport = Integer.parseInt(argv[i + 1]);
Socket socket = null;
for (int k = 0; k < 15 && socket == null; k++) {
try {
socket = new Socket("127.0.0.1", socketport);
} catch (Throwable e) {
System.out.println(new Date());
e.printStackTrace();
}
if (socket == null)
Thread.sleep(1000);
}
if (socket == null) {
System.err.println("Can't connect to parent process through socket " + socketport);
System.err.println("Resin needs to connect to its parent.");
System.exit(1);
}
/*
if (argv[i].equals("-socketwait") || argv[i].equals("--socketwait"))
_waitIn = socket.getInputStream();
*/
_pingSocket = socket;
//socket.setSoTimeout(60000);
i += 2;
}
else if ("-port".equals(argv[i]) || "--port".equals(argv[i])) {
int fd = Integer.parseInt(argv[i + 1]);
String addr = argv[i + 2];
if ("null".equals(addr))
addr = null;
int port = Integer.parseInt(argv[i + 3]);
_boundPortList.add(new BoundPort(QJniServerSocket.openJNI(fd, port),
addr,
port));
i += 4;
}
else if ("start".equals(argv[i])
|| "start-all".equals(argv[i])
|| "restart".equals(argv[i])) {
JniCauchoSystem.create().initJniBackground();
i++;
}
else if (argv[i].equals("-verbose")
|| argv[i].equals("--verbose")) {
i += 1;
}
else if (argv[i].equals("gui")) {
i += 1;
}
else if (argv[i].equals("console")) {
i += 1;
}
else if (argv[i].equals("watchdog")) {
i += 1;
}
else if (argv[i].equals("start-with-foreground")) {
i += 1;
}
else if (argv[i].equals("-fine")
|| argv[i].equals("--fine")) {
i += 1;
}
else if (argv[i].equals("-finer")
|| argv[i].equals("--finer")) {
i += 1;
}
else if (argv[i].startsWith("-D")
|| argv[i].startsWith("-J")
|| argv[i].startsWith("-X")) {
i += 1;
}
else if ("-stage".equals(argv[i])
|| "--stage".equals(argv[i])) {
_stage = argv[i + 1];
i += 2;
}
else if ("-preview".equals(argv[i])
|| "--preview".equals(argv[i])) {
_stage = "preview";
i += 1;
}
else if ("-debug-port".equals(argv[i])
|| "--debug-port".equals(argv[i])) {
i += 2;
}
else if ("-jmx-port".equals(argv[i])
|| "--jmx-port".equals(argv[i])) {
i += 2;
}
else if ("-jmx-port".equals(argv[i])
|| "--jmx-port".equals(argv[i])) {
i += 2;
}
else if ("-user-properties".equals(argv[i])
|| "--user-properties".equals(argv[i])) {
i += 2;
}
else if ("--mode".equals(arg)) {
i += 2;
}
else {
System.out.println(L.l("unknown argument '{0}'", argv[i]));
System.out.println();
usage();
System.exit(66);
}
}
}
| private void parseCommandLine(String []argv)
throws Exception
{
int len = argv.length;
int i = 0;
while (i < len) {
// RandomUtil.addRandom(argv[i]);
String arg = argv[i];
if (arg.startsWith("-") && ! arg.startsWith("--"))
arg = "-" + arg;
if (i + 1 < len
&& (argv[i].equals("-stdout")
|| argv[i].equals("--stdout"))) {
Path path = Vfs.lookup(argv[i + 1]);
RotateStream stream = RotateStream.create(path);
stream.init();
WriteStream out = stream.getStream();
out.setDisableClose(true);
EnvironmentStream.setStdout(out);
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-stderr")
|| argv[i].equals("--stderr"))) {
Path path = Vfs.lookup(argv[i + 1]);
RotateStream stream = RotateStream.create(path);
stream.init();
WriteStream out = stream.getStream();
out.setDisableClose(true);
EnvironmentStream.setStderr(out);
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-conf")
|| argv[i].equals("--conf"))) {
_resinConf = argv[i + 1];
i += 2;
}
else if (argv[i].equals("-log-directory")
|| argv[i].equals("--log-directory")) {
i += 2;
}
else if (argv[i].equals("-config-server")
|| argv[i].equals("--config-server")) {
i += 2;
}
else if (argv[i].equals("--dump-heap-on-exit")) {
_isDumpHeapOnExit = true;
i += 1;
}
else if (i + 1 < len
&& (argv[i].equals("-server")
|| argv[i].equals("--server"))) {
_serverId = argv[i + 1];
if (_serverId.equals(""))
_serverId = "default";
i += 2;
}
else if (argv[i].equals("-resin-home")
|| argv[i].equals("--resin-home")) {
_resinHome = Vfs.lookup(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-root-directory")
|| argv[i].equals("--root-directory")
|| argv[i].equals("-resin-root")
|| argv[i].equals("--resin-root")
|| argv[i].equals("-server-root")
|| argv[i].equals("--server-root")) {
_rootDirectory = _resinHome.lookup(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-data-directory")
|| argv[i].equals("--data-directory")) {
_dataDirectory = Vfs.lookup(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-service")) {
JniCauchoSystem.create().initJniBackground();
// windows service
i += 1;
}
else if (i + 1 < len
&& (argv[i].equals("-cluster")
|| argv[i].equals("--cluster")
|| argv[i].equals("-join-cluster")
|| argv[i].equals("--join-cluster"))) {
_homeCluster = argv[i + 1];
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-server-address")
|| argv[i].equals("--server-address"))) {
_serverAddress = argv[i + 1];
i += 2;
}
else if (i + 1 < len
&& (argv[i].equals("-server-port")
|| argv[i].equals("--server-port"))) {
_serverPort = Integer.parseInt(argv[i + 1]);
i += 2;
}
else if (argv[i].equals("-version")
|| argv[i].equals("--version")) {
System.out.println(VersionFactory.getFullVersion());
System.exit(66);
}
else if (argv[i].equals("-watchdog-port")
|| argv[i].equals("--watchdog-port")) {
// watchdog
i += 2;
}
else if (argv[i].equals("-socketwait")
|| argv[i].equals("--socketwait")
|| argv[i].equals("-pingwait")
|| argv[i].equals("--pingwait")) {
int socketport = Integer.parseInt(argv[i + 1]);
Socket socket = null;
for (int k = 0; k < 15 && socket == null; k++) {
try {
socket = new Socket("127.0.0.1", socketport);
} catch (Throwable e) {
System.out.println(new Date());
e.printStackTrace();
}
if (socket == null)
Thread.sleep(1000);
}
if (socket == null) {
System.err.println("Can't connect to parent process through socket " + socketport);
System.err.println("Resin needs to connect to its parent.");
System.exit(1);
}
/*
if (argv[i].equals("-socketwait") || argv[i].equals("--socketwait"))
_waitIn = socket.getInputStream();
*/
_pingSocket = socket;
//socket.setSoTimeout(60000);
i += 2;
}
else if ("-port".equals(argv[i]) || "--port".equals(argv[i])) {
int fd = Integer.parseInt(argv[i + 1]);
String addr = argv[i + 2];
if ("null".equals(addr))
addr = null;
int port = Integer.parseInt(argv[i + 3]);
_boundPortList.add(new BoundPort(QJniServerSocket.openJNI(fd, port),
addr,
port));
i += 4;
}
else if ("start".equals(argv[i])
|| "start-all".equals(argv[i])
|| "restart".equals(argv[i])) {
JniCauchoSystem.create().initJniBackground();
i++;
}
else if (argv[i].equals("-verbose")
|| argv[i].equals("--verbose")) {
i += 1;
}
else if (argv[i].equals("gui")) {
i += 1;
}
else if (argv[i].equals("console")) {
i += 1;
}
else if (argv[i].equals("watchdog")) {
i += 1;
}
else if (argv[i].equals("start-with-foreground")) {
i += 1;
}
else if (argv[i].equals("-fine")
|| argv[i].equals("--fine")) {
i += 1;
}
else if (argv[i].equals("-finer")
|| argv[i].equals("--finer")) {
i += 1;
}
else if (argv[i].startsWith("-D")
|| argv[i].startsWith("-J")
|| argv[i].startsWith("-X")) {
i += 1;
}
else if ("-stage".equals(argv[i])
|| "--stage".equals(argv[i])) {
_stage = argv[i + 1];
i += 2;
}
else if ("-preview".equals(argv[i])
|| "--preview".equals(argv[i])) {
_stage = "preview";
i += 1;
}
else if ("-debug-port".equals(argv[i])
|| "--debug-port".equals(argv[i])) {
i += 2;
}
else if ("-jmx-port".equals(argv[i])
|| "--jmx-port".equals(argv[i])) {
i += 2;
}
else if ("-jmx-port".equals(argv[i])
|| "--jmx-port".equals(argv[i])) {
i += 2;
}
else if ("--user-properties".equals(arg)) {
i += 2;
}
else if ("--mode".equals(arg)) {
i += 2;
}
else {
System.out.println(L.l("unknown argument '{0}'", argv[i]));
System.out.println();
usage();
System.exit(66);
}
}
}
|
diff --git a/src/main/java/org/apache/maven/artifact/metadata/SnapshotArtifactMetadata.java b/src/main/java/org/apache/maven/artifact/metadata/SnapshotArtifactMetadata.java
index 9124127..632d1fd 100644
--- a/src/main/java/org/apache/maven/artifact/metadata/SnapshotArtifactMetadata.java
+++ b/src/main/java/org/apache/maven/artifact/metadata/SnapshotArtifactMetadata.java
@@ -1,160 +1,171 @@
package org.apache.maven.artifact.metadata;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.codehaus.plexus.util.StringUtils;
import org.apache.maven.artifact.Artifact;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Contains the information stored for a snapshot.
*
* @author <a href="mailto:[email protected]">Brett Porter</a>
* @version $Id$
*/
public class SnapshotArtifactMetadata
extends AbstractVersionArtifactMetadata
{
private String timestamp = null;
private int buildNumber = 0;
private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone( "UTC" );
private static final String UTC_TIMESTAMP_PATTERN = "yyyyMMdd.HHmmss";
public static final Pattern VERSION_FILE_PATTERN = Pattern.compile( "^(.*)-([0-9]{8}.[0-9]{6})-([0-9]+)$" );
// TODO: very quick and nasty hack to get the same timestamp across a build - not embedder friendly
private static String sessionTimestamp = null;
public SnapshotArtifactMetadata( Artifact artifact )
{
super( artifact, artifact.getArtifactId() + "-" + artifact.getBaseVersion() + "." + SNAPSHOT_VERSION_FILE );
}
public String constructVersion()
{
String version = artifact.getBaseVersion();
if ( timestamp != null && buildNumber > 0 )
{
String newVersion = timestamp + "-" + buildNumber;
if ( version != null )
{
version = StringUtils.replace( version, "SNAPSHOT", newVersion );
}
else
{
version = newVersion;
}
}
return version;
}
protected void setContent( String content )
{
Matcher matcher = VERSION_FILE_PATTERN.matcher( content );
if ( matcher.matches() )
{
timestamp = matcher.group( 2 );
buildNumber = Integer.valueOf( matcher.group( 3 ) ).intValue();
}
else
{
timestamp = null;
buildNumber = 0;
}
}
public String getTimestamp()
{
return timestamp;
}
public static DateFormat getUtcDateFormatter()
{
DateFormat utcDateFormatter = new SimpleDateFormat( UTC_TIMESTAMP_PATTERN );
utcDateFormatter.setTimeZone( UTC_TIME_ZONE );
return utcDateFormatter;
}
public void update()
{
this.buildNumber++;
timestamp = getSessionTimestamp();
}
private static String getSessionTimestamp()
{
if ( sessionTimestamp == null )
{
sessionTimestamp = getUtcDateFormatter().format( new Date() );
}
return sessionTimestamp;
}
public int compareTo( Object o )
{
SnapshotArtifactMetadata metadata = (SnapshotArtifactMetadata) o;
// TODO: probably shouldn't test timestamp - except that it may be used do differentiate for a build number of 0
// in the local repository. check, then remove from here and just compare the build numbers
if ( buildNumber > metadata.buildNumber )
{
return 1;
}
else if ( timestamp == null )
{
- return -1;
+ if ( metadata.timestamp == null )
+ {
+ return 0;
+ }
+ else
+ {
+ return -1;
+ }
+ }
+ else if ( metadata.timestamp == null )
+ {
+ return 1;
}
else
{
return timestamp.compareTo( metadata.timestamp );
}
}
public boolean newerThanFile( File file )
{
long fileTime = file.lastModified();
// previous behaviour - compare based on timestamp of file
// problem was that version.txt is often updated even if the remote snapshot was not
// return ( lastModified > fileTime );
// Compare to timestamp
if ( timestamp != null )
{
String fileTimestamp = getUtcDateFormatter().format( new Date( fileTime ) );
return ( fileTimestamp.compareTo( timestamp ) < 0 );
}
return false;
}
public String toString()
{
return "snapshot information for " + artifact.getArtifactId() + " " + artifact.getBaseVersion();
}
}
| true | true | public int compareTo( Object o )
{
SnapshotArtifactMetadata metadata = (SnapshotArtifactMetadata) o;
// TODO: probably shouldn't test timestamp - except that it may be used do differentiate for a build number of 0
// in the local repository. check, then remove from here and just compare the build numbers
if ( buildNumber > metadata.buildNumber )
{
return 1;
}
else if ( timestamp == null )
{
return -1;
}
else
{
return timestamp.compareTo( metadata.timestamp );
}
}
| public int compareTo( Object o )
{
SnapshotArtifactMetadata metadata = (SnapshotArtifactMetadata) o;
// TODO: probably shouldn't test timestamp - except that it may be used do differentiate for a build number of 0
// in the local repository. check, then remove from here and just compare the build numbers
if ( buildNumber > metadata.buildNumber )
{
return 1;
}
else if ( timestamp == null )
{
if ( metadata.timestamp == null )
{
return 0;
}
else
{
return -1;
}
}
else if ( metadata.timestamp == null )
{
return 1;
}
else
{
return timestamp.compareTo( metadata.timestamp );
}
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/JDK12DebugLauncher.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/JDK12DebugLauncher.java
index 436193869..c2cad65e0 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/JDK12DebugLauncher.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/launcher/JDK12DebugLauncher.java
@@ -1,203 +1,206 @@
package org.eclipse.jdt.internal.debug.ui.launcher;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.model.IDebugTarget;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.jdi.Bootstrap;
import org.eclipse.jdt.debug.core.JDIDebugModel;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.VMRunnerConfiguration;
import org.eclipse.jdt.launching.VMRunnerResult;
import org.eclipse.jface.dialogs.ErrorDialog;
import com.sun.jdi.VirtualMachine;
import com.sun.jdi.connect.Connector;
import com.sun.jdi.connect.IllegalConnectorArgumentsException;
import com.sun.jdi.connect.ListeningConnector;
/**
* A launcher for running Java main classes. Uses JDI to launch a vm in debug
* mode.
*/
public class JDK12DebugLauncher extends JDK12Launcher {
public interface IRetryQuery {
/**
* Query the user to retry connecting to the VM.
*/
boolean queryRetry();
}
private IRetryQuery fRetryQuery;
/**
* Creates a new launcher
*/
public JDK12DebugLauncher(IVMInstall vmInstance, IRetryQuery query) {
super(vmInstance);
setRetryQuery(query);
}
/**
* @see IVMRunner#run(VMRunnerConfiguration)
*/
public VMRunnerResult run(VMRunnerConfiguration config) throws CoreException {
verifyVMInstall();
File workingDir = getWorkingDir(config);
int port= SocketUtil.findUnusedLocalPort("", 5000, 15000); //$NON-NLS-1$
if (port == -1) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.noPort"), null)); //$NON-NLS-1$
}
String location= getJDKLocation();
String program= location+File.separator+"bin"+File.separator+"java"; //$NON-NLS-2$ //$NON-NLS-1$
File javawexe= new File(program+"w.exe"); //$NON-NLS-1$
File javaw= new File(program+"w"); //$NON-NLS-1$
if (javaw.isFile()) {
program= javaw.getAbsolutePath();
} else if (javawexe.isFile()) {
program= javawexe.getAbsolutePath();
}
Vector arguments= new Vector();
arguments.addElement(program);
String[] bootCP= config.getBootClassPath();
if (bootCP.length > 0) {
arguments.add("-Xbootclasspath:"+convertClassPath(bootCP)); //$NON-NLS-1$
}
String[] cp= config.getClassPath();
if (cp.length > 0) {
arguments.add("-classpath"); //$NON-NLS-1$
arguments.add(convertClassPath(cp));
}
addArguments(config.getVMArguments(), arguments);
arguments.add("-Xdebug"); //$NON-NLS-1$
arguments.add("-Xnoagent"); //$NON-NLS-1$
arguments.add("-Djava.compiler=NONE"); //$NON-NLS-1$
arguments.add("-Xrunjdwp:transport=dt_socket,address=127.0.0.1:" + port); //$NON-NLS-1$
arguments.add(config.getClassToLaunch());
addArguments(config.getProgramArguments(), arguments);
String[] cmdLine= new String[arguments.size()];
arguments.copyInto(cmdLine);
ListeningConnector connector= getConnector();
if (connector == null) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.noConnector"), null)); //$NON-NLS-1$
}
Map map= connector.defaultArguments();
int timeout= fVMInstance.getDebuggerTimeout();
specifyArguments(map, port, timeout);
Process p= null;
try {
try {
connector.startListening(map);
try {
p= Runtime.getRuntime().exec(cmdLine, null, workingDir);
} catch (IOException e) {
if (p != null) {
p.destroy();
}
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.title"), e)); //$NON-NLS-1$
}
IProcess process= DebugPlugin.getDefault().newProcess(p, renderProcessLabel(cmdLine));
process.setAttribute(JavaRuntime.ATTR_CMDLINE, renderCommandLine(cmdLine));
boolean retry= false;
do {
try {
VirtualMachine vm= connector.accept(map);
setTimeout(vm);
IDebugTarget debugTarget= JDIDebugModel.newDebugTarget(vm, renderDebugTarget(config.getClassToLaunch(), port), process, true, false);
return new VMRunnerResult(debugTarget, new IProcess[] { process });
} catch (InterruptedIOException e) {
String errorMessage= process.getStreamsProxy().getErrorStreamMonitor().getContents();
+ if (errorMessage.length() == 0) {
+ errorMessage= process.getStreamsProxy().getOutputStreamMonitor().getContents();
+ }
if (errorMessage.length() != 0) {
reportError(errorMessage);
} else {
retry= getRetryQuery().queryRetry();
}
}
} while (retry);
} finally {
connector.stopListening(map);
}
} catch (IOException e) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.connect"), e)); //$NON-NLS-1$
} catch (IllegalConnectorArgumentsException e) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.connect"), e)); //$NON-NLS-1$
}
if (p != null)
p.destroy();
return null;
}
private void reportError(final String errorMessage) {
StandardVM.getStandardDisplay().syncExec(new Runnable() {
public void run() {
IStatus s= new Status(IStatus.ERROR, DebugPlugin.getDefault().getDescriptor().getUniqueIdentifier(), 0, errorMessage, null);
ErrorDialog.openError(StandardVM.getStandardDisplay().getActiveShell(),LauncherMessages.getString("JDK12DebugLauncher.Launching_a_Java_VM_1"), LauncherMessages.getString("JDK12DebugLauncher.Problems_encountered_launching_the_Java_VM_in_debug_mode_2"), s); //$NON-NLS-1$ //$NON-NLS-2$
}
});
}
private void setTimeout(VirtualMachine vm) {
if (vm instanceof org.eclipse.jdi.VirtualMachine) {
int timeout= fVMInstance.getDebuggerTimeout();
org.eclipse.jdi.VirtualMachine vm2= (org.eclipse.jdi.VirtualMachine)vm;
vm2.setRequestTimeout(timeout);
}
}
protected void specifyArguments(Map map, int portNumber, int timeout) {
// XXX: Revisit - allows us to put a quote (") around the classpath
Connector.IntegerArgument port= (Connector.IntegerArgument) map.get("port"); //$NON-NLS-1$
port.setValue(portNumber);
Connector.IntegerArgument timeoutArg= (Connector.IntegerArgument) map.get("timeout"); //$NON-NLS-1$
// bug #5163
timeoutArg.setValue(20000);
}
protected ListeningConnector getConnector() {
List connectors= Bootstrap.virtualMachineManager().listeningConnectors();
for (int i= 0; i < connectors.size(); i++) {
ListeningConnector c= (ListeningConnector) connectors.get(i);
if ("com.sun.jdi.SocketListen".equals(c.name())) //$NON-NLS-1$
return c;
}
return null;
}
protected IRetryQuery getRetryQuery() {
return fRetryQuery;
}
protected void setRetryQuery(IRetryQuery retryQuery) {
fRetryQuery = retryQuery;
}
}
| true | true | public VMRunnerResult run(VMRunnerConfiguration config) throws CoreException {
verifyVMInstall();
File workingDir = getWorkingDir(config);
int port= SocketUtil.findUnusedLocalPort("", 5000, 15000); //$NON-NLS-1$
if (port == -1) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.noPort"), null)); //$NON-NLS-1$
}
String location= getJDKLocation();
String program= location+File.separator+"bin"+File.separator+"java"; //$NON-NLS-2$ //$NON-NLS-1$
File javawexe= new File(program+"w.exe"); //$NON-NLS-1$
File javaw= new File(program+"w"); //$NON-NLS-1$
if (javaw.isFile()) {
program= javaw.getAbsolutePath();
} else if (javawexe.isFile()) {
program= javawexe.getAbsolutePath();
}
Vector arguments= new Vector();
arguments.addElement(program);
String[] bootCP= config.getBootClassPath();
if (bootCP.length > 0) {
arguments.add("-Xbootclasspath:"+convertClassPath(bootCP)); //$NON-NLS-1$
}
String[] cp= config.getClassPath();
if (cp.length > 0) {
arguments.add("-classpath"); //$NON-NLS-1$
arguments.add(convertClassPath(cp));
}
addArguments(config.getVMArguments(), arguments);
arguments.add("-Xdebug"); //$NON-NLS-1$
arguments.add("-Xnoagent"); //$NON-NLS-1$
arguments.add("-Djava.compiler=NONE"); //$NON-NLS-1$
arguments.add("-Xrunjdwp:transport=dt_socket,address=127.0.0.1:" + port); //$NON-NLS-1$
arguments.add(config.getClassToLaunch());
addArguments(config.getProgramArguments(), arguments);
String[] cmdLine= new String[arguments.size()];
arguments.copyInto(cmdLine);
ListeningConnector connector= getConnector();
if (connector == null) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.noConnector"), null)); //$NON-NLS-1$
}
Map map= connector.defaultArguments();
int timeout= fVMInstance.getDebuggerTimeout();
specifyArguments(map, port, timeout);
Process p= null;
try {
try {
connector.startListening(map);
try {
p= Runtime.getRuntime().exec(cmdLine, null, workingDir);
} catch (IOException e) {
if (p != null) {
p.destroy();
}
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.title"), e)); //$NON-NLS-1$
}
IProcess process= DebugPlugin.getDefault().newProcess(p, renderProcessLabel(cmdLine));
process.setAttribute(JavaRuntime.ATTR_CMDLINE, renderCommandLine(cmdLine));
boolean retry= false;
do {
try {
VirtualMachine vm= connector.accept(map);
setTimeout(vm);
IDebugTarget debugTarget= JDIDebugModel.newDebugTarget(vm, renderDebugTarget(config.getClassToLaunch(), port), process, true, false);
return new VMRunnerResult(debugTarget, new IProcess[] { process });
} catch (InterruptedIOException e) {
String errorMessage= process.getStreamsProxy().getErrorStreamMonitor().getContents();
if (errorMessage.length() != 0) {
reportError(errorMessage);
} else {
retry= getRetryQuery().queryRetry();
}
}
} while (retry);
} finally {
connector.stopListening(map);
}
} catch (IOException e) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.connect"), e)); //$NON-NLS-1$
} catch (IllegalConnectorArgumentsException e) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.connect"), e)); //$NON-NLS-1$
}
if (p != null)
p.destroy();
return null;
}
| public VMRunnerResult run(VMRunnerConfiguration config) throws CoreException {
verifyVMInstall();
File workingDir = getWorkingDir(config);
int port= SocketUtil.findUnusedLocalPort("", 5000, 15000); //$NON-NLS-1$
if (port == -1) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.noPort"), null)); //$NON-NLS-1$
}
String location= getJDKLocation();
String program= location+File.separator+"bin"+File.separator+"java"; //$NON-NLS-2$ //$NON-NLS-1$
File javawexe= new File(program+"w.exe"); //$NON-NLS-1$
File javaw= new File(program+"w"); //$NON-NLS-1$
if (javaw.isFile()) {
program= javaw.getAbsolutePath();
} else if (javawexe.isFile()) {
program= javawexe.getAbsolutePath();
}
Vector arguments= new Vector();
arguments.addElement(program);
String[] bootCP= config.getBootClassPath();
if (bootCP.length > 0) {
arguments.add("-Xbootclasspath:"+convertClassPath(bootCP)); //$NON-NLS-1$
}
String[] cp= config.getClassPath();
if (cp.length > 0) {
arguments.add("-classpath"); //$NON-NLS-1$
arguments.add(convertClassPath(cp));
}
addArguments(config.getVMArguments(), arguments);
arguments.add("-Xdebug"); //$NON-NLS-1$
arguments.add("-Xnoagent"); //$NON-NLS-1$
arguments.add("-Djava.compiler=NONE"); //$NON-NLS-1$
arguments.add("-Xrunjdwp:transport=dt_socket,address=127.0.0.1:" + port); //$NON-NLS-1$
arguments.add(config.getClassToLaunch());
addArguments(config.getProgramArguments(), arguments);
String[] cmdLine= new String[arguments.size()];
arguments.copyInto(cmdLine);
ListeningConnector connector= getConnector();
if (connector == null) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.noConnector"), null)); //$NON-NLS-1$
}
Map map= connector.defaultArguments();
int timeout= fVMInstance.getDebuggerTimeout();
specifyArguments(map, port, timeout);
Process p= null;
try {
try {
connector.startListening(map);
try {
p= Runtime.getRuntime().exec(cmdLine, null, workingDir);
} catch (IOException e) {
if (p != null) {
p.destroy();
}
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.title"), e)); //$NON-NLS-1$
}
IProcess process= DebugPlugin.getDefault().newProcess(p, renderProcessLabel(cmdLine));
process.setAttribute(JavaRuntime.ATTR_CMDLINE, renderCommandLine(cmdLine));
boolean retry= false;
do {
try {
VirtualMachine vm= connector.accept(map);
setTimeout(vm);
IDebugTarget debugTarget= JDIDebugModel.newDebugTarget(vm, renderDebugTarget(config.getClassToLaunch(), port), process, true, false);
return new VMRunnerResult(debugTarget, new IProcess[] { process });
} catch (InterruptedIOException e) {
String errorMessage= process.getStreamsProxy().getErrorStreamMonitor().getContents();
if (errorMessage.length() == 0) {
errorMessage= process.getStreamsProxy().getOutputStreamMonitor().getContents();
}
if (errorMessage.length() != 0) {
reportError(errorMessage);
} else {
retry= getRetryQuery().queryRetry();
}
}
} while (retry);
} finally {
connector.stopListening(map);
}
} catch (IOException e) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.connect"), e)); //$NON-NLS-1$
} catch (IllegalConnectorArgumentsException e) {
throw new CoreException(createStatus(LauncherMessages.getString("jdkLauncher.error.connect"), e)); //$NON-NLS-1$
}
if (p != null)
p.destroy();
return null;
}
|
diff --git a/org.sonar.ide.eclipse.ui/src/org/sonar/ide/eclipse/ui/internal/jobs/RefreshAllViolationsJob.java b/org.sonar.ide.eclipse.ui/src/org/sonar/ide/eclipse/ui/internal/jobs/RefreshAllViolationsJob.java
index 8e95186d..28e162e1 100644
--- a/org.sonar.ide.eclipse.ui/src/org/sonar/ide/eclipse/ui/internal/jobs/RefreshAllViolationsJob.java
+++ b/org.sonar.ide.eclipse.ui/src/org/sonar/ide/eclipse/ui/internal/jobs/RefreshAllViolationsJob.java
@@ -1,102 +1,102 @@
/*
* Sonar Eclipse
* Copyright (C) 2010-2012 SonarSource
* [email protected]
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 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
* 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 02
*/
package org.sonar.ide.eclipse.ui.internal.jobs;
import com.google.common.collect.ArrayListMultimap;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.sonar.ide.api.SourceCode;
import org.sonar.ide.eclipse.core.internal.SonarNature;
import org.sonar.ide.eclipse.core.internal.markers.MarkerUtils;
import org.sonar.ide.eclipse.core.internal.resources.ResourceUtils;
import org.sonar.ide.eclipse.core.internal.resources.SonarProject;
import org.sonar.ide.eclipse.ui.internal.EclipseSonar;
import org.sonar.wsclient.services.Resource;
import org.sonar.wsclient.services.Violation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RefreshAllViolationsJob extends RefreshViolationsJob {
public static void createAndSchedule() {
List<IResource> resources = new ArrayList<IResource>();
Collections.addAll(resources, ResourcesPlugin.getWorkspace().getRoot().getProjects());
new RefreshAllViolationsJob(resources).schedule();
}
public static void createAndSchedule(IResource resource) {
new RefreshAllViolationsJob(Collections.singletonList(resource)).schedule();
}
protected RefreshAllViolationsJob(List<IResource> resources) {
super(resources);
}
@Override
public boolean visit(final IResource resource) throws CoreException {
if (resource instanceof IProject) {
IProject project = (IProject) resource;
if (!SonarNature.hasSonarNature(project)) {
return false;
}
SonarProject projectProperties = SonarProject.getInstance(project);
if (projectProperties.isAnalysedLocally()) {
return false;
}
MarkerUtils.deleteViolationsMarkers(project);
EclipseSonar sonar = EclipseSonar.getInstance(project);
SourceCode sourceCode = sonar.search(project);
if (sourceCode != null) {
doRefreshViolation(sourceCode);
+ projectProperties.setLastAnalysisDate(sourceCode.getAnalysisDate());
+ projectProperties.save();
}
- projectProperties.setLastAnalysisDate(sourceCode.getAnalysisDate());
- projectProperties.save();
// do not visit members of this resource
return false;
}
return true;
}
private void doRefreshViolation(SourceCode sourceCode) throws CoreException {
List<Violation> violations = sourceCode.getViolations2();
// Split violations by resource
ArrayListMultimap<String, Violation> mm = ArrayListMultimap.create();
for (Violation violation : violations) {
mm.put(violation.getResourceKey(), violation);
}
// Associate violations with resources
for (String resourceKey : mm.keySet()) {
Resource sonarResource = new Resource().setKey(resourceKey);
IResource eclipseResource = ResourceUtils.getResource(sonarResource.getKey());
if (eclipseResource instanceof IFile) {
for (Violation violation : mm.get(resourceKey)) {
MarkerUtils.createMarkerForWSViolation(eclipseResource, violation, false);
}
}
}
}
}
| false | true | public boolean visit(final IResource resource) throws CoreException {
if (resource instanceof IProject) {
IProject project = (IProject) resource;
if (!SonarNature.hasSonarNature(project)) {
return false;
}
SonarProject projectProperties = SonarProject.getInstance(project);
if (projectProperties.isAnalysedLocally()) {
return false;
}
MarkerUtils.deleteViolationsMarkers(project);
EclipseSonar sonar = EclipseSonar.getInstance(project);
SourceCode sourceCode = sonar.search(project);
if (sourceCode != null) {
doRefreshViolation(sourceCode);
}
projectProperties.setLastAnalysisDate(sourceCode.getAnalysisDate());
projectProperties.save();
// do not visit members of this resource
return false;
}
return true;
}
| public boolean visit(final IResource resource) throws CoreException {
if (resource instanceof IProject) {
IProject project = (IProject) resource;
if (!SonarNature.hasSonarNature(project)) {
return false;
}
SonarProject projectProperties = SonarProject.getInstance(project);
if (projectProperties.isAnalysedLocally()) {
return false;
}
MarkerUtils.deleteViolationsMarkers(project);
EclipseSonar sonar = EclipseSonar.getInstance(project);
SourceCode sourceCode = sonar.search(project);
if (sourceCode != null) {
doRefreshViolation(sourceCode);
projectProperties.setLastAnalysisDate(sourceCode.getAnalysisDate());
projectProperties.save();
}
// do not visit members of this resource
return false;
}
return true;
}
|
diff --git a/studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/view/dialogs/EditAliasesDialog.java b/studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/view/dialogs/EditAliasesDialog.java
index 5b7825cb3..b49dcd04e 100644
--- a/studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/view/dialogs/EditAliasesDialog.java
+++ b/studio-apacheds-schemaeditor/src/main/java/org/apache/directory/studio/apacheds/schemaeditor/view/dialogs/EditAliasesDialog.java
@@ -1,360 +1,360 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.apacheds.schemaeditor.view.dialogs;
import java.util.ArrayList;
import java.util.List;
import org.apache.directory.studio.apacheds.schemaeditor.Activator;
import org.apache.directory.studio.apacheds.schemaeditor.PluginUtils;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.TraverseEvent;
import org.eclipse.swt.events.TraverseListener;
import org.eclipse.swt.graphics.Image;
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.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
/**
* This class implements the Manage Aliases Dialog.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class EditAliasesDialog extends Dialog
{
/** The aliases List */
private List<String> aliases;
private List<String> aliasesLowerCased;
/** The dirty flag */
private boolean dirty = false;
// UI Fields
private Table aliasesTable;
private Text newAliasText;
private Button newAliasAddButton;
private Composite errorComposite;
private Image errorImage;
private Label errorLabel;
/**
* Creates a new instance of EditAliasesDialog.
*
* @param aliases
* the array containing the aliases
*/
public EditAliasesDialog( String[] aliases )
{
super( PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell() );
this.aliases = new ArrayList<String>();
aliasesLowerCased = new ArrayList<String>();
for ( String alias : aliases )
{
this.aliases.add( alias );
aliasesLowerCased.add( alias.toLowerCase() );
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.window.Window#configureShell(org.eclipse.swt.widgets.Shell)
*/
protected void configureShell( Shell newShell )
{
super.configureShell( newShell );
newShell.setText( "Edit Aliases" );
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets.Composite)
*/
protected Control createDialogArea( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
composite.setLayout( new GridLayout( 2, false ) );
composite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
// ALIASES Label
Label aliases_label = new Label( composite, SWT.NONE );
aliases_label.setText( "Aliases" );
aliases_label.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, true, 2, 1 ) );
// ALIASES Table
aliasesTable = new Table( composite, SWT.BORDER | SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION
| SWT.HIDE_SELECTION );
GridData gridData = new GridData( SWT.FILL, SWT.FILL, true, true, 2, 1 );
gridData.heightHint = 100;
gridData.minimumHeight = 100;
gridData.widthHint = 200;
gridData.minimumWidth = 200;
aliasesTable.setLayoutData( gridData );
// ADD Label
Label add_label = new Label( composite, SWT.NONE );
add_label.setText( "Add an alias" );
add_label.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, true, 2, 1 ) );
// NEW ALIAS Field
newAliasText = new Text( composite, SWT.BORDER );
newAliasText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Add Button
newAliasAddButton = new Button( composite, SWT.PUSH );
newAliasAddButton.setText( "Add" );
newAliasAddButton.setLayoutData( new GridData( SWT.NONE, SWT.NONE, false, false ) );
newAliasAddButton.setEnabled( false );
// Error Composite
errorComposite = new Composite( composite, SWT.NONE );
errorComposite.setLayout( new GridLayout( 2, false ) );
errorComposite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 2, 1 ) );
errorComposite.setVisible( false );
// Error Image
errorImage = PlatformUI.getWorkbench().getSharedImages().getImage( ISharedImages.IMG_OBJS_ERROR_TSK );
Label label = new Label( errorComposite, SWT.NONE );
label.setImage( errorImage );
label.setSize( 16, 16 );
// Error Label
errorLabel = new Label( errorComposite, SWT.NONE );
errorLabel.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true ) );
errorLabel.setText( "An element with the same alias already exists." );
// Table initialization
fillAliasesTable();
// Listeners initialization
initListeners();
// Setting the focus to the text field
newAliasText.setFocus();
return composite;
}
/**
* Fills in the Aliases Table from the aliases list */
private void fillAliasesTable()
{
aliasesTable.removeAll();
aliasesTable.setItemCount( 0 );
for ( String alias : aliases )
{
TableItem newItem = new TableItem( aliasesTable, SWT.NONE );
newItem.setText( alias );
}
}
/**
* Initializes the Listeners.
*/
private void initListeners()
{
aliasesTable.addKeyListener( new KeyAdapter()
{
public void keyPressed( KeyEvent e )
{
if ( ( e.keyCode == SWT.DEL ) || ( e.keyCode == Action.findKeyCode( "BACKSPACE" ) ) ) { //$NON-NLS-1$
// NOTE: I couldn't find the corresponding Identificator in the SWT.SWT Class,
// so I Used JFace Action fineKeyCode method to get the Backspace keycode.
removeAliases();
}
}
} );
// Aliases Table's Popup Menu
Menu menu = new Menu( getShell(), SWT.POP_UP );
aliasesTable.setMenu( menu );
MenuItem deleteMenuItem = new MenuItem( menu, SWT.PUSH );
deleteMenuItem.setText( "Delete" );
deleteMenuItem.setImage( PlatformUI.getWorkbench().getSharedImages().getImage( ISharedImages.IMG_TOOL_DELETE ) );
// Adding the listener
deleteMenuItem.addListener( SWT.Selection, new Listener()
{
public void handleEvent( Event event )
{
removeAliases();
}
} );
// NEW ALIAS Field
newAliasText.addTraverseListener( new TraverseListener()
{
public void keyTraversed( TraverseEvent e )
{
if ( e.detail == SWT.TRAVERSE_RETURN )
{
String text = newAliasText.getText();
if ( "".equals( text ) ) //$NON-NLS-1$
{
close();
}
else if ( ( !aliasesLowerCased.contains( text.toLowerCase() ) ) //$NON-NLS-1$
&& ( !Activator.getDefault().getSchemaHandler().isAliasOrOidAlreadyTaken( text ) ) )
{
addANewAlias();
}
}
}
} );
newAliasText.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
errorComposite.setVisible( false );
newAliasAddButton.setEnabled( true );
String text = newAliasText.getText();
if ( "".equals( text ) ) //$NON-NLS-1$
{
newAliasAddButton.setEnabled( false );
}
else if ( aliasesLowerCased.contains( text.toLowerCase() ) )
{
errorComposite.setVisible( true );
errorLabel.setText( "This alias already exists in the list." );
newAliasAddButton.setEnabled( false );
}
else if ( Activator.getDefault().getSchemaHandler().isAliasOrOidAlreadyTaken( text ) )
{
errorComposite.setVisible( true );
errorLabel.setText( "An element with the same alias already exists." );
newAliasAddButton.setEnabled( false );
}
else if ( !PluginUtils.verifyName( text ) )
{
errorComposite.setVisible( true );
- errorLabel.setText( "Invalid_Alias." );
+ errorLabel.setText( "Invalid Alias." );
newAliasAddButton.setEnabled( false );
}
}
} );
// ADD Button
newAliasAddButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
addANewAlias();
}
} );
}
/**
* Removes the selected aliases in the Aliases Table from the Aliases List.
*/
private void removeAliases()
{
TableItem[] selectedItems = aliasesTable.getSelection();
for ( TableItem item : selectedItems )
{
aliases.remove( item.getText() );
aliasesLowerCased.remove( item.getText().toLowerCase() );
}
dirty = true;
fillAliasesTable();
}
/**
* Adds a new alias
*/
private void addANewAlias()
{
if ( newAliasText.getText().length() != 0 )
{
aliases.add( newAliasText.getText() );
aliasesLowerCased.add( newAliasText.getText().toLowerCase() );
fillAliasesTable();
newAliasText.setText( "" ); //$NON-NLS-1$
newAliasText.setFocus();
this.dirty = true;
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.dialogs.Dialog#createButtonsForButtonBar(org.eclipse.swt.widgets.Composite)
*/
protected void createButtonsForButtonBar( Composite parent )
{
createButton( parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, false );
createButton( parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false );
}
/**
* Returns the aliases.
*
* @return
* the aliases
*/
public String[] getAliases()
{
return aliases.toArray( new String[0] );
}
/**
* Gets the Dirty flag of the dialog
*
* @return
* the dirty flag of the dialog
*/
public boolean isDirty()
{
return dirty;
}
}
| true | true | private void initListeners()
{
aliasesTable.addKeyListener( new KeyAdapter()
{
public void keyPressed( KeyEvent e )
{
if ( ( e.keyCode == SWT.DEL ) || ( e.keyCode == Action.findKeyCode( "BACKSPACE" ) ) ) { //$NON-NLS-1$
// NOTE: I couldn't find the corresponding Identificator in the SWT.SWT Class,
// so I Used JFace Action fineKeyCode method to get the Backspace keycode.
removeAliases();
}
}
} );
// Aliases Table's Popup Menu
Menu menu = new Menu( getShell(), SWT.POP_UP );
aliasesTable.setMenu( menu );
MenuItem deleteMenuItem = new MenuItem( menu, SWT.PUSH );
deleteMenuItem.setText( "Delete" );
deleteMenuItem.setImage( PlatformUI.getWorkbench().getSharedImages().getImage( ISharedImages.IMG_TOOL_DELETE ) );
// Adding the listener
deleteMenuItem.addListener( SWT.Selection, new Listener()
{
public void handleEvent( Event event )
{
removeAliases();
}
} );
// NEW ALIAS Field
newAliasText.addTraverseListener( new TraverseListener()
{
public void keyTraversed( TraverseEvent e )
{
if ( e.detail == SWT.TRAVERSE_RETURN )
{
String text = newAliasText.getText();
if ( "".equals( text ) ) //$NON-NLS-1$
{
close();
}
else if ( ( !aliasesLowerCased.contains( text.toLowerCase() ) ) //$NON-NLS-1$
&& ( !Activator.getDefault().getSchemaHandler().isAliasOrOidAlreadyTaken( text ) ) )
{
addANewAlias();
}
}
}
} );
newAliasText.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
errorComposite.setVisible( false );
newAliasAddButton.setEnabled( true );
String text = newAliasText.getText();
if ( "".equals( text ) ) //$NON-NLS-1$
{
newAliasAddButton.setEnabled( false );
}
else if ( aliasesLowerCased.contains( text.toLowerCase() ) )
{
errorComposite.setVisible( true );
errorLabel.setText( "This alias already exists in the list." );
newAliasAddButton.setEnabled( false );
}
else if ( Activator.getDefault().getSchemaHandler().isAliasOrOidAlreadyTaken( text ) )
{
errorComposite.setVisible( true );
errorLabel.setText( "An element with the same alias already exists." );
newAliasAddButton.setEnabled( false );
}
else if ( !PluginUtils.verifyName( text ) )
{
errorComposite.setVisible( true );
errorLabel.setText( "Invalid_Alias." );
newAliasAddButton.setEnabled( false );
}
}
} );
// ADD Button
newAliasAddButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
addANewAlias();
}
} );
}
| private void initListeners()
{
aliasesTable.addKeyListener( new KeyAdapter()
{
public void keyPressed( KeyEvent e )
{
if ( ( e.keyCode == SWT.DEL ) || ( e.keyCode == Action.findKeyCode( "BACKSPACE" ) ) ) { //$NON-NLS-1$
// NOTE: I couldn't find the corresponding Identificator in the SWT.SWT Class,
// so I Used JFace Action fineKeyCode method to get the Backspace keycode.
removeAliases();
}
}
} );
// Aliases Table's Popup Menu
Menu menu = new Menu( getShell(), SWT.POP_UP );
aliasesTable.setMenu( menu );
MenuItem deleteMenuItem = new MenuItem( menu, SWT.PUSH );
deleteMenuItem.setText( "Delete" );
deleteMenuItem.setImage( PlatformUI.getWorkbench().getSharedImages().getImage( ISharedImages.IMG_TOOL_DELETE ) );
// Adding the listener
deleteMenuItem.addListener( SWT.Selection, new Listener()
{
public void handleEvent( Event event )
{
removeAliases();
}
} );
// NEW ALIAS Field
newAliasText.addTraverseListener( new TraverseListener()
{
public void keyTraversed( TraverseEvent e )
{
if ( e.detail == SWT.TRAVERSE_RETURN )
{
String text = newAliasText.getText();
if ( "".equals( text ) ) //$NON-NLS-1$
{
close();
}
else if ( ( !aliasesLowerCased.contains( text.toLowerCase() ) ) //$NON-NLS-1$
&& ( !Activator.getDefault().getSchemaHandler().isAliasOrOidAlreadyTaken( text ) ) )
{
addANewAlias();
}
}
}
} );
newAliasText.addModifyListener( new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
errorComposite.setVisible( false );
newAliasAddButton.setEnabled( true );
String text = newAliasText.getText();
if ( "".equals( text ) ) //$NON-NLS-1$
{
newAliasAddButton.setEnabled( false );
}
else if ( aliasesLowerCased.contains( text.toLowerCase() ) )
{
errorComposite.setVisible( true );
errorLabel.setText( "This alias already exists in the list." );
newAliasAddButton.setEnabled( false );
}
else if ( Activator.getDefault().getSchemaHandler().isAliasOrOidAlreadyTaken( text ) )
{
errorComposite.setVisible( true );
errorLabel.setText( "An element with the same alias already exists." );
newAliasAddButton.setEnabled( false );
}
else if ( !PluginUtils.verifyName( text ) )
{
errorComposite.setVisible( true );
errorLabel.setText( "Invalid Alias." );
newAliasAddButton.setEnabled( false );
}
}
} );
// ADD Button
newAliasAddButton.addSelectionListener( new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
addANewAlias();
}
} );
}
|
diff --git a/src/main/java/net/pms/dlna/DLNAResource.java b/src/main/java/net/pms/dlna/DLNAResource.java
index c4ab72ed1..170e0f87f 100644
--- a/src/main/java/net/pms/dlna/DLNAResource.java
+++ b/src/main/java/net/pms/dlna/DLNAResource.java
@@ -1,3283 +1,3286 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.dlna;
import java.io.*;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.FormatConfiguration;
import net.pms.configuration.PmsConfiguration;
import net.pms.configuration.RendererConfiguration;
import net.pms.dlna.virtual.TranscodeVirtualFolder;
import net.pms.dlna.virtual.VirtualFolder;
import net.pms.encoders.*;
import net.pms.external.AdditionalResourceFolderListener;
import net.pms.external.ExternalFactory;
import net.pms.external.ExternalListener;
import net.pms.external.StartStopListener;
import net.pms.formats.Format;
import net.pms.formats.FormatFactory;
import net.pms.io.OutputParams;
import net.pms.io.ProcessWrapper;
import net.pms.io.ProcessWrapperImpl;
import net.pms.io.SizeLimitInputStream;
import net.pms.network.HTTPResource;
import net.pms.util.FileUtil;
import net.pms.util.ImagesUtil;
import net.pms.util.Iso639;
import net.pms.util.MpegUtil;
import net.pms.util.OpenSubtitle;
import static net.pms.util.StringUtil.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents any item that can be browsed via the UPNP ContentDirectory service.
*
* TODO: Change all instance variables to private. For backwards compatibility
* with external plugin code the variables have all been marked as deprecated
* instead of changed to private, but this will surely change in the future.
* When everything has been changed to private, the deprecated note can be
* removed.
*/
public abstract class DLNAResource extends HTTPResource implements Cloneable, Runnable {
private final Map<String, Integer> requestIdToRefcount = new HashMap<>();
private boolean resolved;
private static final int STOP_PLAYING_DELAY = 4000;
private static final Logger LOGGER = LoggerFactory.getLogger(DLNAResource.class);
private final SimpleDateFormat SDF_DATE = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
private static final PmsConfiguration configuration = PMS.getConfiguration();
protected static final int MAX_ARCHIVE_ENTRY_SIZE = 10000000;
protected static final int MAX_ARCHIVE_SIZE_SEEK = 800000000;
/**
* The name displayed on the renderer. Cached the first time getDisplayName(RendererConfiguration) is called.
*/
private String displayName;
/**
* @deprecated This field will be removed. Use {@link net.pms.configuration.PmsConfiguration#getTranscodeFolderName()} instead.
*/
@Deprecated
protected static final String TRANSCODE_FOLDER = Messages.getString("TranscodeVirtualFolder.0"); // localized #--TRANSCODE--#
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected int specificType;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected String id;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected DLNAResource parent;
/**
* @deprecated This field will be removed. Use {@link #getFormat()} and
* {@link #setFormat(Format)} instead.
*/
@Deprecated
protected Format ext;
/**
* The format of this resource.
*/
private Format format;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected DLNAMediaInfo media;
/**
* @deprecated Use {@link #getMediaAudio()} and {@link
* #setMediaAudio(DLNAMediaAudio)} to access this field.
*/
@Deprecated
protected DLNAMediaAudio media_audio;
/**
* @deprecated Use {@link #getMediaSubtitle()} and {@link
* #setMediaSubtitle(DLNAMediaSubtitle)} to access this field.
*/
@Deprecated
protected DLNAMediaSubtitle media_subtitle;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected long lastmodified; // TODO make private and rename lastmodified -> lastModified
/**
* Represents the transformation to be used to the file. If null, then
*
* @see Player
*/
private Player player;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected boolean discovered = false;
private ProcessWrapper externalProcess;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected boolean srtFile;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected int updateId = 1;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
public static int systemUpdateId = 1;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected boolean noName;
private int nametruncate;
private DLNAResource first;
private DLNAResource second;
/**
* @deprecated Use standard getter and setter to access this field.
*
* The time range for the file containing the start and end time in seconds.
*/
@Deprecated
protected Range.Time splitRange = new Range.Time();
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected int splitTrack;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected String fakeParentId;
/**
* @deprecated Use standard getter and setter to access this field.
*/
// Ditlew - needs this in one of the derived classes
@Deprecated
protected RendererConfiguration defaultRenderer;
private String dlnaspec;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected boolean avisynth;
/**
* @deprecated Use standard getter and setter to access this field.
*/
@Deprecated
protected boolean skipTranscode = false;
private boolean allChildrenAreFolders = true;
private String dlnaOrgOpFlags;
/**
* @deprecated Use standard getter and setter to access this field.
*
* List of children objects associated with this DLNAResource. This is only valid when the DLNAResource is of the container type.
*/
@Deprecated
protected List<DLNAResource> children;
/**
* @deprecated Use standard getter and setter to access this field.
*
* The numerical ID (1-based index) assigned to the last child of this folder. The next child is assigned this ID + 1.
*/
// FIXME should be lastChildId
@Deprecated
protected int lastChildrenId = 0; // XXX make private and rename lastChildrenId -> lastChildId
/**
* @deprecated Use standard getter and setter to access this field.
*
* The last time refresh was called.
*/
@Deprecated
protected long lastRefreshTime;
private String lastSearch;
protected HashMap<String, Object> attachments = null;
/**
* Returns parent object, usually a folder type of resource. In the DLDI
* queries, the UPNP server needs to give out the parent container where
* the item is. The <i>parent</i> represents such a container.
*
* @return Parent object.
*/
public DLNAResource getParent() {
return parent;
}
/**
* Set the parent object, usually a folder type of resource. In the DLDI
* queries, the UPNP server needs to give out the parent container where
* the item is. The <i>parent</i> represents such a container.
*
* @param parent Sets the parent object.
*/
public void setParent(DLNAResource parent) {
this.parent = parent;
}
/**
* Returns the id of this resource based on the index in its parent
* container. Its main purpose is to be unique in the parent container.
*
* @return The id string.
* @since 1.50
*/
protected String getId() {
return id;
}
/**
* Set the ID of this resource based on the index in its parent container.
* Its main purpose is to be unique in the parent container. The method is
* automatically called by addChildInternal, so most of the time it is not
* necessary to call it explicitly.
*
* @param id
* @since 1.50
* @see #addChildInternal(DLNAResource)
*/
protected void setId(String id) {
this.id = id;
}
/**
* String representing this resource ID. This string is used by the UPNP
* ContentDirectory service. There is no hard spec on the actual numbering
* except for the root container that always has to be "0". In PMS the
* format used is <i>number($number)+</i>. A common client that expects a
* different format than the one used here is the XBox360. PMS translates
* the XBox360 queries on the fly. For more info, check
* http://www.mperfect.net/whsUpnp360/ .
*
* @return The resource id.
* @since 1.50
*/
public String getResourceId() {
if (getId() == null) {
return null;
}
if (getParent() != null) {
return getParent().getResourceId() + '$' + getId();
} else {
return getId();
}
}
/**
* @see #setId(String)
* @param id
*/
protected void setIndexId(int id) {
setId(Integer.toString(id));
}
/**
*
* @return the unique id which identifies the DLNAResource relative to its parent.
*/
public String getInternalId() {
return getId();
}
/**
*
* @return true, if this contain can have a transcode folder
*/
public boolean isTranscodeFolderAvailable() {
return true;
}
/**
* Any {@link DLNAResource} needs to represent the container or item with a String.
*
* @return String to be showed in the UPNP client.
*/
public abstract String getName();
public abstract String getSystemName();
public abstract long length();
// Ditlew
public long length(RendererConfiguration mediaRenderer) {
return length();
}
public abstract InputStream getInputStream() throws IOException;
public abstract boolean isFolder();
public String getDlnaContentFeatures() {
return (dlnaspec != null ? (dlnaspec + ";") : "") + getDlnaOrgOpFlags() + ";DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000";
}
public DLNAResource getPrimaryResource() {
return first;
}
public DLNAResource getSecondaryResource() {
return second;
}
public String getFakeParentId() {
return fakeParentId;
}
public void setFakeParentId(String fakeParentId) {
this.fakeParentId = fakeParentId;
}
/**
* @return the fake parent id if specified, or the real parent id
*/
public String getParentId() {
if (getFakeParentId() != null) {
return getFakeParentId();
} else {
if (getParent() != null) {
return getParent().getResourceId();
} else {
return "-1";
}
}
}
public DLNAResource() {
setSpecificType(Format.UNKNOWN);
setChildren(new ArrayList<DLNAResource>());
setUpdateId(1);
lastSearch = null;
resHash = 0;
masterParent = null;
}
public DLNAResource(int specificType) {
this();
setSpecificType(specificType);
}
/**
* Recursive function that searches through all of the children until it finds
* a {@link DLNAResource} that matches the name.<p> Only used by
* {@link net.pms.dlna.RootFolder#addWebFolder(File webConf)
* addWebFolder(File webConf)} while parsing the web.conf file.
*
* @param name String to be compared the name to.
* @return Returns a {@link DLNAResource} whose name matches the parameter name
* @see #getName()
*/
public DLNAResource searchByName(String name) {
for (DLNAResource child : getChildren()) {
if (child.getName().equals(name)) {
return child;
}
}
return null;
}
/**
* @param renderer Renderer for which to check if file is supported.
* @return true if the given {@link net.pms.configuration.RendererConfiguration
* RendererConfiguration} can understand type of media. Also returns true
* if this DLNAResource is a container.
*/
public boolean isCompatible(RendererConfiguration renderer) {
return getFormat() == null
|| getFormat().isUnknown()
|| (getFormat().isVideo() && renderer.isVideoSupported())
|| (getFormat().isAudio() && renderer.isAudioSupported())
|| (getFormat().isImage() && renderer.isImageSupported());
}
/**
* Adds a new DLNAResource to the child list. Only useful if this object is
* of the container type.
* <P>
* TODO: (botijo) check what happens with the child object. This function
* can and will transform the child object. If the transcode option is set,
* the child item is converted to a container with the real item and the
* transcode option folder. There is also a parser in order to get the right
* name and type, I suppose. Is this the right place to be doing things like
* these?
* <p>
* FIXME: Ideally the logic below is completely renderer-agnostic. Focus on
* harvesting generic data and transform it for a specific renderer as late
* as possible.
*
* @param child
* DLNAResource to add to a container type.
*/
public void addChild(DLNAResource child) {
// child may be null (spotted - via rootFolder.addChild() - in a misbehaving plugin
if (child == null) {
LOGGER.error("A plugin has attempted to add a null child to \"{}\"", getName());
LOGGER.debug("Error info:", new NullPointerException("Invalid DLNA resource"));
return;
}
child.setParent(this);
child.setMasterParent(getMasterParent());
if (getParent() != null) {
setDefaultRenderer(getParent().getDefaultRenderer());
}
if (PMS.filter(getDefaultRenderer(), child)) {
LOGGER.debug("Resource " + child.getName() + " is filtered out for render " + getDefaultRenderer().getRendererName());
return;
}
try {
if (child.isValid()) {
LOGGER.trace("Adding new child \"{}\" with class \"{}\"", child.getName(), child.getClass().getName());
if (allChildrenAreFolders && !child.isFolder()) {
allChildrenAreFolders = false;
}
child.resHash = Math.abs(child.getSystemName().hashCode() + resumeHash());
DLNAResource resumeRes = null;
ResumeObj r = ResumeObj.create(child);
if (r != null) {
resumeRes = child.clone();
resumeRes.resume = r;
resumeRes.resHash = child.resHash;
addChildInternal(resumeRes);
}
addChildInternal(child);
boolean parserV2 = child.getMedia() != null && getDefaultRenderer() != null && getDefaultRenderer().isMediaParserV2();
if (parserV2) {
// See which mime type the renderer prefers in case it supports the media
String mimeType = getDefaultRenderer().getFormatConfiguration().match(child.getMedia());
if (mimeType != null) {
// Media is streamable
if (!FormatConfiguration.MIMETYPE_AUTO.equals(mimeType)) {
// Override with the preferred mime type of the renderer
LOGGER.trace("Overriding detected mime type \"{}\" for file \"{}\" with renderer preferred mime type \"{}\"",
child.getMedia().getMimeType(), child.getName(), mimeType);
child.getMedia().setMimeType(mimeType);
}
LOGGER.trace("File \"{}\" can be streamed with mime type \"{}\"", child.getName(), child.getMedia().getMimeType());
} else {
// Media is transcodable
LOGGER.trace("File \"{}\" can be transcoded", child.getName());
}
}
if (child.getFormat() != null) {
String configurationSkipExtensions = configuration.getDisableTranscodeForExtensions();
String rendererSkipExtensions = null;
if (getDefaultRenderer() != null) {
rendererSkipExtensions = getDefaultRenderer().getStreamedExtensions();
}
// Should transcoding be skipped for this format?
boolean skip = child.getFormat().skip(configurationSkipExtensions, rendererSkipExtensions);
setSkipTranscode(skip);
if (skip) {
LOGGER.trace("File \"{}\" will be forced to skip transcoding by configuration", child.getName());
}
if (parserV2 || (child.getFormat().transcodable() && child.getMedia() == null)) {
if (!parserV2) {
child.setMedia(new DLNAMediaInfo());
}
// Try to determine a player to use for transcoding.
Player player = null;
// First, try to match a player from recently played folder or based on the name of the DLNAResource
// or its parent. If the name ends in "[unique player id]", that player
// is preferred.
String name = getName();
if (!configuration.isHideRecentlyPlayedFolder(null)) {
player = child.getPlayer();
} else {
for (Player p : PlayerFactory.getPlayers()) {
String end = "[" + p.id() + "]";
if (name.endsWith(end)) {
nametruncate = name.lastIndexOf(end);
player = p;
LOGGER.trace("Selecting player based on name end");
break;
} else if (getParent() != null && getParent().getName().endsWith(end)) {
getParent().nametruncate = getParent().getName().lastIndexOf(end);
player = p;
LOGGER.trace("Selecting player based on parent name end");
break;
}
}
}
// If no preferred player could be determined from the name, try to
// match a player based on media information and format.
if (player == null) {
player = PlayerFactory.getPlayer(child);
}
if (player != null && !allChildrenAreFolders) {
String configurationForceExtensions = configuration.getForceTranscodeForExtensions();
String rendererForceExtensions = null;
if (getDefaultRenderer() != null) {
rendererForceExtensions = getDefaultRenderer().getTranscodedExtensions();
}
// Should transcoding be forced for this format?
boolean forceTranscode = child.getFormat().skip(configurationForceExtensions, rendererForceExtensions);
if (forceTranscode) {
LOGGER.trace("File \"{}\" will be forced to be transcoded by configuration", child.getName());
}
boolean hasEmbeddedSubs = false;
if (child.getMedia() != null) {
for (DLNAMediaSubtitle s : child.getMedia().getSubtitleTracksList()) {
hasEmbeddedSubs = (hasEmbeddedSubs || s.isEmbedded());
}
}
boolean hasSubsToTranscode = false;
if (!configuration.isDisableSubtitles()) {
if (child.isSubsFile()) {
hasSubsToTranscode = getDefaultRenderer() != null && StringUtils.isBlank(getDefaultRenderer().getSupportedSubtitles());
} else {
// FIXME: Why transcode if the renderer can handle embedded subs?
hasSubsToTranscode = hasEmbeddedSubs;
}
if (hasSubsToTranscode) {
LOGGER.trace("File \"{}\" has subs that need transcoding", child.getName());
}
}
boolean isIncompatible = false;
if (!child.getFormat().isCompatible(child.getMedia(), getDefaultRenderer())) {
isIncompatible = true;
LOGGER.trace("File \"{}\" is not supported by the renderer", child.getName());
}
// Prefer transcoding over streaming if:
// 1) the media is unsupported by the renderer, or
// 2) there are subs to transcode
boolean preferTranscode = isIncompatible || hasSubsToTranscode;
// Transcode if:
// 1) transcoding is forced by configuration, or
// 2) transcoding is preferred and not prevented by configuration
if (forceTranscode || (preferTranscode && !isSkipTranscode())) {
child.setPlayer(player);
if (resumeRes != null) {
resumeRes.setPlayer(player);
}
if (parserV2) {
LOGGER.trace("Final verdict: \"{}\" will be transcoded with player \"{}\" with mime type \"{}\"", child.getName(), player.toString(), child.getMedia().getMimeType());
} else {
LOGGER.trace("Final verdict: \"{}\" will be transcoded with player \"{}\"", child.getName(), player.toString());
}
} else {
LOGGER.trace("Final verdict: \"{}\" will be streamed", child.getName());
}
// Should the child be added to the #--TRANSCODE--# folder?
if ((child.getFormat().isVideo() || child.getFormat().isAudio()) && child.isTranscodeFolderAvailable()) {
// true: create (and append) the #--TRANSCODE--# folder to this
// folder if supported/enabled and if it doesn't already exist
VirtualFolder transcodeFolder = getTranscodeFolder(true);
if (transcodeFolder != null) {
VirtualFolder fileTranscodeFolder = new FileTranscodeVirtualFolder(child.getDisplayName(), null);
DLNAResource newChild = child.clone();
newChild.setPlayer(player);
newChild.setMedia(child.getMedia());
fileTranscodeFolder.addChildInternal(newChild);
LOGGER.trace("Adding \"{}\" to transcode folder for player: \"{}\"", child.getName(), player.toString());
transcodeFolder.addChild(fileTranscodeFolder);
}
}
if (child.getFormat().isVideo() && child.isSubSelectable() && !(this instanceof SubSelFile)) {
VirtualFolder vf = getSubSelector(true);
if (vf != null) {
DLNAResource newChild = child.clone();
newChild.setPlayer(player);
newChild.setMedia(child.getMedia());
LOGGER.trace("Duplicate subtitle " + child.getName() + " with player: " + player.toString());
vf.addChild(new SubSelFile(newChild));
}
}
for (ExternalListener listener : ExternalFactory.getExternalListeners()) {
if (listener instanceof AdditionalResourceFolderListener) {
try {
((AdditionalResourceFolderListener) listener).addAdditionalFolder(this, child);
} catch (Throwable t) {
LOGGER.error("Failed to add additional folder for listener of type: \"{}\"", listener.getClass(), t);
}
}
}
} else if (!child.getFormat().isCompatible(child.getMedia(), getDefaultRenderer()) && !child.isFolder()) {
LOGGER.trace("Ignoring file \"{}\" because it is not compatible with renderer \"{}\"", child.getName(), getDefaultRenderer().getRendererName());
getChildren().remove(child);
}
}
if (resumeRes != null) {
resumeRes.setMedia(child.getMedia());
}
if (
child.getFormat().getSecondaryFormat() != null &&
child.getMedia() != null &&
getDefaultRenderer() != null &&
getDefaultRenderer().supportsFormat(child.getFormat().getSecondaryFormat())
) {
DLNAResource newChild = child.clone();
newChild.setFormat(newChild.getFormat().getSecondaryFormat());
LOGGER.trace("Detected secondary format \"{}\" for \"{}\"", newChild.getFormat().toString(), newChild.getName());
newChild.first = child;
child.second = newChild;
if (!newChild.getFormat().isCompatible(newChild.getMedia(), getDefaultRenderer())) {
Player player = PlayerFactory.getPlayer(newChild);
newChild.setPlayer(player);
LOGGER.trace("Secondary format \"{}\" will use player \"{}\" for \"{}\"", newChild.getFormat().toString(), child.getPlayer().name(), newChild.getName());
}
if (child.getMedia() != null && child.getMedia().isSecondaryFormatValid()) {
addChild(newChild);
LOGGER.trace("Adding secondary format \"{}\" for \"{}\"", newChild.getFormat().toString(), newChild.getName());
} else {
LOGGER.trace("Ignoring secondary format \"{}\" for \"{}\": invalid format", newChild.getFormat().toString(), newChild.getName());
}
}
}
}
} catch (Throwable t) {
LOGGER.error("Error adding child: \"{}\"", child.getName(), t);
child.setParent(null);
getChildren().remove(child);
}
}
/**
* Return the transcode folder for this resource.
* If UMS is configured to hide transcode folders, null is returned.
* If no folder exists and the create argument is false, null is returned.
* If no folder exists and the create argument is true, a new transcode folder is created.
* This method is called on the parent frolder each time a child is added to that parent
* (via {@link addChild(DLNAResource)}.
*
* @param create
* @return the transcode virtual folder
*/
// XXX package-private: used by MapFile; should be protected?
TranscodeVirtualFolder getTranscodeFolder(boolean create) {
if (!isTranscodeFolderAvailable()) {
return null;
}
if (configuration.getHideTranscodeEnabled()) {
return null;
}
// search for transcode folder
for (DLNAResource child : getChildren()) {
if (child instanceof TranscodeVirtualFolder) {
return (TranscodeVirtualFolder) child;
}
}
if (create) {
TranscodeVirtualFolder transcodeFolder = new TranscodeVirtualFolder(null);
addChildInternal(transcodeFolder);
return transcodeFolder;
}
return null;
}
/**
* Adds the supplied DNLA resource to the internal list of child nodes,
* and sets the parent to the current node. Avoids the side-effects
* associated with the {@link #addChild(DLNAResource)} method.
*
* @param child the DLNA resource to add to this node's list of children
*/
protected synchronized void addChildInternal(DLNAResource child) {
if (child.getInternalId() != null) {
LOGGER.info(
"Node ({}) already has an ID ({}), which is overridden now. The previous parent node was: {}",
new Object[] {
child.getClass().getName(),
child.getResourceId(),
child.getParent()
}
);
}
getChildren().add(child);
child.setParent(this);
setLastChildId(getLastChildId() + 1);
child.setIndexId(getLastChildId());
}
/**
* First thing it does it searches for an item matching the given objectID.
* If children is false, then it returns the found object as the only object in the list.
* TODO: (botijo) This function does a lot more than this!
*
* @param objectId ID to search for.
* @param children State if you want all the children in the returned list.
* @param start
* @param count
* @param renderer Renderer for which to do the actions.
* @return List of DLNAResource items.
* @throws IOException
*/
public synchronized List<DLNAResource> getDLNAResources(String objectId, boolean children, int start, int count, RendererConfiguration renderer) throws IOException {
return getDLNAResources(objectId, children, start, count, renderer, null);
}
public synchronized List<DLNAResource> getDLNAResources(String objectId, boolean returnChildren, int start, int count, RendererConfiguration renderer, String searchStr) throws IOException {
ArrayList<DLNAResource> resources = new ArrayList<>();
DLNAResource dlna = search(objectId, count, renderer, searchStr);
if (dlna != null) {
String systemName = dlna.getSystemName();
dlna.setDefaultRenderer(renderer);
if (!returnChildren) {
resources.add(dlna);
dlna.refreshChildrenIfNeeded(searchStr);
} else {
dlna.discoverWithRenderer(renderer, count, true, searchStr);
if (count == 0) {
count = dlna.getChildren().size();
}
if (count > 0) {
ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(count);
int nParallelThreads = 3;
if (dlna instanceof DVDISOFile) {
nParallelThreads = 1; // Some DVD drives die with 3 parallel threads
}
ThreadPoolExecutor tpe = new ThreadPoolExecutor(
Math.min(count, nParallelThreads),
count,
20,
TimeUnit.SECONDS,
queue
);
for (int i = start; i < start + count; i++) {
if (i < dlna.getChildren().size()) {
final DLNAResource child = dlna.getChildren().get(i);
if (child != null) {
tpe.execute(child);
resources.add(child);
} else {
LOGGER.warn("null child at index {} in {}", i, systemName);
}
}
}
try {
tpe.shutdown();
tpe.awaitTermination(20, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOGGER.error("error while shutting down thread pool executor for " + systemName, e);
}
LOGGER.trace("End of analysis for " + systemName);
}
}
}
lastSearch = searchStr;
return resources;
}
protected void refreshChildrenIfNeeded(String search) {
if (isDiscovered() && shouldRefresh(search)) {
refreshChildren(search);
notifyRefresh();
}
}
/**
* Update the last refresh time.
*/
protected void notifyRefresh() {
setLastRefreshTime(System.currentTimeMillis());
setUpdateId(getUpdateId() + 1);
setSystemUpdateId(getSystemUpdateId() + 1);
}
final protected void discoverWithRenderer(RendererConfiguration renderer, int count, boolean forced, String searchStr) {
// Discover children if it hasn't been done already
if (!isDiscovered()) {
if (configuration.getFolderLimit() && depthLimit()) {
if (renderer.getRendererName().equalsIgnoreCase("Playstation 3") || renderer.isXBOX()) {
LOGGER.info("Depth limit potentionally hit for " + getDisplayName());
}
if (defaultRenderer != null) {
defaultRenderer.addFolderLimit(this);
}
}
discoverChildren(searchStr);
boolean ready;
if (renderer.isMediaParserV2() && renderer.isDLNATreeHack()) {
ready = analyzeChildren(count);
} else {
ready = analyzeChildren(-1);
}
if (!renderer.isMediaParserV2() || ready) {
setDiscovered(true);
}
notifyRefresh();
} else {
// if forced, then call the old 'refreshChildren' method
LOGGER.trace("discover {} refresh forced: {}", getResourceId(), forced);
if (forced) {
if (refreshChildren(searchStr)) {
notifyRefresh();
}
} else {
// if not, then the regular isRefreshNeeded/doRefreshChildren pair.
if (shouldRefresh(searchStr)) {
doRefreshChildren(searchStr);
notifyRefresh();
}
}
}
}
private boolean shouldRefresh(String searchStr) {
return (searchStr == null && lastSearch != null) ||
(searchStr !=null && !searchStr.equals(lastSearch)) ||
isRefreshNeeded();
}
@Override
public void run() {
if (first == null) {
resolve();
if (second != null) {
second.resolve();
}
}
}
/**
* Recursive function that searches for a given ID.
*
* @param searchId ID to search for.
* @param count
* @param renderer
* @param searchStr
* @return Item found, or null otherwise.
* @see #getId()
*/
public DLNAResource search(String searchId, int count, RendererConfiguration renderer, String searchStr) {
if (getId() != null && searchId != null) {
String[] indexPath = searchId.split("\\$", 2);
if (getId().equals(indexPath[0])) {
if (indexPath.length == 1 || indexPath[1].length() == 0) {
return this;
} else {
discoverWithRenderer(renderer, count, false, searchStr);
for (DLNAResource file : getChildren()) {
DLNAResource found = file.search(indexPath[1], count, renderer, searchStr);
if (found != null) {
return found;
}
}
}
} else {
return null;
}
}
return null;
}
/**
* TODO: (botijo) What is the intention of this function? Looks like a prototype to be overloaded.
*/
public void discoverChildren() {
}
public void discoverChildren(String str) {
discoverChildren();
}
/**
* TODO: (botijo) What is the intention of this function? Looks like a prototype to be overloaded.
*
* @param count
* @return Returns true
*/
public boolean analyzeChildren(int count) {
return true;
}
/**
* Reload the list of children.
*/
public void doRefreshChildren() {
}
public void doRefreshChildren(String search) {
doRefreshChildren();
}
/**
* @return true, if the container is changed, so refresh is needed.
* This could be called a lot of times.
*/
public boolean isRefreshNeeded() {
return false;
}
/**
* This method gets called only for the browsed folder, and not for the
* parent folders. (And in the media library scan step too). Override in
* plugins when you do not want to implement proper change tracking, and
* you do not care if the hierarchy of nodes getting invalid between.
*
* @return True when a refresh is needed, false otherwise.
*/
public boolean refreshChildren() {
if (isRefreshNeeded()) {
doRefreshChildren();
return true;
}
return false;
}
public boolean refreshChildren(String search) {
if (shouldRefresh(search)) {
doRefreshChildren(search);
return true;
}
return false;
}
/**
* @deprecated Use {@link #resolveFormat()} instead.
*/
@Deprecated
protected void checktype() {
resolveFormat();
}
/**
* Sets the resource's {@link net.pms.formats.Format} according to its filename
* if it isn't set already.
*
* @since 1.90.0
*/
protected void resolveFormat() {
if (getFormat() == null) {
setFormat(FormatFactory.getAssociatedFormat(getSystemName()));
}
if (getFormat() != null && getFormat().isUnknown()) {
getFormat().setType(getSpecificType());
}
}
/**
* Hook to lazily initialise immutable resources e.g. ISOs, zip files &c.
*
* @since 1.90.0
* @see #resolve()
*/
protected void resolveOnce() { }
/**
* Resolve events are hooks that allow DLNA resources to perform various forms
* of initialisation when navigated to or streamed i.e. they function as lazy
* constructors.
*
* This method is called by request handlers for a) requests for a stream
* or b) content directory browsing i.e. for potentially every request for a file or
* folder the renderer hasn't cached. Many resource types are immutable (e.g. playlists,
* zip files, DVD ISOs &c.) and only need to respond to this event once.
* Most resource types don't "subscribe" to this event at all. This default implementation
* provides hooks for immutable resources and handles the event for resource types that
* don't care about it. The rest override this method and handle it accordingly. Currently,
* the only resource type that overrides it is {@link RealFile}.
*
* Note: resolving a resource once (only) doesn't prevent children being added to or
* removed from it (if supported). There are other mechanisms for that e.g.
* {@link #doRefreshChildren()} (see {@link Feed} for an example).
*/
public synchronized void resolve() {
if (!resolved) {
resolveOnce();
// if resolve() isn't overridden, this file/folder is immutable
// (or doesn't respond to resolve events, which amounts to the
// same thing), so don't spam it with this event again.
resolved = true;
}
}
// Ditlew
/**
* Returns the display name for the default renderer.
*
* @return The display name.
* @see #getDisplayName(RendererConfiguration)
*/
public String getDisplayName() {
return getDisplayName(null);
}
/**
* Returns the DisplayName that is shown to the Renderer.
* Extra info might be appended depending on the settings, like item duration.
* This is based on {@link #getName()}.
*
* @param mediaRenderer Media Renderer for which to show information.
* @return String representing the item.
*/
public String getDisplayName(RendererConfiguration mediaRenderer) {
if (displayName != null) { // cached
return displayName;
}
displayName = getName();
String subtitleFormat;
String subtitleLanguage;
boolean isNamedNoEncoding = false;
if (
this instanceof RealFile &&
(
configuration.isHideExtensions() ||
configuration.isPrettifyFilenames()
) &&
!isFolder()
) {
if (configuration.isPrettifyFilenames()) {
displayName = FileUtil.getFileNameWithRewriting(displayName);
} else {
displayName = FileUtil.getFileNameWithoutExtension(displayName);
}
}
if (getPlayer() != null) {
if (isNoName()) {
displayName = "[" + getPlayer().name() + "]";
} else {
// Ditlew - WDTV Live don't show durations otherwise, and this is useful for finding the main title
if (mediaRenderer != null && mediaRenderer.isShowDVDTitleDuration() && getMedia() != null && getMedia().getDvdtrack() > 0) {
displayName += " - " + getMedia().getDurationString();
}
if (!configuration.isHideEngineNames()) {
displayName += " [" + getPlayer().name() + "]";
}
}
} else {
if (isNoName()) {
displayName = "[No encoding]";
isNamedNoEncoding = true;
if (mediaRenderer != null && StringUtils.isNotBlank(mediaRenderer.getSupportedSubtitles())) {
isNamedNoEncoding = false;
}
} else if (nametruncate > 0) {
displayName = displayName.substring(0, nametruncate).trim();
}
}
if (
isSubsFile() &&
!isNamedNoEncoding &&
(
getMediaAudio() == null &&
getMediaSubtitle() == null
) &&
(
getPlayer() == null ||
getPlayer().isExternalSubtitlesSupported()
) &&
!configuration.hideSubInfo()
) {
displayName += " {External Subtitles}";
}
if (getMediaAudio() != null) {
String audioLanguage = "/" + getMediaAudio().getLangFullName();
if ("/Undetermined".equals(audioLanguage)) {
audioLanguage = "";
}
displayName = (getPlayer() != null ? ("[" + getPlayer().name() + "]") : "") + " {Audio: " + getMediaAudio().getAudioCodec() + audioLanguage + ((getMediaAudio().getFlavor() != null && mediaRenderer != null && mediaRenderer.isShowAudioMetadata()) ? (" (" + getMediaAudio().getFlavor() + ")") : "") + "}";
}
if (
getMediaSubtitle() != null &&
getMediaSubtitle().getId() != -1 &&
!configuration.hideSubInfo()
) {
subtitleFormat = getMediaSubtitle().getType().getDescription();
if ("(Advanced) SubStation Alpha".equals(subtitleFormat)) {
subtitleFormat = "SSA";
}
subtitleLanguage = "/" + getMediaSubtitle().getLangFullName();
if ("/Undetermined".equals(subtitleLanguage)) {
subtitleLanguage = "";
}
displayName += " {Sub: " + subtitleFormat + subtitleLanguage + ((getMediaSubtitle().getFlavor() != null && mediaRenderer != null && mediaRenderer.isShowSubMetadata()) ? (" (" + getMediaSubtitle().getFlavor() + ")") : "") + "}";
}
if (isAvisynth()) {
displayName = (getPlayer() != null ? ("[" + getPlayer().name()) : "") + " + AviSynth]";
}
if (getSplitRange().isEndLimitAvailable()) {
displayName = ">> " + convertTimeToString(getSplitRange().getStart(), DURATION_TIME_FORMAT);
}
return displayName;
}
/**
* Prototype for returning URLs.
*
* @return An empty URL
*/
protected String getFileURL() {
return getURL("");
}
/**
* @return Returns a URL pointing to an image representing the item. If
* none is available, "thumbnail0000.png" is used.
*/
protected String getThumbnailURL() {
return getURL("thumbnail0000");
}
/**
* @param prefix
* @return Returns a URL for a given media item. Not used for container types.
*/
protected String getURL(String prefix) {
StringBuilder sb = new StringBuilder();
sb.append(PMS.get().getServer().getURL());
sb.append("/get/");
sb.append(getResourceId()); //id
sb.append("/");
sb.append(prefix);
sb.append(encode(getName()));
return sb.toString();
}
/**
* @param subs
* @return Returns a URL for a given subtitles item. Not used for container types.
*/
protected String getSubsURL(DLNAMediaSubtitle subs) {
StringBuilder sb = new StringBuilder();
sb.append(PMS.get().getServer().getURL());
sb.append("/get/");
sb.append(getResourceId()); //id
sb.append("/");
sb.append("subtitle0000");
sb.append(encode(subs.getExternalFile().getName()));
return sb.toString();
}
/**
* Transforms a String to UTF-8.
*
* @param s
* @return Transformed string s in UTF-8 encoding.
*/
private static String encode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOGGER.debug("Caught exception", e);
}
return "";
}
/**
* @return Number of children objects. This might be used in the DLDI
* response, as some renderers might not have enough memory to hold the
* list for all children.
*/
public int childrenNumber() {
if (getChildren() == null) {
return 0;
}
return getChildren().size();
}
/**
* (non-Javadoc)
*
* @see java.lang.Object#clone()
*/
@Override
protected DLNAResource clone() {
DLNAResource o = null;
try {
o = (DLNAResource) super.clone();
o.setId(null);
// Clear the cached display name
o.displayName = null;
// Make sure clones (typically #--TRANSCODE--# folder files)
// have the option to respond to resolve events
o.resolved = false;
} catch (CloneNotSupportedException e) {
LOGGER.error(null, e);
}
return o;
}
// this shouldn't be public
@Deprecated
public String getFlags() {
return getDlnaOrgOpFlags();
}
// permit the renderer to seek by time, bytes or both
private String getDlnaOrgOpFlags() {
return "DLNA.ORG_OP=" + dlnaOrgOpFlags;
}
/**
* @deprecated Use {@link #getDidlString(RendererConfiguration)} instead.
*
* @param mediaRenderer
* @return
*/
@Deprecated
public final String toString(RendererConfiguration mediaRenderer) {
return getDidlString(mediaRenderer);
}
/**
* Returns an XML (DIDL) representation of the DLNA node. It gives a
* complete representation of the item, with as many tags as available.
* Recommendations as per UPNP specification are followed where possible.
*
* @param mediaRenderer
* Media Renderer for which to represent this information. Useful
* for some hacks.
* @return String representing the item. An example would start like this:
* {@code <container id="0$1" childCount="1" parentID="0" restricted="true">}
*/
public final String getDidlString(RendererConfiguration mediaRenderer) {
boolean subsAreValid = false;
StringBuilder sb = new StringBuilder();
if (!configuration.isDisableSubtitles() && StringUtils.isNotBlank(mediaRenderer.getSupportedSubtitles()) && getMedia() != null && getPlayer() == null) {
OutputParams params = new OutputParams(configuration);
Player.setAudioAndSubs(getSystemName(), getMedia(), params);
if (params.sid != null) {
String[] supportedSubs = mediaRenderer.getSupportedSubtitles().split(",");
for (String supportedSub : supportedSubs) {
if (params.sid.getType().toString().equals(supportedSub.trim().toUpperCase())) {
setMediaSubtitle(params.sid);
subsAreValid = true;
break;
}
}
}
}
if (isFolder()) {
openTag(sb, "container");
} else {
openTag(sb, "item");
}
addAttribute(sb, "id", getResourceId());
if (isFolder()) {
if (!isDiscovered() && childrenNumber() == 0) {
// When a folder has not been scanned for resources, it will automatically have zero children.
// Some renderers like XBMC will assume a folder is empty when encountering childCount="0" and
// will not display the folder. By returning childCount="1" these renderers will still display
// the folder. When it is opened, its children will be discovered and childrenNumber() will be
// set to the right value.
addAttribute(sb, "childCount", 1);
} else {
addAttribute(sb, "childCount", childrenNumber());
}
}
addAttribute(sb, "parentID", getParentId());
addAttribute(sb, "restricted", "true");
endTag(sb);
StringBuilder wireshark = new StringBuilder();
final DLNAMediaAudio firstAudioTrack = getMedia() != null ? getMedia().getFirstAudioTrack() : null;
if (firstAudioTrack != null && StringUtils.isNotBlank(firstAudioTrack.getSongname())) {
wireshark.append(firstAudioTrack.getSongname()).append(getPlayer() != null && !configuration.isHideEngineNames() ? (" [" + getPlayer().name() + "]") : "");
addXMLTagAndAttribute(
sb,
"dc:title",
encodeXML(mediaRenderer.getDcTitle(resumeStr(wireshark.toString()), this))
);
} else { // Ditlew - org
// Ditlew
wireshark.append(((isFolder() || getPlayer() == null && subsAreValid) ? getDisplayName() : mediaRenderer.getUseSameExtension(getDisplayName(mediaRenderer))));
String tmp = (isFolder() || getPlayer() == null && subsAreValid) ? getDisplayName() : mediaRenderer.getUseSameExtension(getDisplayName(mediaRenderer));
addXMLTagAndAttribute(
sb,
"dc:title",
encodeXML(mediaRenderer.getDcTitle(resumeStr(tmp), this))
);
}
if (firstAudioTrack != null) {
if (StringUtils.isNotBlank(firstAudioTrack.getAlbum())) {
addXMLTagAndAttribute(sb, "upnp:album", encodeXML(firstAudioTrack.getAlbum()));
}
if (StringUtils.isNotBlank(firstAudioTrack.getArtist())) {
addXMLTagAndAttribute(sb, "upnp:artist", encodeXML(firstAudioTrack.getArtist()));
addXMLTagAndAttribute(sb, "dc:creator", encodeXML(firstAudioTrack.getArtist()));
}
if (StringUtils.isNotBlank(firstAudioTrack.getGenre())) {
addXMLTagAndAttribute(sb, "upnp:genre", encodeXML(firstAudioTrack.getGenre()));
}
if (firstAudioTrack.getTrack() > 0) {
addXMLTagAndAttribute(sb, "upnp:originalTrackNumber", "" + firstAudioTrack.getTrack());
}
}
if (!isFolder()) {
int indexCount = 1;
if (mediaRenderer.isDLNALocalizationRequired()) {
indexCount = getDLNALocalesCount();
}
for (int c = 0; c < indexCount; c++) {
openTag(sb, "res");
/**
* DLNA.ORG_OP flags
*
* Two booleans (binary digits) which determine what transport operations the renderer is allowed to
* perform (in the form of HTTP request headers): the first digit allows the renderer to send
* TimeSeekRange.DLNA.ORG (seek by time) headers; the second allows it to send RANGE (seek by byte)
* headers.
*
* 00 - no seeking (or even pausing) allowed
* 01 - seek by byte
* 10 - seek by time
* 11 - seek by both
*
* See here for an example of how these options can be mapped to keys on the renderer's controller:
* http://www.ps3mediaserver.org/forum/viewtopic.php?f=2&t=2908&p=12550#p12550
*
* Note that seek-by-byte is the preferred option for streamed files [1] and seek-by-time is the
* preferred option for transcoded files.
*
* [1] see http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=15841&p=76201#p76201
*
* seek-by-time requires a) support by the renderer (via the SeekByTime renderer conf option)
* and b) support by the transcode engine.
*
* The seek-by-byte fallback doesn't work well with transcoded files [2], but it's better than
* disabling seeking (and pausing) altogether.
*
* [2] http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=3507&p=16567#p16567 (bottom post)
*/
dlnaOrgOpFlags = "01"; // seek by byte (exclusive)
if (mediaRenderer.isSeekByTime() && getPlayer() != null && getPlayer().isTimeSeekable()) {
/**
* Some renderers - e.g. the PS3 and Panasonic TVs - behave erratically when
* transcoding if we keep the default seek-by-byte permission on when permitting
* seek-by-time: http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=15841
*
* It's not clear if this is a bug in the DLNA libraries of these renderers or a bug
* in UMS, but setting an option in the renderer conf that disables seek-by-byte when
* we permit seek-by-time - e.g.:
*
* SeekByTime = exclusive
*
* works around it.
*/
/**
* TODO (e.g. in a beta release): set seek-by-time (exclusive) here for *all* renderers:
* seek-by-byte isn't needed here (both the renderer and the engine support seek-by-time)
* and may be buggy on other renderers than the ones we currently handle.
*
* In the unlikely event that a renderer *requires* seek-by-both here, it can
* opt in with (e.g.):
*
* SeekByTime = both
*/
if (mediaRenderer.isSeekByTimeExclusive()) {
dlnaOrgOpFlags = "10"; // seek by time (exclusive)
} else {
dlnaOrgOpFlags = "11"; // seek by both
}
}
addAttribute(sb, "xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0/");
// FIXME: There is a flaw here. In addChild(DLNAResource) the mime type
// is determined for the default renderer. This renderer may rewrite the
// mime type based on its configuration. Looking up that mime type is
// not guaranteed to return a match for another renderer.
String mime = mediaRenderer.getMimeType(mimeType());
if (mime == null) {
// FIXME: Setting the default to "video/mpeg" leaves a lot of audio files in the cold.
mime = "video/mpeg";
}
dlnaspec = null;
if (mediaRenderer.isDLNAOrgPNUsed()) {
if (mediaRenderer.isPS3()) {
if (mime.equals("video/x-divx")) {
dlnaspec = "DLNA.ORG_PN=AVI";
} else if (mime.equals("video/x-ms-wmv") && getMedia() != null && getMedia().getHeight() > 700) {
dlnaspec = "DLNA.ORG_PN=WMVHIGH_PRO";
}
} else {
if (mime.equals("video/mpeg")) {
dlnaspec = "DLNA.ORG_PN=" + getMPEG_PS_PALLocalizedValue(c);
if (getPlayer() != null) {
boolean isFileMPEGTS = TsMuxeRVideo.ID.equals(getPlayer().id()) || VideoLanVideoStreaming.ID.equals(getPlayer().id());
boolean isMuxableResult = getMedia().isMuxable(mediaRenderer);
boolean isBravia = mediaRenderer.isBRAVIA();
if (
!isFileMPEGTS &&
(
(
configuration.isMencoderMuxWhenCompatible() &&
MEncoderVideo.ID.equals(getPlayer().id())
) ||
(
- configuration.isFFmpegMuxWhenCompatible() &&
+ (
+ configuration.isFFmpegMuxWhenCompatible() ||
+ configuration.isFFmpegMuxWithTsMuxerWhenCompatible()
+ ) &&
FFMpegVideo.ID.equals(getPlayer().id())
)
)
) {
if (isBravia) {
/**
* Sony Bravia TVs (and possibly other renderers) need ORG_PN to be accurate.
* If the value does not match the media, it won't play the media.
* Often we can lazily predict the correct value to send, but due to
* MEncoder needing to mux via tsMuxeR, we need to work it all out
* before even sending the file list to these devices.
* This is very time-consuming so we should a) avoid using this
* chunk of code whenever possible, and b) design a better system.
* Ideally we would just mux to MPEG-PS instead of MPEG-TS so we could
* know it will always be PS, but most renderers will not accept H.264
* inside MPEG-PS. Another option may be to always produce MPEG-TS
* instead and we should check if that will be OK for all renderers.
*
* This code block comes from Player.setAudioAndSubs()
*/
boolean finishedMatchingPreferences = false;
OutputParams params = new OutputParams(configuration);
if (getMedia() != null) {
// check for preferred audio
StringTokenizer st = new StringTokenizer(configuration.getAudioLanguages(), ",");
while (st != null && st.hasMoreTokens()) {
String lang = st.nextToken();
lang = lang.trim();
LOGGER.trace("Looking for an audio track with lang: " + lang);
for (DLNAMediaAudio audio : getMedia().getAudioTracksList()) {
if (audio.matchCode(lang)) {
params.aid = audio;
LOGGER.trace("Matched audio track: " + audio);
st = null;
break;
}
}
}
}
if (params.aid == null && getMedia().getAudioTracksList().size() > 0) {
// Take a default audio track, dts first if possible
for (DLNAMediaAudio audio : getMedia().getAudioTracksList()) {
if (audio.isDTS()) {
params.aid = audio;
LOGGER.trace("Found priority audio track with DTS: " + audio);
break;
}
}
if (params.aid == null) {
params.aid = getMedia().getAudioTracksList().get(0);
LOGGER.trace("Chose a default audio track: " + params.aid);
}
}
String currentLang = null;
DLNAMediaSubtitle matchedSub = null;
if (params.aid != null) {
currentLang = params.aid.getLang();
}
if (params.sid != null && params.sid.getId() == -1) {
LOGGER.trace("Don't want subtitles!");
params.sid = null;
setMediaSubtitle(params.sid);
finishedMatchingPreferences = true;
}
if (!finishedMatchingPreferences && params.sid != null && !StringUtils.isEmpty(params.sid.getLiveSubURL())) {
// live subtitles
// currently only open subtitles
LOGGER.debug("Live subtitles " + params.sid.getLiveSubURL());
try {
matchedSub = params.sid;
String file = OpenSubtitle.fetchSubs(matchedSub.getLiveSubURL(), matchedSub.getLiveSubFile());
if (!StringUtils.isEmpty(file)) {
matchedSub.setExternalFile(new File(file));
params.sid = matchedSub;
setMediaSubtitle(params.sid);
finishedMatchingPreferences = true;
}
} catch (IOException e) {
}
}
if (!finishedMatchingPreferences) {
StringTokenizer st1 = new StringTokenizer(configuration.getAudioSubLanguages(), ";");
boolean matchedEmbeddedSubtitle = false;
while (st1.hasMoreTokens()) {
String pair = st1.nextToken();
if (pair.contains(",")) {
String audio = pair.substring(0, pair.indexOf(','));
String sub = pair.substring(pair.indexOf(',') + 1);
audio = audio.trim();
sub = sub.trim();
LOGGER.trace("Searching for a match for: " + currentLang + " with " + audio + " and " + sub);
if (Iso639.isCodesMatching(audio, currentLang) || (currentLang != null && audio.equals("*"))) {
if (sub.equals("off")) {
matchedSub = new DLNAMediaSubtitle();
matchedSub.setLang("off");
} else {
for (DLNAMediaSubtitle present_sub : getMedia().getSubtitleTracksList()) {
if (present_sub.matchCode(sub) || sub.equals("*")) {
if (present_sub.getExternalFile() != null) {
if (configuration.isAutoloadExternalSubtitles()) {
// Subtitle is external and we want external subtitles, look no further
matchedSub = present_sub;
LOGGER.trace(" Found a match: " + matchedSub);
break;
} else {
// Subtitle is external but we do not want external subtitles, keep searching
LOGGER.trace(" External subtitle ignored because of user setting: " + present_sub);
}
} else {
matchedSub = present_sub;
LOGGER.trace(" Found a match: " + matchedSub);
if (configuration.isAutoloadExternalSubtitles()) {
// Subtitle is internal and we will wait to see if an external one is available instead
matchedEmbeddedSubtitle = true;
} else {
// Subtitle is internal and we will use it
break;
}
}
}
}
}
if (matchedSub != null && !matchedEmbeddedSubtitle) {
break;
}
}
}
}
if (matchedSub != null && params.sid == null) {
if (configuration.isDisableSubtitles() || (matchedSub.getLang() != null && matchedSub.getLang().equals("off"))) {
LOGGER.trace(" Disabled the subtitles: " + matchedSub);
} else {
params.sid = matchedSub;
setMediaSubtitle(params.sid);
}
}
if (!configuration.isDisableSubtitles() && params.sid == null && getMedia() != null) {
// Check for subtitles again
File video = new File(getSystemName());
FileUtil.isSubtitlesExists(video, getMedia(), false);
if (configuration.isAutoloadExternalSubtitles()) {
boolean forcedSubsFound = false;
// Priority to external subtitles
for (DLNAMediaSubtitle sub : getMedia().getSubtitleTracksList()) {
if (matchedSub != null && matchedSub.getLang() != null && matchedSub.getLang().equals("off")) {
StringTokenizer st = new StringTokenizer(configuration.getForcedSubtitleTags(), ",");
while (sub.getFlavor() != null && st.hasMoreTokens()) {
String forcedTags = st.nextToken();
forcedTags = forcedTags.trim();
if (
sub.getFlavor().toLowerCase().indexOf(forcedTags) > -1 &&
Iso639.isCodesMatching(sub.getLang(), configuration.getForcedSubtitleLanguage())
) {
LOGGER.trace("Forcing preferred subtitles : " + sub.getLang() + "/" + sub.getFlavor());
LOGGER.trace("Forced subtitles track : " + sub);
if (sub.getExternalFile() != null) {
LOGGER.trace("Found external forced file : " + sub.getExternalFile().getAbsolutePath());
}
params.sid = sub;
setMediaSubtitle(params.sid);
forcedSubsFound = true;
break;
}
}
if (forcedSubsFound == true) {
break;
}
} else {
LOGGER.trace("Found subtitles track: " + sub);
if (sub.getExternalFile() != null) {
LOGGER.trace("Found external file: " + sub.getExternalFile().getAbsolutePath());
params.sid = sub;
setMediaSubtitle(params.sid);
break;
}
}
}
}
if (
matchedSub != null &&
matchedSub.getLang() != null &&
matchedSub.getLang().equals("off")
) {
finishedMatchingPreferences = true;
}
if (!finishedMatchingPreferences && params.sid == null) {
StringTokenizer st = new StringTokenizer(configuration.getSubtitlesLanguages(), ",");
while (st != null && st.hasMoreTokens()) {
String lang = st.nextToken();
lang = lang.trim();
LOGGER.trace("Looking for a subtitle track with lang: " + lang);
for (DLNAMediaSubtitle sub : getMedia().getSubtitleTracksList()) {
if (
sub.matchCode(lang) &&
!(
!configuration.isAutoloadExternalSubtitles() &&
sub.getExternalFile() != null
)
) {
params.sid = sub;
LOGGER.trace("Matched sub track: " + params.sid);
st = null;
break;
}
}
}
}
}
}
if (getMediaSubtitle() == null) {
LOGGER.trace("We do not want a subtitle for " + getName());
} else {
LOGGER.trace("We do want a subtitle for " + getName());
}
}
if (
(
getMediaSubtitle() == null &&
!isSubsFile() &&
getMedia() != null &&
getMedia().getDvdtrack() == 0 &&
isMuxableResult &&
mediaRenderer.isMuxH264MpegTS()
) ||
mediaRenderer.isTranscodeToMPEGTSAC3()
) {
isFileMPEGTS = true;
}
}
if (isFileMPEGTS) {
dlnaspec = "DLNA.ORG_PN=" + getMPEG_TS_SD_EU_ISOLocalizedValue(c);
if (
getMedia().isH264() &&
!VideoLanVideoStreaming.ID.equals(getPlayer().id()) &&
isMuxableResult
) {
dlnaspec = "DLNA.ORG_PN=AVC_TS_HD_24_AC3_ISO";
}
}
} else if (getMedia() != null) {
if (getMedia().isMpegTS()) {
dlnaspec = "DLNA.ORG_PN=" + getMPEG_TS_SD_EULocalizedValue(c);
if (getMedia().isH264()) {
dlnaspec = "DLNA.ORG_PN=AVC_TS_HD_50_AC3";
}
}
}
} else if (mime.equals("video/vnd.dlna.mpeg-tts")) {
// patters - on Sony BDP m2ts clips aren't listed without this
dlnaspec = "DLNA.ORG_PN=" + getMPEG_TS_SD_EULocalizedValue(c);
} else if (mime.equals("image/jpeg")) {
dlnaspec = "DLNA.ORG_PN=JPEG_LRG";
} else if (mime.equals("audio/mpeg")) {
dlnaspec = "DLNA.ORG_PN=MP3";
} else if (mime.substring(0, 9).equals("audio/L16") || mime.equals("audio/wav")) {
dlnaspec = "DLNA.ORG_PN=LPCM";
}
}
if (dlnaspec != null) {
dlnaspec = "DLNA.ORG_PN=" + mediaRenderer.getDLNAPN(dlnaspec.substring(12));
}
}
String tempString = "http-get:*:" + mime + ":" + (dlnaspec != null ? (dlnaspec + ";") : "") + getDlnaOrgOpFlags();
wireshark.append(" ").append(tempString);
addAttribute(sb, "protocolInfo", tempString);
if (subsAreValid && !mediaRenderer.useClosedCaption()) {
addAttribute(sb, "pv:subtitleFileType", getMediaSubtitle().getType().getExtension().toUpperCase());
wireshark.append(" pv:subtitleFileType=").append(getMediaSubtitle().getType().getExtension().toUpperCase());
addAttribute(sb, "pv:subtitleFileUri", getSubsURL(getMediaSubtitle()));
wireshark.append(" pv:subtitleFileUri=").append(getSubsURL(getMediaSubtitle()));
}
if (getFormat() != null && getFormat().isVideo() && getMedia() != null && getMedia().isMediaparsed()) {
if (getPlayer() == null && getMedia() != null) {
wireshark.append(" size=").append(getMedia().getSize());
addAttribute(sb, "size", getMedia().getSize());
} else {
long transcoded_size = mediaRenderer.getTranscodedSize();
if (transcoded_size != 0) {
wireshark.append(" size=").append(transcoded_size);
addAttribute(sb, "size", transcoded_size);
}
}
if (getMedia().getDuration() != null) {
if (getSplitRange().isEndLimitAvailable()) {
wireshark.append(" duration=").append(convertTimeToString(getSplitRange().getDuration(), DURATION_TIME_FORMAT));
addAttribute(sb, "duration", convertTimeToString(getSplitRange().getDuration(), DURATION_TIME_FORMAT));
} else {
wireshark.append(" duration=").append(getMedia().getDurationString());
addAttribute(sb, "duration", getMedia().getDurationString());
}
}
if (getMedia().getResolution() != null) {
addAttribute(sb, "resolution", getMedia().getResolution());
}
addAttribute(sb, "bitrate", getMedia().getRealVideoBitrate());
if (firstAudioTrack != null) {
if (firstAudioTrack.getAudioProperties().getNumberOfChannels() > 0) {
addAttribute(sb, "nrAudioChannels", firstAudioTrack.getAudioProperties().getNumberOfChannels());
}
if (firstAudioTrack.getSampleFrequency() != null) {
addAttribute(sb, "sampleFrequency", firstAudioTrack.getSampleFrequency());
}
}
} else if (getFormat() != null && getFormat().isImage()) {
if (getMedia() != null && getMedia().isMediaparsed()) {
wireshark.append(" size=").append(getMedia().getSize());
addAttribute(sb, "size", getMedia().getSize());
if (getMedia().getResolution() != null) {
addAttribute(sb, "resolution", getMedia().getResolution());
}
} else {
wireshark.append(" size=").append(length());
addAttribute(sb, "size", length());
}
} else if (getFormat() != null && getFormat().isAudio()) {
if (getMedia() != null && getMedia().isMediaparsed()) {
addAttribute(sb, "bitrate", getMedia().getBitrate());
if (getMedia().getDuration() != null) {
wireshark.append(" duration=").append(convertTimeToString(getMedia().getDuration(), DURATION_TIME_FORMAT));
addAttribute(sb, "duration", convertTimeToString(getMedia().getDuration(), DURATION_TIME_FORMAT));
}
if (firstAudioTrack != null && firstAudioTrack.getSampleFrequency() != null) {
addAttribute(sb, "sampleFrequency", firstAudioTrack.getSampleFrequency());
}
if (firstAudioTrack != null) {
addAttribute(sb, "nrAudioChannels", firstAudioTrack.getAudioProperties().getNumberOfChannels());
}
if (getPlayer() == null) {
wireshark.append(" size=").append(getMedia().getSize());
addAttribute(sb, "size", getMedia().getSize());
} else {
// Calculate WAV size
if (firstAudioTrack != null) {
int defaultFrequency = mediaRenderer.isTranscodeAudioTo441() ? 44100 : 48000;
if (!configuration.isAudioResample()) {
try {
// FIXME: Which exception could be thrown here?
defaultFrequency = firstAudioTrack.getSampleRate();
} catch (Exception e) {
LOGGER.debug("Caught exception", e);
}
}
int na = firstAudioTrack.getAudioProperties().getNumberOfChannels();
if (na > 2) { // No 5.1 dump in MPlayer
na = 2;
}
int finalSize = (int) (getMedia().getDurationInSeconds() * defaultFrequency * 2 * na);
LOGGER.trace("Calculated size for " + getSystemName() + ": " + finalSize);
wireshark.append(" size=").append(finalSize);
addAttribute(sb, "size", finalSize);
}
}
} else {
wireshark.append(" size=").append(length());
addAttribute(sb, "size", length());
}
} else {
wireshark.append(" size=").append(DLNAMediaInfo.TRANS_SIZE).append(" duration=09:59:59");
addAttribute(sb, "size", DLNAMediaInfo.TRANS_SIZE);
addAttribute(sb, "duration", "09:59:59");
addAttribute(sb, "bitrate", "1000000");
}
endTag(sb);
wireshark.append(" ").append(getFileURL());
LOGGER.trace("Network debugger: " + wireshark.toString());
wireshark.setLength(0);
sb.append(getFileURL());
closeTag(sb, "res");
}
}
if (subsAreValid) {
String subsURL = getSubsURL(getMediaSubtitle());
if (mediaRenderer.useClosedCaption()) {
openTag(sb, "sec:CaptionInfoEx");
addAttribute(sb, "sec:type", "srt");
endTag(sb);
sb.append(subsURL);
closeTag(sb, "sec:CaptionInfoEx");
LOGGER.trace("Network debugger: sec:CaptionInfoEx: sec:type=srt " + subsURL);
} else {
openTag(sb, "res");
String format = getMediaSubtitle().getType().getExtension();
if (StringUtils.isBlank(format)) {
format = "plain";
}
addAttribute(sb, "protocolInfo", "http-get:*:text/" + format + ":*");
endTag(sb);
sb.append(subsURL);
closeTag(sb, "res");
LOGGER.trace("Network debugger: http-get:*:text/" + format + ":*" + subsURL);
}
}
appendThumbnail(mediaRenderer, sb);
if (getLastModified() > 0 && !mediaRenderer.isOmitDcDate()) {
addXMLTagAndAttribute(sb, "dc:date", SDF_DATE.format(new Date(getLastModified())));
}
String uclass;
if (first != null && getMedia() != null && !getMedia().isSecondaryFormatValid()) {
uclass = "dummy";
} else {
if (isFolder()) {
uclass = "object.container.storageFolder";
boolean xbox = mediaRenderer.isXBOX();
if (xbox && getFakeParentId() != null && getFakeParentId().equals("7")) {
uclass = "object.container.album.musicAlbum";
} else if (xbox && getFakeParentId() != null && getFakeParentId().equals("6")) {
uclass = "object.container.person.musicArtist";
} else if (xbox && getFakeParentId() != null && getFakeParentId().equals("5")) {
uclass = "object.container.genre.musicGenre";
} else if (xbox && getFakeParentId() != null && getFakeParentId().equals("F")) {
uclass = "object.container.playlistContainer";
}
} else if (getFormat() != null && getFormat().isVideo()) {
uclass = "object.item.videoItem";
} else if (getFormat() != null && getFormat().isImage()) {
uclass = "object.item.imageItem.photo";
} else if (getFormat() != null && getFormat().isAudio()) {
uclass = "object.item.audioItem.musicTrack";
} else {
uclass = "object.item.videoItem";
}
}
addXMLTagAndAttribute(sb, "upnp:class", uclass);
if (isFolder()) {
closeTag(sb, "container");
} else {
closeTag(sb, "item");
}
return sb.toString();
}
/**
* Generate and append the response for the thumbnail based on the
* configuration of the renderer.
*
* @param mediaRenderer The renderer configuration.
* @param sb The StringBuilder to append the response to.
*/
private void appendThumbnail(RendererConfiguration mediaRenderer, StringBuilder sb) {
final String thumbURL = getThumbnailURL();
if (StringUtils.isNotBlank(thumbURL)) {
if (mediaRenderer.getThumbNailAsResource()) {
// Samsung 2012 (ES and EH) models do not recognize the "albumArtURI" element. Instead,
// the "res" element should be used.
// Also use "res" when faking JPEG thumbs.
openTag(sb, "res");
if (getThumbnailContentType().equals(PNG_TYPEMIME) && !mediaRenderer.isForceJPGThumbnails()) {
addAttribute(sb, "protocolInfo", "http-get:*:image/png:DLNA.ORG_PN=PNG_TN");
} else {
addAttribute(sb, "protocolInfo", "http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN");
}
endTag(sb);
sb.append(thumbURL);
closeTag(sb, "res");
} else {
// Renderers that can handle the "albumArtURI" element.
openTag(sb, "upnp:albumArtURI");
addAttribute(sb, "xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0/");
if (getThumbnailContentType().equals(PNG_TYPEMIME) && !mediaRenderer.isForceJPGThumbnails()) {
addAttribute(sb, "dlna:profileID", "PNG_TN");
} else {
addAttribute(sb, "dlna:profileID", "JPEG_TN");
}
endTag(sb);
sb.append(thumbURL);
closeTag(sb, "upnp:albumArtURI");
}
}
}
private String getRequestId(String rendererId) {
return String.format("%s|%x|%s", rendererId, hashCode(), getSystemName());
}
/**
* Plugin implementation. When this item is going to play, it will notify all the StartStopListener objects available.
*
* @see StartStopListener
*/
public void startPlaying(final String rendererId) {
final String requestId = getRequestId(rendererId);
synchronized (requestIdToRefcount) {
Integer temp = requestIdToRefcount.get(requestId);
if (temp == null) {
temp = 0;
}
final Integer refCount = temp;
requestIdToRefcount.put(requestId, refCount + 1);
if (refCount == 0) {
final DLNAResource self = this;
Runnable r = new Runnable() {
@Override
public void run() {
InetAddress rendererIp;
try {
rendererIp = InetAddress.getByName(rendererId);
RendererConfiguration renderer = RendererConfiguration.getRendererConfigurationBySocketAddress(rendererIp);
String rendererName = "unknown renderer";
try {
rendererName = renderer.getRendererName();
} catch (NullPointerException e) { }
LOGGER.info("Started playing " + getName() + " on your " + rendererName);
LOGGER.debug("The full filename of which is: " + getSystemName() + " and the address of the renderer is: " + rendererId);
} catch (UnknownHostException ex) {
LOGGER.debug("" + ex);
}
startTime = System.currentTimeMillis();
for (final ExternalListener listener : ExternalFactory.getExternalListeners()) {
if (listener instanceof StartStopListener) {
// run these asynchronously for slow handlers (e.g. logging, scrobbling)
Runnable fireStartStopEvent = new Runnable() {
@Override
public void run() {
try {
((StartStopListener) listener).nowPlaying(getMedia(), self);
} catch (Throwable t) {
LOGGER.error("Notification of startPlaying event failed for StartStopListener {}", listener.getClass(), t);
}
}
};
new Thread(fireStartStopEvent, "StartPlaying Event for " + listener.name()).start();
}
}
}
};
new Thread(r, "StartPlaying Event").start();
}
}
}
/**
* Plugin implementation. When this item is going to stop playing, it will notify all the StartStopListener
* objects available.
*
* @see StartStopListener
*/
public void stopPlaying(final String rendererId) {
final DLNAResource self = this;
final String requestId = getRequestId(rendererId);
Runnable defer = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(STOP_PLAYING_DELAY);
} catch (InterruptedException e) {
LOGGER.error("stopPlaying sleep interrupted", e);
}
synchronized (requestIdToRefcount) {
final Integer refCount = requestIdToRefcount.get(requestId);
assert refCount != null;
assert refCount > 0;
requestIdToRefcount.put(requestId, refCount - 1);
Runnable r = new Runnable() {
@Override
public void run() {
if (refCount == 1) {
InetAddress rendererIp;
try {
rendererIp = InetAddress.getByName(rendererId);
RendererConfiguration renderer = RendererConfiguration.getRendererConfigurationBySocketAddress(rendererIp);
String rendererName = "unknown renderer";
try {
rendererName = renderer.getRendererName();
} catch (NullPointerException e) { }
LOGGER.info("Stopped playing " + getName() + " on your " + rendererName);
LOGGER.debug("The full filename of which is: " + getSystemName() + " and the address of the renderer is: " + rendererId);
} catch (UnknownHostException ex) {
LOGGER.debug("" + ex);
}
// Initiate the code that figures out whether to create a resume item
if (getMedia() != null) {
long durSec = (long) getMedia().getDurationInSeconds();
if (externalProcess != null && (durSec == 0 || durSec == DLNAMediaInfo.TRANS_SIZE)) {
ProcessWrapperImpl pw = (ProcessWrapperImpl) externalProcess;
String dur = pw.getDuration();
if (StringUtils.isNotEmpty(dur)) {
getMedia().setDuration(convertStringToTime(dur));
}
}
}
PMS.get().getFrame().setStatusLine("");
internalStop();
for (final ExternalListener listener : ExternalFactory.getExternalListeners()) {
if (listener instanceof StartStopListener) {
// run these asynchronously for slow handlers (e.g. logging, scrobbling)
Runnable fireStartStopEvent = new Runnable() {
@Override
public void run() {
try {
((StartStopListener) listener).donePlaying(getMedia(), self);
} catch (Throwable t) {
LOGGER.error("Notification of donePlaying event failed for StartStopListener {}", listener.getClass(), t);
}
}
};
new Thread(fireStartStopEvent, "StopPlaying Event for " + listener.name()).start();
}
}
}
}
};
new Thread(r, "StopPlaying Event").start();
}
}
};
new Thread(defer, "StopPlaying Event Deferrer").start();
}
/**
* Returns an InputStream of this DLNAResource that starts at a given time, if possible. Very useful if video chapters are being used.
*
* @param range
* @param mediarenderer
* @return The inputstream
* @throws IOException
*/
public InputStream getInputStream(Range range, RendererConfiguration mediarenderer) throws IOException {
LOGGER.trace("Asked stream chunk : " + range + " of " + getName() + " and player " + getPlayer());
// shagrath: small fix, regression on chapters
boolean timeseek_auto = false;
// Ditlew - WDTV Live
// Ditlew - We convert byteoffset to timeoffset here. This needs the stream to be CBR!
int cbr_video_bitrate = mediarenderer.getCBRVideoBitrate();
long low = range.isByteRange() && range.isStartOffsetAvailable() ? range.asByteRange().getStart() : 0;
long high = range.isByteRange() && range.isEndLimitAvailable() ? range.asByteRange().getEnd() : -1;
Range.Time timeRange = range.createTimeRange();
if (getPlayer() != null && low > 0 && cbr_video_bitrate > 0) {
int used_bit_rated = (int) ((cbr_video_bitrate + 256) * 1024 / 8 * 1.04); // 1.04 = container overhead
if (low > used_bit_rated) {
timeRange.setStart((double) (low / (used_bit_rated)));
low = 0;
// WDTV Live - if set to TS it asks multiple times and ends by
// asking for an invalid offset which kills MEncoder
if (timeRange.getStartOrZero() > getMedia().getDurationInSeconds()) {
return null;
}
// Should we rewind a little (in case our overhead isn't accurate enough)
int rewind_secs = mediarenderer.getByteToTimeseekRewindSeconds();
timeRange.rewindStart(rewind_secs);
// shagrath:
timeseek_auto = true;
}
}
// Determine source of the stream
if (getPlayer() == null && !isResume()) {
// No transcoding
if (this instanceof IPushOutput) {
PipedOutputStream out = new PipedOutputStream();
InputStream fis = new PipedInputStream(out);
((IPushOutput) this).push(out);
if (low > 0) {
fis.skip(low);
}
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12035
return wrap(fis, high, low);
}
InputStream fis;
if (getFormat() != null && getFormat().isImage() && getMedia() != null && getMedia().getOrientation() > 1 && mediarenderer.isAutoRotateBasedOnExif()) {
// seems it's a jpeg file with an orientation setting to take care of
fis = ImagesUtil.getAutoRotateInputStreamImage(getInputStream(), getMedia().getOrientation());
if (fis == null) { // error, let's return the original one
fis = getInputStream();
}
} else {
fis = getInputStream();
}
if (fis != null) {
if (low > 0) {
fis.skip(low);
}
// http://www.ps3mediaserver.org/forum/viewtopic.php?f=11&t=12035
fis = wrap(fis, high, low);
if (timeRange.getStartOrZero() > 0 && this instanceof RealFile) {
fis.skip(MpegUtil.getPositionForTimeInMpeg(((RealFile) this).getFile(), (int) timeRange.getStartOrZero()));
}
}
return fis;
} else {
// Pipe transcoding result
OutputParams params = new OutputParams(configuration);
params.aid = getMediaAudio();
params.sid = getMediaSubtitle();
params.header = getHeaders();
params.mediaRenderer = mediarenderer;
timeRange.limit(getSplitRange());
params.timeseek = timeRange.getStartOrZero();
params.timeend = timeRange.getEndOrZero();
params.shift_scr = timeseek_auto;
if (this instanceof IPushOutput) {
params.stdin = (IPushOutput) this;
}
if (resume != null) {
params.timeseek += (long) (resume.getTimeOffset() / 1000);
if (getPlayer() == null) {
setPlayer(new FFMpegVideo());
}
}
// (Re)start transcoding process if necessary
if (externalProcess == null || externalProcess.isDestroyed()) {
// First playback attempt => start new transcoding process
LOGGER.debug("Starting transcode/remux of " + getName() + " with media info: " + getMedia().toString());
externalProcess = getPlayer().launchTranscode(this, getMedia(), params);
if (params.waitbeforestart > 0) {
LOGGER.trace("Sleeping for {} milliseconds", params.waitbeforestart);
try {
Thread.sleep(params.waitbeforestart);
} catch (InterruptedException e) {
LOGGER.error(null, e);
}
LOGGER.trace("Finished sleeping for " + params.waitbeforestart + " milliseconds");
}
} else if (
params.timeseek > 0 &&
getMedia() != null &&
getMedia().isMediaparsed() &&
getMedia().getDurationInSeconds() > 0
) {
// Time seek request => stop running transcode process and start a new one
LOGGER.debug("Requesting time seek: " + params.timeseek + " seconds");
params.minBufferSize = 1;
Runnable r = new Runnable() {
@Override
public void run() {
externalProcess.stopProcess();
}
};
new Thread(r, "External Process Stopper").start();
ProcessWrapper newExternalProcess = getPlayer().launchTranscode(this, getMedia(), params);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
LOGGER.error(null, e);
}
if (newExternalProcess == null) {
LOGGER.trace("External process instance is null... sounds not good");
}
externalProcess = newExternalProcess;
}
if (externalProcess == null) {
return null;
}
InputStream is = null;
int timer = 0;
while (is == null && timer < 10) {
is = externalProcess.getInputStream(low);
timer++;
if (is == null) {
LOGGER.debug("External input stream instance is null... sounds not good, waiting 500ms");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
}
// fail fast: don't leave a process running indefinitely if it's
// not producing output after params.waitbeforestart milliseconds + 5 seconds
// this cleans up lingering MEncoder web video transcode processes that hang
// instead of exiting
if (is == null && externalProcess != null && !externalProcess.isDestroyed()) {
Runnable r = new Runnable() {
@Override
public void run() {
LOGGER.error("External input stream instance is null... stopping process");
externalProcess.stopProcess();
}
};
new Thread(r, "Hanging External Process Stopper").start();
}
return is;
}
}
/**
* Wrap an {@link InputStream} in a {@link SizeLimitInputStream} that sets a
* limit to the maximum number of bytes to be read from the original input
* stream. The number of bytes is determined by the high and low value
* (bytes = high - low). If the high value is less than the low value, the
* input stream is not wrapped and returned as is.
*
* @param input
* The input stream to wrap.
* @param high
* The high value.
* @param low
* The low value.
* @return The resulting input stream.
*/
private InputStream wrap(InputStream input, long high, long low) {
if (input != null && high > low) {
long bytes = (high - (low < 0 ? 0 : low)) + 1;
LOGGER.trace("Using size-limiting stream (" + bytes + " bytes)");
return new SizeLimitInputStream(input, bytes);
}
return input;
}
public String mimeType() {
if (getPlayer() != null) {
// FIXME: This cannot be right. A player like FFmpeg can output many
// formats depending on the media and the renderer. Also, players are
// singletons. Therefore it is impossible to have exactly one mime
// type to return.
return getPlayer().mimeType();
} else if (getMedia() != null && getMedia().isMediaparsed()) {
return getMedia().getMimeType();
} else if (getFormat() != null) {
return getFormat().mimeType();
} else {
return getDefaultMimeType(getSpecificType());
}
}
/**
* Prototype function. Original comment: need to override if some thumbnail work is to be done when mediaparserv2 enabled
*/
public void checkThumbnail() {
// need to override if some thumbnail work is to be done when mediaparserv2 enabled
}
/**
* Checks if a thumbnail exists, and, if not, generates one (if possible).
* Called from Request/RequestV2 in response to thumbnail requests e.g. HEAD /get/0$1$0$42$3/thumbnail0000%5BExample.mkv
* Calls DLNAMediaInfo.generateThumbnail, which in turn calls DLNAMediaInfo.parse.
*
* @param inputFile File to check or generate the thumbnail for.
*/
protected void checkThumbnail(InputFile inputFile) {
if (getMedia() != null && !getMedia().isThumbready() && configuration.isThumbnailGenerationEnabled()) {
getMedia().setThumbready(true);
getMedia().generateThumbnail(inputFile, getFormat(), getType());
if (getMedia().getThumb() != null && configuration.getUseCache() && inputFile.getFile() != null) {
PMS.get().getDatabase().updateThumbnail(inputFile.getFile().getAbsolutePath(), inputFile.getFile().lastModified(), getType(), getMedia());
}
}
}
/**
* Returns the input stream for this resource's generic thumbnail,
* which is the first of:
* - its Format icon, if any
* - the fallback image, if any
* - the default video icon
*
* @param fallback
* the fallback image, or null.
*
* @return The InputStream
* @throws IOException
*/
public InputStream getGenericThumbnailInputStream(String fallback) throws IOException {
String thumb = fallback;
if (getFormat() != null && getFormat().getIcon() != null) {
thumb = getFormat().getIcon();
}
// Thumb could be:
if (thumb != null) {
// A local file
if (new File(thumb).exists()) {
return new FileInputStream(thumb);
}
// A jar resource
InputStream is;
if ((is = getResourceInputStream(thumb)) != null) {
return is;
}
// A URL
try {
return downloadAndSend(thumb, true);
} catch (Exception e) {}
}
// Or none of the above
String defaultThumbnailImage = "images/thumbnail-video-256.png";
if (getDefaultRenderer() != null && getDefaultRenderer().isForceJPGThumbnails()) {
defaultThumbnailImage = "images/thumbnail-video-120.jpg";
}
return getResourceInputStream(defaultThumbnailImage);
}
/**
* Returns the input stream for this resource's thumbnail
* (or a default image if a thumbnail can't be found).
* Typically overridden by a subclass.
*
* @return The InputStream
* @throws IOException
*/
public InputStream getThumbnailInputStream() throws IOException {
String id = null;
if (getMediaAudio() != null) {
id = getMediaAudio().getLang();
}
if (getMediaSubtitle() != null && getMediaSubtitle().getId() != -1) {
id = getMediaSubtitle().getLang();
}
if ((getMediaSubtitle() != null || getMediaAudio() != null) && StringUtils.isBlank(id)) {
id = DLNAMediaLang.UND;
}
if (id != null) {
String code = Iso639.getISO639_2Code(id.toLowerCase());
return getResourceInputStream("/images/codes/" + code + ".png");
}
if (isAvisynth()) {
return getResourceInputStream("/images/logo-avisynth.png");
}
return getGenericThumbnailInputStream(null);
}
public String getThumbnailContentType() {
return HTTPResource.JPEG_TYPEMIME;
}
public int getType() {
if (getFormat() != null) {
return getFormat().getType();
} else {
return Format.UNKNOWN;
}
}
/**
* Prototype function.
*
* @return true if child can be added to other folder.
* @see #addChild(DLNAResource)
*/
public abstract boolean isValid();
public boolean allowScan() {
return false;
}
/**
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(getClass().getSimpleName());
result.append(" [id=");
result.append(getId());
result.append(", name=");
result.append(getName());
result.append(", full path=");
result.append(getResourceId());
result.append(", ext=");
result.append(getFormat());
result.append(", discovered=");
result.append(isDiscovered());
result.append("]");
return result.toString();
}
/**
* Returns the specific type of resource. Valid types are defined in {@link Format}.
*
* @return The specific type
*/
protected int getSpecificType() {
return specificType;
}
/**
* Set the specific type of this resource. Valid types are defined in {@link Format}.
*
* @param specificType The specific type to set.
*/
protected void setSpecificType(int specificType) {
this.specificType = specificType;
}
/**
* Returns the {@link Format} of this resource, which defines its capabilities.
*
* @return The format of this resource.
*/
public Format getFormat() {
return format;
}
/**
* Sets the {@link Format} of this resource, thereby defining its capabilities.
*
* @param format The format to set.
*/
protected void setFormat(Format format) {
this.format = format;
// Set deprecated variable for backwards compatibility
ext = format;
}
/**
* @deprecated Use {@link #getFormat()} instead.
*
* @return The format of this resource.
*/
@Deprecated
public Format getExt() {
return getFormat();
}
/**
* @deprecated Use {@link #setFormat(Format)} instead.
*
* @param format The format to set.
*/
@Deprecated
protected void setExt(Format format) {
setFormat(format);
}
/**
* Returns the {@link DLNAMediaInfo} object for this resource, containing the
* specifics of this resource, e.g. the duration.
*
* @return The object containing detailed information.
*/
public DLNAMediaInfo getMedia() {
return media;
}
/**
* Sets the the {@link DLNAMediaInfo} object that contains all specifics for
* this resource.
*
* @param media The object containing detailed information.
* @since 1.50
*/
protected void setMedia(DLNAMediaInfo media) {
this.media = media;
}
/**
* Returns the {@link DLNAMediaAudio} object for this resource that contains
* the audio specifics. A resource can have many audio tracks, this method
* returns the one that should be played.
*
* @return The audio object containing detailed information.
* @since 1.50
*/
public DLNAMediaAudio getMediaAudio() {
return media_audio;
}
/**
* Sets the {@link DLNAMediaAudio} object for this resource that contains
* the audio specifics. A resource can have many audio tracks, this method
* determines the one that should be played.
*
* @param mediaAudio The audio object containing detailed information.
* @since 1.50
*/
protected void setMediaAudio(DLNAMediaAudio mediaAudio) {
this.media_audio = mediaAudio;
}
/**
* Returns the {@link DLNAMediaSubtitle} object for this resource that
* contains the specifics for the subtitles. A resource can have many
* subtitles, this method returns the one that should be displayed.
*
* @return The subtitle object containing detailed information.
* @since 1.50
*/
public DLNAMediaSubtitle getMediaSubtitle() {
return media_subtitle;
}
/**
* Sets the {@link DLNAMediaSubtitle} object for this resource that
* contains the specifics for the subtitles. A resource can have many
* subtitles, this method determines the one that should be used.
*
* @param mediaSubtitle The subtitle object containing detailed information.
* @since 1.50
*/
protected void setMediaSubtitle(DLNAMediaSubtitle mediaSubtitle) {
this.media_subtitle = mediaSubtitle;
}
/**
* @deprecated Use {@link #getLastModified()} instead.
*
* Returns the timestamp at which this resource was last modified.
*
* @return The timestamp.
*/
@Deprecated
public long getLastmodified() {
return getLastModified();
}
/**
* Returns the timestamp at which this resource was last modified.
*
* @return The timestamp.
* @since 1.71.0
*/
public long getLastModified() {
return lastmodified; // TODO rename lastmodified -> lastModified
}
/**
* @deprecated Use {@link #setLastModified(long)} instead.
*
* Sets the timestamp at which this resource was last modified.
*
* @param lastModified The timestamp to set.
* @since 1.50
*/
@Deprecated
protected void setLastmodified(long lastModified) {
setLastModified(lastModified);
}
/**
* Sets the timestamp at which this resource was last modified.
*
* @param lastModified The timestamp to set.
* @since 1.71.0
*/
protected void setLastModified(long lastModified) {
this.lastmodified = lastModified; // TODO rename lastmodified -> lastModified
}
/**
* Returns the {@link Player} object that is used to encode this resource
* for the renderer. Can be null.
*
* @return The player object.
*/
public Player getPlayer() {
return player;
}
/**
* Sets the {@link Player} object that is to be used to encode this
* resource for the renderer. The player object can be null.
*
* @param player The player object to set.
* @since 1.50
*/
protected void setPlayer(Player player) {
this.player = player;
}
/**
* Returns true when the details of this resource have already been
* investigated. This helps is not doing the same work twice.
*
* @return True if discovered, false otherwise.
*/
public boolean isDiscovered() {
return discovered;
}
/**
* Set to true when the details of this resource have already been
* investigated. This helps is not doing the same work twice.
*
* @param discovered Set to true if this resource is discovered,
* false otherwise.
* @since 1.50
*/
protected void setDiscovered(boolean discovered) {
this.discovered = discovered;
}
/**
* @Deprecated use {@link #isSubsFile()} instead
*/
@Deprecated
protected boolean isSrtFile() {
return isSubsFile();
}
/**
* Returns true if this resource has subtitles in a file.
*
* @return the srtFile
* @since 1.50
*/
protected boolean isSubsFile() {
return srtFile;
}
/**
* @Deprecated use {@link #setSubsFile()} instead
*/
@Deprecated
protected void setSrtFile(boolean srtFile) {
setSubsFile(srtFile);
}
/**
* Set to true if this resource has subtitles in a file.
*
* @param srtFile the srtFile to set
* @since 1.50
*/
protected void setSubsFile(boolean srtFile) {
this.srtFile = srtFile;
}
/**
* Returns the update counter for this resource. When the resource needs
* to be refreshed, its counter is updated.
*
* @return The update counter.
* @see #notifyRefresh()
*/
public int getUpdateId() {
return updateId;
}
/**
* Sets the update counter for this resource. When the resource needs
* to be refreshed, its counter should be updated.
*
* @param updateId The counter value to set.
* @since 1.50
*/
protected void setUpdateId(int updateId) {
this.updateId = updateId;
}
/**
* Returns the update counter for all resources. When all resources need
* to be refreshed, this counter is updated.
*
* @return The system update counter.
* @since 1.50
*/
public static int getSystemUpdateId() {
return systemUpdateId;
}
/**
* Sets the update counter for all resources. When all resources need
* to be refreshed, this counter should be updated.
*
* @param systemUpdateId The system update counter to set.
* @since 1.50
*/
public static void setSystemUpdateId(int systemUpdateId) {
DLNAResource.systemUpdateId = systemUpdateId;
}
/**
* Returns whether or not this is a nameless resource.
*
* @return True if the resource is nameless.
*/
public boolean isNoName() {
return noName;
}
/**
* Sets whether or not this is a nameless resource. This is particularly
* useful in the virtual TRANSCODE folder for a file, where the same file
* is copied many times with different audio and subtitle settings. In that
* case the name of the file becomes irrelevant and only the settings
* need to be shown.
*
* @param noName Set to true if the resource is nameless.
* @since 1.50
*/
protected void setNoName(boolean noName) {
this.noName = noName;
}
/**
* Returns the from - to time range for this resource.
*
* @return The time range.
*/
public Range.Time getSplitRange() {
return splitRange;
}
/**
* Sets the from - to time range for this resource.
*
* @param splitRange The time range to set.
* @since 1.50
*/
protected void setSplitRange(Range.Time splitRange) {
this.splitRange = splitRange;
}
/**
* Returns the number of the track to split from this resource.
*
* @return the splitTrack
* @since 1.50
*/
protected int getSplitTrack() {
return splitTrack;
}
/**
* Sets the number of the track from this resource to split.
*
* @param splitTrack The track number.
* @since 1.50
*/
protected void setSplitTrack(int splitTrack) {
this.splitTrack = splitTrack;
}
/**
* Returns the default renderer configuration for this resource.
*
* @return The default renderer configuration.
* @since 1.50
*/
protected RendererConfiguration getDefaultRenderer() {
return defaultRenderer;
}
/**
* Sets the default renderer configuration for this resource.
*
* @param defaultRenderer The default renderer configuration to set.
* @since 1.50
*/
protected void setDefaultRenderer(RendererConfiguration defaultRenderer) {
this.defaultRenderer = defaultRenderer;
}
/**
* Returns whether or not this resource is handled by AviSynth.
*
* @return True if handled by AviSynth, otherwise false.
* @since 1.50
*/
protected boolean isAvisynth() {
return avisynth;
}
/**
* Sets whether or not this resource is handled by AviSynth.
*
* @param avisynth Set to true if handled by Avisyth, otherwise false.
* @since 1.50
*/
protected void setAvisynth(boolean avisynth) {
this.avisynth = avisynth;
}
/**
* Returns true if transcoding should be skipped for this resource.
*
* @return True if transcoding should be skipped, false otherwise.
* @since 1.50
*/
protected boolean isSkipTranscode() {
return skipTranscode;
}
/**
* Set to true if transcoding should be skipped for this resource.
*
* @param skipTranscode Set to true if trancoding should be skipped, false
* otherwise.
* @since 1.50
*/
protected void setSkipTranscode(boolean skipTranscode) {
this.skipTranscode = skipTranscode;
}
/**
* Returns the list of children for this resource.
*
* @return List of children objects.
*/
public List<DLNAResource> getChildren() {
return children;
}
/**
* Sets the list of children for this resource.
*
* @param children The list of children to set.
* @since 1.50
*/
protected void setChildren(List<DLNAResource> children) {
this.children = children;
}
/**
* @deprecated use {@link #getLastChildId()} instead.
*/
@Deprecated
protected int getLastChildrenId() {
return getLastChildId();
}
/**
* Returns the numerical ID of the last child added.
*
* @return The ID.
* @since 1.80.0
*/
protected int getLastChildId() {
return lastChildrenId;
}
/**
* @deprecated use {@link #setLastChildId(int)} instead.
*/
@Deprecated
protected void setLastChildrenId(int lastChildId) {
setLastChildId(lastChildId);
}
/**
* Sets the numerical ID of the last child added.
*
* @param lastChildId The ID to set.
* @since 1.80.0
*/
protected void setLastChildId(int lastChildId) {
this.lastChildrenId = lastChildId;
}
/**
* Returns the timestamp when this resource was last refreshed.
*
* @return The timestamp.
*/
long getLastRefreshTime() {
return lastRefreshTime;
}
/**
* Sets the timestamp when this resource was last refreshed.
*
* @param lastRefreshTime The timestamp to set.
* @since 1.50
*/
protected void setLastRefreshTime(long lastRefreshTime) {
this.lastRefreshTime = lastRefreshTime;
}
private static final int DEPTH_WARNING_LIMIT = 7;
private boolean depthLimit() {
DLNAResource tmp = this;
int depth = 0;
while (tmp != null) {
tmp = tmp.getParent();
depth++;
}
return (depth > DEPTH_WARNING_LIMIT);
}
public boolean isSearched() {
return false;
}
public byte[] getHeaders() {
return null;
}
public void attach(String key, Object data) {
if (attachments == null) {
attachments = new HashMap<>();
}
attachments.put(key, data);
}
public Object getAttachment(String key) {
return attachments == null ? null : attachments.get(key);
}
public boolean isURLResolved() {
return false;
}
////////////////////////////////////////////////////
// Subtitle handling
////////////////////////////////////////////////////
private SubSelect getSubSelector(boolean create) {
if (
configuration.isDisableSubtitles() ||
!configuration.isAutoloadExternalSubtitles() ||
configuration.isHideLiveSubtitlesFolder()
) {
return null;
}
// Search for transcode folder
for (DLNAResource r : getChildren()) {
if (r instanceof SubSelect) {
return (SubSelect) r;
}
}
if (create) {
SubSelect vf = new SubSelect();
addChildInternal(vf);
return vf;
}
return null;
}
public boolean isSubSelectable() {
return false;
}
private boolean liveSubs(DLNAResource r) {
DLNAMediaSubtitle s = r.getMediaSubtitle();
if (s != null) {
return StringUtils.isNotEmpty(s.getLiveSubURL());
}
return false;
}
////////////////////////////////////////////////////
// Resume handling
////////////////////////////////////////////////////
private ResumeObj resume;
private int resHash;
private long startTime;
private void internalStop() {
DLNAResource res = resumeStop();
final RootFolder root = ((defaultRenderer != null) ? defaultRenderer.getRootFolder() : null);
if (root != null) {
if (res == null) {
res = this.clone();
} else {
res = res.clone();
}
root.stopPlaying(res);
}
}
public int resumeHash() {
return resHash;
}
public ResumeObj getResume() {
return resume;
}
public void setResume(ResumeObj r) {
resume = r;
}
public boolean isResumeable() {
if (getFormat() != null) {
// Only resume videos
return getFormat().isVideo();
}
return true;
}
private DLNAResource resumeStop() {
if (!configuration.isResumeEnabled() || !isResumeable()) {
return null;
}
if (resume != null) {
resume.stop(startTime, (long) (getMedia().getDurationInSeconds() * 1000));
if (resume.isDone()) {
getParent().getChildren().remove(this);
}
notifyRefresh();
} else {
for (DLNAResource res : getParent().getChildren()) {
if (res.isResume() && res.getName().equals(getName())) {
res.resume.stop(startTime, (long) (getMedia().getDurationInSeconds() * 1000));
if (res.resume.isDone()) {
getParent().getChildren().remove(res);
return null;
}
return res;
}
}
ResumeObj r = ResumeObj.store(this, startTime);
if (r != null) {
DLNAResource clone = this.clone();
clone.resume = r;
clone.resHash = resHash;
clone.setMedia(getMedia());
clone.setPlayer(getPlayer());
getParent().addChildInternal(clone);
return clone;
}
}
return null;
}
public final boolean isResume() {
return isResumeable() && (resume != null);
}
public int minPlayTime() {
return configuration.getMinPlayTime();
}
private String resumeStr(String s) {
if (isResume()) {
return Messages.getString("PMS.134") + ": " + s;
} else {
return s;
}
}
/**
* Handle last played stuff
*
* This method should be overridden by all media types that should be
* added to the last played list.
* By default it just returns null which means the resource is ignored
* in the last played file.
*/
public String write() {
return null;
}
private ExternalListener masterParent;
public void setMasterParent(ExternalListener r) {
if (masterParent == null) {
// If master is already set ignore this
masterParent = r;
}
}
public ExternalListener getMasterParent() {
return masterParent;
}
}
| true | true | public final String getDidlString(RendererConfiguration mediaRenderer) {
boolean subsAreValid = false;
StringBuilder sb = new StringBuilder();
if (!configuration.isDisableSubtitles() && StringUtils.isNotBlank(mediaRenderer.getSupportedSubtitles()) && getMedia() != null && getPlayer() == null) {
OutputParams params = new OutputParams(configuration);
Player.setAudioAndSubs(getSystemName(), getMedia(), params);
if (params.sid != null) {
String[] supportedSubs = mediaRenderer.getSupportedSubtitles().split(",");
for (String supportedSub : supportedSubs) {
if (params.sid.getType().toString().equals(supportedSub.trim().toUpperCase())) {
setMediaSubtitle(params.sid);
subsAreValid = true;
break;
}
}
}
}
if (isFolder()) {
openTag(sb, "container");
} else {
openTag(sb, "item");
}
addAttribute(sb, "id", getResourceId());
if (isFolder()) {
if (!isDiscovered() && childrenNumber() == 0) {
// When a folder has not been scanned for resources, it will automatically have zero children.
// Some renderers like XBMC will assume a folder is empty when encountering childCount="0" and
// will not display the folder. By returning childCount="1" these renderers will still display
// the folder. When it is opened, its children will be discovered and childrenNumber() will be
// set to the right value.
addAttribute(sb, "childCount", 1);
} else {
addAttribute(sb, "childCount", childrenNumber());
}
}
addAttribute(sb, "parentID", getParentId());
addAttribute(sb, "restricted", "true");
endTag(sb);
StringBuilder wireshark = new StringBuilder();
final DLNAMediaAudio firstAudioTrack = getMedia() != null ? getMedia().getFirstAudioTrack() : null;
if (firstAudioTrack != null && StringUtils.isNotBlank(firstAudioTrack.getSongname())) {
wireshark.append(firstAudioTrack.getSongname()).append(getPlayer() != null && !configuration.isHideEngineNames() ? (" [" + getPlayer().name() + "]") : "");
addXMLTagAndAttribute(
sb,
"dc:title",
encodeXML(mediaRenderer.getDcTitle(resumeStr(wireshark.toString()), this))
);
} else { // Ditlew - org
// Ditlew
wireshark.append(((isFolder() || getPlayer() == null && subsAreValid) ? getDisplayName() : mediaRenderer.getUseSameExtension(getDisplayName(mediaRenderer))));
String tmp = (isFolder() || getPlayer() == null && subsAreValid) ? getDisplayName() : mediaRenderer.getUseSameExtension(getDisplayName(mediaRenderer));
addXMLTagAndAttribute(
sb,
"dc:title",
encodeXML(mediaRenderer.getDcTitle(resumeStr(tmp), this))
);
}
if (firstAudioTrack != null) {
if (StringUtils.isNotBlank(firstAudioTrack.getAlbum())) {
addXMLTagAndAttribute(sb, "upnp:album", encodeXML(firstAudioTrack.getAlbum()));
}
if (StringUtils.isNotBlank(firstAudioTrack.getArtist())) {
addXMLTagAndAttribute(sb, "upnp:artist", encodeXML(firstAudioTrack.getArtist()));
addXMLTagAndAttribute(sb, "dc:creator", encodeXML(firstAudioTrack.getArtist()));
}
if (StringUtils.isNotBlank(firstAudioTrack.getGenre())) {
addXMLTagAndAttribute(sb, "upnp:genre", encodeXML(firstAudioTrack.getGenre()));
}
if (firstAudioTrack.getTrack() > 0) {
addXMLTagAndAttribute(sb, "upnp:originalTrackNumber", "" + firstAudioTrack.getTrack());
}
}
if (!isFolder()) {
int indexCount = 1;
if (mediaRenderer.isDLNALocalizationRequired()) {
indexCount = getDLNALocalesCount();
}
for (int c = 0; c < indexCount; c++) {
openTag(sb, "res");
/**
* DLNA.ORG_OP flags
*
* Two booleans (binary digits) which determine what transport operations the renderer is allowed to
* perform (in the form of HTTP request headers): the first digit allows the renderer to send
* TimeSeekRange.DLNA.ORG (seek by time) headers; the second allows it to send RANGE (seek by byte)
* headers.
*
* 00 - no seeking (or even pausing) allowed
* 01 - seek by byte
* 10 - seek by time
* 11 - seek by both
*
* See here for an example of how these options can be mapped to keys on the renderer's controller:
* http://www.ps3mediaserver.org/forum/viewtopic.php?f=2&t=2908&p=12550#p12550
*
* Note that seek-by-byte is the preferred option for streamed files [1] and seek-by-time is the
* preferred option for transcoded files.
*
* [1] see http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=15841&p=76201#p76201
*
* seek-by-time requires a) support by the renderer (via the SeekByTime renderer conf option)
* and b) support by the transcode engine.
*
* The seek-by-byte fallback doesn't work well with transcoded files [2], but it's better than
* disabling seeking (and pausing) altogether.
*
* [2] http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=3507&p=16567#p16567 (bottom post)
*/
dlnaOrgOpFlags = "01"; // seek by byte (exclusive)
if (mediaRenderer.isSeekByTime() && getPlayer() != null && getPlayer().isTimeSeekable()) {
/**
* Some renderers - e.g. the PS3 and Panasonic TVs - behave erratically when
* transcoding if we keep the default seek-by-byte permission on when permitting
* seek-by-time: http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=15841
*
* It's not clear if this is a bug in the DLNA libraries of these renderers or a bug
* in UMS, but setting an option in the renderer conf that disables seek-by-byte when
* we permit seek-by-time - e.g.:
*
* SeekByTime = exclusive
*
* works around it.
*/
/**
* TODO (e.g. in a beta release): set seek-by-time (exclusive) here for *all* renderers:
* seek-by-byte isn't needed here (both the renderer and the engine support seek-by-time)
* and may be buggy on other renderers than the ones we currently handle.
*
* In the unlikely event that a renderer *requires* seek-by-both here, it can
* opt in with (e.g.):
*
* SeekByTime = both
*/
if (mediaRenderer.isSeekByTimeExclusive()) {
dlnaOrgOpFlags = "10"; // seek by time (exclusive)
} else {
dlnaOrgOpFlags = "11"; // seek by both
}
}
addAttribute(sb, "xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0/");
// FIXME: There is a flaw here. In addChild(DLNAResource) the mime type
// is determined for the default renderer. This renderer may rewrite the
// mime type based on its configuration. Looking up that mime type is
// not guaranteed to return a match for another renderer.
String mime = mediaRenderer.getMimeType(mimeType());
if (mime == null) {
// FIXME: Setting the default to "video/mpeg" leaves a lot of audio files in the cold.
mime = "video/mpeg";
}
dlnaspec = null;
if (mediaRenderer.isDLNAOrgPNUsed()) {
if (mediaRenderer.isPS3()) {
if (mime.equals("video/x-divx")) {
dlnaspec = "DLNA.ORG_PN=AVI";
} else if (mime.equals("video/x-ms-wmv") && getMedia() != null && getMedia().getHeight() > 700) {
dlnaspec = "DLNA.ORG_PN=WMVHIGH_PRO";
}
} else {
if (mime.equals("video/mpeg")) {
dlnaspec = "DLNA.ORG_PN=" + getMPEG_PS_PALLocalizedValue(c);
if (getPlayer() != null) {
boolean isFileMPEGTS = TsMuxeRVideo.ID.equals(getPlayer().id()) || VideoLanVideoStreaming.ID.equals(getPlayer().id());
boolean isMuxableResult = getMedia().isMuxable(mediaRenderer);
boolean isBravia = mediaRenderer.isBRAVIA();
if (
!isFileMPEGTS &&
(
(
configuration.isMencoderMuxWhenCompatible() &&
MEncoderVideo.ID.equals(getPlayer().id())
) ||
(
configuration.isFFmpegMuxWhenCompatible() &&
FFMpegVideo.ID.equals(getPlayer().id())
)
)
) {
if (isBravia) {
/**
* Sony Bravia TVs (and possibly other renderers) need ORG_PN to be accurate.
* If the value does not match the media, it won't play the media.
* Often we can lazily predict the correct value to send, but due to
* MEncoder needing to mux via tsMuxeR, we need to work it all out
* before even sending the file list to these devices.
* This is very time-consuming so we should a) avoid using this
* chunk of code whenever possible, and b) design a better system.
* Ideally we would just mux to MPEG-PS instead of MPEG-TS so we could
* know it will always be PS, but most renderers will not accept H.264
* inside MPEG-PS. Another option may be to always produce MPEG-TS
* instead and we should check if that will be OK for all renderers.
*
* This code block comes from Player.setAudioAndSubs()
*/
boolean finishedMatchingPreferences = false;
OutputParams params = new OutputParams(configuration);
if (getMedia() != null) {
// check for preferred audio
StringTokenizer st = new StringTokenizer(configuration.getAudioLanguages(), ",");
while (st != null && st.hasMoreTokens()) {
String lang = st.nextToken();
lang = lang.trim();
LOGGER.trace("Looking for an audio track with lang: " + lang);
for (DLNAMediaAudio audio : getMedia().getAudioTracksList()) {
if (audio.matchCode(lang)) {
params.aid = audio;
LOGGER.trace("Matched audio track: " + audio);
st = null;
break;
}
}
}
}
if (params.aid == null && getMedia().getAudioTracksList().size() > 0) {
// Take a default audio track, dts first if possible
for (DLNAMediaAudio audio : getMedia().getAudioTracksList()) {
if (audio.isDTS()) {
params.aid = audio;
LOGGER.trace("Found priority audio track with DTS: " + audio);
break;
}
}
if (params.aid == null) {
params.aid = getMedia().getAudioTracksList().get(0);
LOGGER.trace("Chose a default audio track: " + params.aid);
}
}
String currentLang = null;
DLNAMediaSubtitle matchedSub = null;
if (params.aid != null) {
currentLang = params.aid.getLang();
}
if (params.sid != null && params.sid.getId() == -1) {
LOGGER.trace("Don't want subtitles!");
params.sid = null;
setMediaSubtitle(params.sid);
finishedMatchingPreferences = true;
}
if (!finishedMatchingPreferences && params.sid != null && !StringUtils.isEmpty(params.sid.getLiveSubURL())) {
// live subtitles
// currently only open subtitles
LOGGER.debug("Live subtitles " + params.sid.getLiveSubURL());
try {
matchedSub = params.sid;
String file = OpenSubtitle.fetchSubs(matchedSub.getLiveSubURL(), matchedSub.getLiveSubFile());
if (!StringUtils.isEmpty(file)) {
matchedSub.setExternalFile(new File(file));
params.sid = matchedSub;
setMediaSubtitle(params.sid);
finishedMatchingPreferences = true;
}
} catch (IOException e) {
}
}
if (!finishedMatchingPreferences) {
StringTokenizer st1 = new StringTokenizer(configuration.getAudioSubLanguages(), ";");
boolean matchedEmbeddedSubtitle = false;
while (st1.hasMoreTokens()) {
String pair = st1.nextToken();
if (pair.contains(",")) {
String audio = pair.substring(0, pair.indexOf(','));
String sub = pair.substring(pair.indexOf(',') + 1);
audio = audio.trim();
sub = sub.trim();
LOGGER.trace("Searching for a match for: " + currentLang + " with " + audio + " and " + sub);
if (Iso639.isCodesMatching(audio, currentLang) || (currentLang != null && audio.equals("*"))) {
if (sub.equals("off")) {
matchedSub = new DLNAMediaSubtitle();
matchedSub.setLang("off");
} else {
for (DLNAMediaSubtitle present_sub : getMedia().getSubtitleTracksList()) {
if (present_sub.matchCode(sub) || sub.equals("*")) {
if (present_sub.getExternalFile() != null) {
if (configuration.isAutoloadExternalSubtitles()) {
// Subtitle is external and we want external subtitles, look no further
matchedSub = present_sub;
LOGGER.trace(" Found a match: " + matchedSub);
break;
} else {
// Subtitle is external but we do not want external subtitles, keep searching
LOGGER.trace(" External subtitle ignored because of user setting: " + present_sub);
}
} else {
matchedSub = present_sub;
LOGGER.trace(" Found a match: " + matchedSub);
if (configuration.isAutoloadExternalSubtitles()) {
// Subtitle is internal and we will wait to see if an external one is available instead
matchedEmbeddedSubtitle = true;
} else {
// Subtitle is internal and we will use it
break;
}
}
}
}
}
if (matchedSub != null && !matchedEmbeddedSubtitle) {
break;
}
}
}
}
if (matchedSub != null && params.sid == null) {
if (configuration.isDisableSubtitles() || (matchedSub.getLang() != null && matchedSub.getLang().equals("off"))) {
LOGGER.trace(" Disabled the subtitles: " + matchedSub);
} else {
params.sid = matchedSub;
setMediaSubtitle(params.sid);
}
}
if (!configuration.isDisableSubtitles() && params.sid == null && getMedia() != null) {
// Check for subtitles again
File video = new File(getSystemName());
FileUtil.isSubtitlesExists(video, getMedia(), false);
if (configuration.isAutoloadExternalSubtitles()) {
boolean forcedSubsFound = false;
// Priority to external subtitles
for (DLNAMediaSubtitle sub : getMedia().getSubtitleTracksList()) {
if (matchedSub != null && matchedSub.getLang() != null && matchedSub.getLang().equals("off")) {
StringTokenizer st = new StringTokenizer(configuration.getForcedSubtitleTags(), ",");
while (sub.getFlavor() != null && st.hasMoreTokens()) {
String forcedTags = st.nextToken();
forcedTags = forcedTags.trim();
if (
sub.getFlavor().toLowerCase().indexOf(forcedTags) > -1 &&
Iso639.isCodesMatching(sub.getLang(), configuration.getForcedSubtitleLanguage())
) {
LOGGER.trace("Forcing preferred subtitles : " + sub.getLang() + "/" + sub.getFlavor());
LOGGER.trace("Forced subtitles track : " + sub);
if (sub.getExternalFile() != null) {
LOGGER.trace("Found external forced file : " + sub.getExternalFile().getAbsolutePath());
}
params.sid = sub;
setMediaSubtitle(params.sid);
forcedSubsFound = true;
break;
}
}
if (forcedSubsFound == true) {
break;
}
} else {
LOGGER.trace("Found subtitles track: " + sub);
if (sub.getExternalFile() != null) {
LOGGER.trace("Found external file: " + sub.getExternalFile().getAbsolutePath());
params.sid = sub;
setMediaSubtitle(params.sid);
break;
}
}
}
}
if (
matchedSub != null &&
matchedSub.getLang() != null &&
matchedSub.getLang().equals("off")
) {
finishedMatchingPreferences = true;
}
if (!finishedMatchingPreferences && params.sid == null) {
StringTokenizer st = new StringTokenizer(configuration.getSubtitlesLanguages(), ",");
while (st != null && st.hasMoreTokens()) {
String lang = st.nextToken();
lang = lang.trim();
LOGGER.trace("Looking for a subtitle track with lang: " + lang);
for (DLNAMediaSubtitle sub : getMedia().getSubtitleTracksList()) {
if (
sub.matchCode(lang) &&
!(
!configuration.isAutoloadExternalSubtitles() &&
sub.getExternalFile() != null
)
) {
params.sid = sub;
LOGGER.trace("Matched sub track: " + params.sid);
st = null;
break;
}
}
}
}
}
}
if (getMediaSubtitle() == null) {
LOGGER.trace("We do not want a subtitle for " + getName());
} else {
LOGGER.trace("We do want a subtitle for " + getName());
}
}
if (
(
getMediaSubtitle() == null &&
!isSubsFile() &&
getMedia() != null &&
getMedia().getDvdtrack() == 0 &&
isMuxableResult &&
mediaRenderer.isMuxH264MpegTS()
) ||
mediaRenderer.isTranscodeToMPEGTSAC3()
) {
isFileMPEGTS = true;
}
}
if (isFileMPEGTS) {
dlnaspec = "DLNA.ORG_PN=" + getMPEG_TS_SD_EU_ISOLocalizedValue(c);
if (
getMedia().isH264() &&
!VideoLanVideoStreaming.ID.equals(getPlayer().id()) &&
isMuxableResult
) {
dlnaspec = "DLNA.ORG_PN=AVC_TS_HD_24_AC3_ISO";
}
}
} else if (getMedia() != null) {
if (getMedia().isMpegTS()) {
dlnaspec = "DLNA.ORG_PN=" + getMPEG_TS_SD_EULocalizedValue(c);
if (getMedia().isH264()) {
dlnaspec = "DLNA.ORG_PN=AVC_TS_HD_50_AC3";
}
}
}
} else if (mime.equals("video/vnd.dlna.mpeg-tts")) {
// patters - on Sony BDP m2ts clips aren't listed without this
dlnaspec = "DLNA.ORG_PN=" + getMPEG_TS_SD_EULocalizedValue(c);
} else if (mime.equals("image/jpeg")) {
dlnaspec = "DLNA.ORG_PN=JPEG_LRG";
} else if (mime.equals("audio/mpeg")) {
dlnaspec = "DLNA.ORG_PN=MP3";
} else if (mime.substring(0, 9).equals("audio/L16") || mime.equals("audio/wav")) {
dlnaspec = "DLNA.ORG_PN=LPCM";
}
}
if (dlnaspec != null) {
dlnaspec = "DLNA.ORG_PN=" + mediaRenderer.getDLNAPN(dlnaspec.substring(12));
}
}
String tempString = "http-get:*:" + mime + ":" + (dlnaspec != null ? (dlnaspec + ";") : "") + getDlnaOrgOpFlags();
wireshark.append(" ").append(tempString);
addAttribute(sb, "protocolInfo", tempString);
if (subsAreValid && !mediaRenderer.useClosedCaption()) {
addAttribute(sb, "pv:subtitleFileType", getMediaSubtitle().getType().getExtension().toUpperCase());
wireshark.append(" pv:subtitleFileType=").append(getMediaSubtitle().getType().getExtension().toUpperCase());
addAttribute(sb, "pv:subtitleFileUri", getSubsURL(getMediaSubtitle()));
wireshark.append(" pv:subtitleFileUri=").append(getSubsURL(getMediaSubtitle()));
}
if (getFormat() != null && getFormat().isVideo() && getMedia() != null && getMedia().isMediaparsed()) {
if (getPlayer() == null && getMedia() != null) {
wireshark.append(" size=").append(getMedia().getSize());
addAttribute(sb, "size", getMedia().getSize());
} else {
long transcoded_size = mediaRenderer.getTranscodedSize();
if (transcoded_size != 0) {
wireshark.append(" size=").append(transcoded_size);
addAttribute(sb, "size", transcoded_size);
}
}
if (getMedia().getDuration() != null) {
if (getSplitRange().isEndLimitAvailable()) {
wireshark.append(" duration=").append(convertTimeToString(getSplitRange().getDuration(), DURATION_TIME_FORMAT));
addAttribute(sb, "duration", convertTimeToString(getSplitRange().getDuration(), DURATION_TIME_FORMAT));
} else {
wireshark.append(" duration=").append(getMedia().getDurationString());
addAttribute(sb, "duration", getMedia().getDurationString());
}
}
if (getMedia().getResolution() != null) {
addAttribute(sb, "resolution", getMedia().getResolution());
}
addAttribute(sb, "bitrate", getMedia().getRealVideoBitrate());
if (firstAudioTrack != null) {
if (firstAudioTrack.getAudioProperties().getNumberOfChannels() > 0) {
addAttribute(sb, "nrAudioChannels", firstAudioTrack.getAudioProperties().getNumberOfChannels());
}
if (firstAudioTrack.getSampleFrequency() != null) {
addAttribute(sb, "sampleFrequency", firstAudioTrack.getSampleFrequency());
}
}
} else if (getFormat() != null && getFormat().isImage()) {
if (getMedia() != null && getMedia().isMediaparsed()) {
wireshark.append(" size=").append(getMedia().getSize());
addAttribute(sb, "size", getMedia().getSize());
if (getMedia().getResolution() != null) {
addAttribute(sb, "resolution", getMedia().getResolution());
}
} else {
wireshark.append(" size=").append(length());
addAttribute(sb, "size", length());
}
} else if (getFormat() != null && getFormat().isAudio()) {
if (getMedia() != null && getMedia().isMediaparsed()) {
addAttribute(sb, "bitrate", getMedia().getBitrate());
if (getMedia().getDuration() != null) {
wireshark.append(" duration=").append(convertTimeToString(getMedia().getDuration(), DURATION_TIME_FORMAT));
addAttribute(sb, "duration", convertTimeToString(getMedia().getDuration(), DURATION_TIME_FORMAT));
}
if (firstAudioTrack != null && firstAudioTrack.getSampleFrequency() != null) {
addAttribute(sb, "sampleFrequency", firstAudioTrack.getSampleFrequency());
}
if (firstAudioTrack != null) {
addAttribute(sb, "nrAudioChannels", firstAudioTrack.getAudioProperties().getNumberOfChannels());
}
if (getPlayer() == null) {
wireshark.append(" size=").append(getMedia().getSize());
addAttribute(sb, "size", getMedia().getSize());
} else {
// Calculate WAV size
if (firstAudioTrack != null) {
int defaultFrequency = mediaRenderer.isTranscodeAudioTo441() ? 44100 : 48000;
if (!configuration.isAudioResample()) {
try {
// FIXME: Which exception could be thrown here?
defaultFrequency = firstAudioTrack.getSampleRate();
} catch (Exception e) {
LOGGER.debug("Caught exception", e);
}
}
int na = firstAudioTrack.getAudioProperties().getNumberOfChannels();
if (na > 2) { // No 5.1 dump in MPlayer
na = 2;
}
int finalSize = (int) (getMedia().getDurationInSeconds() * defaultFrequency * 2 * na);
LOGGER.trace("Calculated size for " + getSystemName() + ": " + finalSize);
wireshark.append(" size=").append(finalSize);
addAttribute(sb, "size", finalSize);
}
}
} else {
wireshark.append(" size=").append(length());
addAttribute(sb, "size", length());
}
} else {
wireshark.append(" size=").append(DLNAMediaInfo.TRANS_SIZE).append(" duration=09:59:59");
addAttribute(sb, "size", DLNAMediaInfo.TRANS_SIZE);
addAttribute(sb, "duration", "09:59:59");
addAttribute(sb, "bitrate", "1000000");
}
endTag(sb);
wireshark.append(" ").append(getFileURL());
LOGGER.trace("Network debugger: " + wireshark.toString());
wireshark.setLength(0);
sb.append(getFileURL());
closeTag(sb, "res");
}
}
if (subsAreValid) {
String subsURL = getSubsURL(getMediaSubtitle());
if (mediaRenderer.useClosedCaption()) {
openTag(sb, "sec:CaptionInfoEx");
addAttribute(sb, "sec:type", "srt");
endTag(sb);
sb.append(subsURL);
closeTag(sb, "sec:CaptionInfoEx");
LOGGER.trace("Network debugger: sec:CaptionInfoEx: sec:type=srt " + subsURL);
} else {
openTag(sb, "res");
String format = getMediaSubtitle().getType().getExtension();
if (StringUtils.isBlank(format)) {
format = "plain";
}
addAttribute(sb, "protocolInfo", "http-get:*:text/" + format + ":*");
endTag(sb);
sb.append(subsURL);
closeTag(sb, "res");
LOGGER.trace("Network debugger: http-get:*:text/" + format + ":*" + subsURL);
}
}
appendThumbnail(mediaRenderer, sb);
if (getLastModified() > 0 && !mediaRenderer.isOmitDcDate()) {
addXMLTagAndAttribute(sb, "dc:date", SDF_DATE.format(new Date(getLastModified())));
}
String uclass;
if (first != null && getMedia() != null && !getMedia().isSecondaryFormatValid()) {
uclass = "dummy";
} else {
if (isFolder()) {
uclass = "object.container.storageFolder";
boolean xbox = mediaRenderer.isXBOX();
if (xbox && getFakeParentId() != null && getFakeParentId().equals("7")) {
uclass = "object.container.album.musicAlbum";
} else if (xbox && getFakeParentId() != null && getFakeParentId().equals("6")) {
uclass = "object.container.person.musicArtist";
} else if (xbox && getFakeParentId() != null && getFakeParentId().equals("5")) {
uclass = "object.container.genre.musicGenre";
} else if (xbox && getFakeParentId() != null && getFakeParentId().equals("F")) {
uclass = "object.container.playlistContainer";
}
} else if (getFormat() != null && getFormat().isVideo()) {
uclass = "object.item.videoItem";
} else if (getFormat() != null && getFormat().isImage()) {
uclass = "object.item.imageItem.photo";
} else if (getFormat() != null && getFormat().isAudio()) {
uclass = "object.item.audioItem.musicTrack";
} else {
uclass = "object.item.videoItem";
}
}
addXMLTagAndAttribute(sb, "upnp:class", uclass);
if (isFolder()) {
closeTag(sb, "container");
} else {
closeTag(sb, "item");
}
return sb.toString();
}
| public final String getDidlString(RendererConfiguration mediaRenderer) {
boolean subsAreValid = false;
StringBuilder sb = new StringBuilder();
if (!configuration.isDisableSubtitles() && StringUtils.isNotBlank(mediaRenderer.getSupportedSubtitles()) && getMedia() != null && getPlayer() == null) {
OutputParams params = new OutputParams(configuration);
Player.setAudioAndSubs(getSystemName(), getMedia(), params);
if (params.sid != null) {
String[] supportedSubs = mediaRenderer.getSupportedSubtitles().split(",");
for (String supportedSub : supportedSubs) {
if (params.sid.getType().toString().equals(supportedSub.trim().toUpperCase())) {
setMediaSubtitle(params.sid);
subsAreValid = true;
break;
}
}
}
}
if (isFolder()) {
openTag(sb, "container");
} else {
openTag(sb, "item");
}
addAttribute(sb, "id", getResourceId());
if (isFolder()) {
if (!isDiscovered() && childrenNumber() == 0) {
// When a folder has not been scanned for resources, it will automatically have zero children.
// Some renderers like XBMC will assume a folder is empty when encountering childCount="0" and
// will not display the folder. By returning childCount="1" these renderers will still display
// the folder. When it is opened, its children will be discovered and childrenNumber() will be
// set to the right value.
addAttribute(sb, "childCount", 1);
} else {
addAttribute(sb, "childCount", childrenNumber());
}
}
addAttribute(sb, "parentID", getParentId());
addAttribute(sb, "restricted", "true");
endTag(sb);
StringBuilder wireshark = new StringBuilder();
final DLNAMediaAudio firstAudioTrack = getMedia() != null ? getMedia().getFirstAudioTrack() : null;
if (firstAudioTrack != null && StringUtils.isNotBlank(firstAudioTrack.getSongname())) {
wireshark.append(firstAudioTrack.getSongname()).append(getPlayer() != null && !configuration.isHideEngineNames() ? (" [" + getPlayer().name() + "]") : "");
addXMLTagAndAttribute(
sb,
"dc:title",
encodeXML(mediaRenderer.getDcTitle(resumeStr(wireshark.toString()), this))
);
} else { // Ditlew - org
// Ditlew
wireshark.append(((isFolder() || getPlayer() == null && subsAreValid) ? getDisplayName() : mediaRenderer.getUseSameExtension(getDisplayName(mediaRenderer))));
String tmp = (isFolder() || getPlayer() == null && subsAreValid) ? getDisplayName() : mediaRenderer.getUseSameExtension(getDisplayName(mediaRenderer));
addXMLTagAndAttribute(
sb,
"dc:title",
encodeXML(mediaRenderer.getDcTitle(resumeStr(tmp), this))
);
}
if (firstAudioTrack != null) {
if (StringUtils.isNotBlank(firstAudioTrack.getAlbum())) {
addXMLTagAndAttribute(sb, "upnp:album", encodeXML(firstAudioTrack.getAlbum()));
}
if (StringUtils.isNotBlank(firstAudioTrack.getArtist())) {
addXMLTagAndAttribute(sb, "upnp:artist", encodeXML(firstAudioTrack.getArtist()));
addXMLTagAndAttribute(sb, "dc:creator", encodeXML(firstAudioTrack.getArtist()));
}
if (StringUtils.isNotBlank(firstAudioTrack.getGenre())) {
addXMLTagAndAttribute(sb, "upnp:genre", encodeXML(firstAudioTrack.getGenre()));
}
if (firstAudioTrack.getTrack() > 0) {
addXMLTagAndAttribute(sb, "upnp:originalTrackNumber", "" + firstAudioTrack.getTrack());
}
}
if (!isFolder()) {
int indexCount = 1;
if (mediaRenderer.isDLNALocalizationRequired()) {
indexCount = getDLNALocalesCount();
}
for (int c = 0; c < indexCount; c++) {
openTag(sb, "res");
/**
* DLNA.ORG_OP flags
*
* Two booleans (binary digits) which determine what transport operations the renderer is allowed to
* perform (in the form of HTTP request headers): the first digit allows the renderer to send
* TimeSeekRange.DLNA.ORG (seek by time) headers; the second allows it to send RANGE (seek by byte)
* headers.
*
* 00 - no seeking (or even pausing) allowed
* 01 - seek by byte
* 10 - seek by time
* 11 - seek by both
*
* See here for an example of how these options can be mapped to keys on the renderer's controller:
* http://www.ps3mediaserver.org/forum/viewtopic.php?f=2&t=2908&p=12550#p12550
*
* Note that seek-by-byte is the preferred option for streamed files [1] and seek-by-time is the
* preferred option for transcoded files.
*
* [1] see http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=15841&p=76201#p76201
*
* seek-by-time requires a) support by the renderer (via the SeekByTime renderer conf option)
* and b) support by the transcode engine.
*
* The seek-by-byte fallback doesn't work well with transcoded files [2], but it's better than
* disabling seeking (and pausing) altogether.
*
* [2] http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=3507&p=16567#p16567 (bottom post)
*/
dlnaOrgOpFlags = "01"; // seek by byte (exclusive)
if (mediaRenderer.isSeekByTime() && getPlayer() != null && getPlayer().isTimeSeekable()) {
/**
* Some renderers - e.g. the PS3 and Panasonic TVs - behave erratically when
* transcoding if we keep the default seek-by-byte permission on when permitting
* seek-by-time: http://www.ps3mediaserver.org/forum/viewtopic.php?f=6&t=15841
*
* It's not clear if this is a bug in the DLNA libraries of these renderers or a bug
* in UMS, but setting an option in the renderer conf that disables seek-by-byte when
* we permit seek-by-time - e.g.:
*
* SeekByTime = exclusive
*
* works around it.
*/
/**
* TODO (e.g. in a beta release): set seek-by-time (exclusive) here for *all* renderers:
* seek-by-byte isn't needed here (both the renderer and the engine support seek-by-time)
* and may be buggy on other renderers than the ones we currently handle.
*
* In the unlikely event that a renderer *requires* seek-by-both here, it can
* opt in with (e.g.):
*
* SeekByTime = both
*/
if (mediaRenderer.isSeekByTimeExclusive()) {
dlnaOrgOpFlags = "10"; // seek by time (exclusive)
} else {
dlnaOrgOpFlags = "11"; // seek by both
}
}
addAttribute(sb, "xmlns:dlna", "urn:schemas-dlna-org:metadata-1-0/");
// FIXME: There is a flaw here. In addChild(DLNAResource) the mime type
// is determined for the default renderer. This renderer may rewrite the
// mime type based on its configuration. Looking up that mime type is
// not guaranteed to return a match for another renderer.
String mime = mediaRenderer.getMimeType(mimeType());
if (mime == null) {
// FIXME: Setting the default to "video/mpeg" leaves a lot of audio files in the cold.
mime = "video/mpeg";
}
dlnaspec = null;
if (mediaRenderer.isDLNAOrgPNUsed()) {
if (mediaRenderer.isPS3()) {
if (mime.equals("video/x-divx")) {
dlnaspec = "DLNA.ORG_PN=AVI";
} else if (mime.equals("video/x-ms-wmv") && getMedia() != null && getMedia().getHeight() > 700) {
dlnaspec = "DLNA.ORG_PN=WMVHIGH_PRO";
}
} else {
if (mime.equals("video/mpeg")) {
dlnaspec = "DLNA.ORG_PN=" + getMPEG_PS_PALLocalizedValue(c);
if (getPlayer() != null) {
boolean isFileMPEGTS = TsMuxeRVideo.ID.equals(getPlayer().id()) || VideoLanVideoStreaming.ID.equals(getPlayer().id());
boolean isMuxableResult = getMedia().isMuxable(mediaRenderer);
boolean isBravia = mediaRenderer.isBRAVIA();
if (
!isFileMPEGTS &&
(
(
configuration.isMencoderMuxWhenCompatible() &&
MEncoderVideo.ID.equals(getPlayer().id())
) ||
(
(
configuration.isFFmpegMuxWhenCompatible() ||
configuration.isFFmpegMuxWithTsMuxerWhenCompatible()
) &&
FFMpegVideo.ID.equals(getPlayer().id())
)
)
) {
if (isBravia) {
/**
* Sony Bravia TVs (and possibly other renderers) need ORG_PN to be accurate.
* If the value does not match the media, it won't play the media.
* Often we can lazily predict the correct value to send, but due to
* MEncoder needing to mux via tsMuxeR, we need to work it all out
* before even sending the file list to these devices.
* This is very time-consuming so we should a) avoid using this
* chunk of code whenever possible, and b) design a better system.
* Ideally we would just mux to MPEG-PS instead of MPEG-TS so we could
* know it will always be PS, but most renderers will not accept H.264
* inside MPEG-PS. Another option may be to always produce MPEG-TS
* instead and we should check if that will be OK for all renderers.
*
* This code block comes from Player.setAudioAndSubs()
*/
boolean finishedMatchingPreferences = false;
OutputParams params = new OutputParams(configuration);
if (getMedia() != null) {
// check for preferred audio
StringTokenizer st = new StringTokenizer(configuration.getAudioLanguages(), ",");
while (st != null && st.hasMoreTokens()) {
String lang = st.nextToken();
lang = lang.trim();
LOGGER.trace("Looking for an audio track with lang: " + lang);
for (DLNAMediaAudio audio : getMedia().getAudioTracksList()) {
if (audio.matchCode(lang)) {
params.aid = audio;
LOGGER.trace("Matched audio track: " + audio);
st = null;
break;
}
}
}
}
if (params.aid == null && getMedia().getAudioTracksList().size() > 0) {
// Take a default audio track, dts first if possible
for (DLNAMediaAudio audio : getMedia().getAudioTracksList()) {
if (audio.isDTS()) {
params.aid = audio;
LOGGER.trace("Found priority audio track with DTS: " + audio);
break;
}
}
if (params.aid == null) {
params.aid = getMedia().getAudioTracksList().get(0);
LOGGER.trace("Chose a default audio track: " + params.aid);
}
}
String currentLang = null;
DLNAMediaSubtitle matchedSub = null;
if (params.aid != null) {
currentLang = params.aid.getLang();
}
if (params.sid != null && params.sid.getId() == -1) {
LOGGER.trace("Don't want subtitles!");
params.sid = null;
setMediaSubtitle(params.sid);
finishedMatchingPreferences = true;
}
if (!finishedMatchingPreferences && params.sid != null && !StringUtils.isEmpty(params.sid.getLiveSubURL())) {
// live subtitles
// currently only open subtitles
LOGGER.debug("Live subtitles " + params.sid.getLiveSubURL());
try {
matchedSub = params.sid;
String file = OpenSubtitle.fetchSubs(matchedSub.getLiveSubURL(), matchedSub.getLiveSubFile());
if (!StringUtils.isEmpty(file)) {
matchedSub.setExternalFile(new File(file));
params.sid = matchedSub;
setMediaSubtitle(params.sid);
finishedMatchingPreferences = true;
}
} catch (IOException e) {
}
}
if (!finishedMatchingPreferences) {
StringTokenizer st1 = new StringTokenizer(configuration.getAudioSubLanguages(), ";");
boolean matchedEmbeddedSubtitle = false;
while (st1.hasMoreTokens()) {
String pair = st1.nextToken();
if (pair.contains(",")) {
String audio = pair.substring(0, pair.indexOf(','));
String sub = pair.substring(pair.indexOf(',') + 1);
audio = audio.trim();
sub = sub.trim();
LOGGER.trace("Searching for a match for: " + currentLang + " with " + audio + " and " + sub);
if (Iso639.isCodesMatching(audio, currentLang) || (currentLang != null && audio.equals("*"))) {
if (sub.equals("off")) {
matchedSub = new DLNAMediaSubtitle();
matchedSub.setLang("off");
} else {
for (DLNAMediaSubtitle present_sub : getMedia().getSubtitleTracksList()) {
if (present_sub.matchCode(sub) || sub.equals("*")) {
if (present_sub.getExternalFile() != null) {
if (configuration.isAutoloadExternalSubtitles()) {
// Subtitle is external and we want external subtitles, look no further
matchedSub = present_sub;
LOGGER.trace(" Found a match: " + matchedSub);
break;
} else {
// Subtitle is external but we do not want external subtitles, keep searching
LOGGER.trace(" External subtitle ignored because of user setting: " + present_sub);
}
} else {
matchedSub = present_sub;
LOGGER.trace(" Found a match: " + matchedSub);
if (configuration.isAutoloadExternalSubtitles()) {
// Subtitle is internal and we will wait to see if an external one is available instead
matchedEmbeddedSubtitle = true;
} else {
// Subtitle is internal and we will use it
break;
}
}
}
}
}
if (matchedSub != null && !matchedEmbeddedSubtitle) {
break;
}
}
}
}
if (matchedSub != null && params.sid == null) {
if (configuration.isDisableSubtitles() || (matchedSub.getLang() != null && matchedSub.getLang().equals("off"))) {
LOGGER.trace(" Disabled the subtitles: " + matchedSub);
} else {
params.sid = matchedSub;
setMediaSubtitle(params.sid);
}
}
if (!configuration.isDisableSubtitles() && params.sid == null && getMedia() != null) {
// Check for subtitles again
File video = new File(getSystemName());
FileUtil.isSubtitlesExists(video, getMedia(), false);
if (configuration.isAutoloadExternalSubtitles()) {
boolean forcedSubsFound = false;
// Priority to external subtitles
for (DLNAMediaSubtitle sub : getMedia().getSubtitleTracksList()) {
if (matchedSub != null && matchedSub.getLang() != null && matchedSub.getLang().equals("off")) {
StringTokenizer st = new StringTokenizer(configuration.getForcedSubtitleTags(), ",");
while (sub.getFlavor() != null && st.hasMoreTokens()) {
String forcedTags = st.nextToken();
forcedTags = forcedTags.trim();
if (
sub.getFlavor().toLowerCase().indexOf(forcedTags) > -1 &&
Iso639.isCodesMatching(sub.getLang(), configuration.getForcedSubtitleLanguage())
) {
LOGGER.trace("Forcing preferred subtitles : " + sub.getLang() + "/" + sub.getFlavor());
LOGGER.trace("Forced subtitles track : " + sub);
if (sub.getExternalFile() != null) {
LOGGER.trace("Found external forced file : " + sub.getExternalFile().getAbsolutePath());
}
params.sid = sub;
setMediaSubtitle(params.sid);
forcedSubsFound = true;
break;
}
}
if (forcedSubsFound == true) {
break;
}
} else {
LOGGER.trace("Found subtitles track: " + sub);
if (sub.getExternalFile() != null) {
LOGGER.trace("Found external file: " + sub.getExternalFile().getAbsolutePath());
params.sid = sub;
setMediaSubtitle(params.sid);
break;
}
}
}
}
if (
matchedSub != null &&
matchedSub.getLang() != null &&
matchedSub.getLang().equals("off")
) {
finishedMatchingPreferences = true;
}
if (!finishedMatchingPreferences && params.sid == null) {
StringTokenizer st = new StringTokenizer(configuration.getSubtitlesLanguages(), ",");
while (st != null && st.hasMoreTokens()) {
String lang = st.nextToken();
lang = lang.trim();
LOGGER.trace("Looking for a subtitle track with lang: " + lang);
for (DLNAMediaSubtitle sub : getMedia().getSubtitleTracksList()) {
if (
sub.matchCode(lang) &&
!(
!configuration.isAutoloadExternalSubtitles() &&
sub.getExternalFile() != null
)
) {
params.sid = sub;
LOGGER.trace("Matched sub track: " + params.sid);
st = null;
break;
}
}
}
}
}
}
if (getMediaSubtitle() == null) {
LOGGER.trace("We do not want a subtitle for " + getName());
} else {
LOGGER.trace("We do want a subtitle for " + getName());
}
}
if (
(
getMediaSubtitle() == null &&
!isSubsFile() &&
getMedia() != null &&
getMedia().getDvdtrack() == 0 &&
isMuxableResult &&
mediaRenderer.isMuxH264MpegTS()
) ||
mediaRenderer.isTranscodeToMPEGTSAC3()
) {
isFileMPEGTS = true;
}
}
if (isFileMPEGTS) {
dlnaspec = "DLNA.ORG_PN=" + getMPEG_TS_SD_EU_ISOLocalizedValue(c);
if (
getMedia().isH264() &&
!VideoLanVideoStreaming.ID.equals(getPlayer().id()) &&
isMuxableResult
) {
dlnaspec = "DLNA.ORG_PN=AVC_TS_HD_24_AC3_ISO";
}
}
} else if (getMedia() != null) {
if (getMedia().isMpegTS()) {
dlnaspec = "DLNA.ORG_PN=" + getMPEG_TS_SD_EULocalizedValue(c);
if (getMedia().isH264()) {
dlnaspec = "DLNA.ORG_PN=AVC_TS_HD_50_AC3";
}
}
}
} else if (mime.equals("video/vnd.dlna.mpeg-tts")) {
// patters - on Sony BDP m2ts clips aren't listed without this
dlnaspec = "DLNA.ORG_PN=" + getMPEG_TS_SD_EULocalizedValue(c);
} else if (mime.equals("image/jpeg")) {
dlnaspec = "DLNA.ORG_PN=JPEG_LRG";
} else if (mime.equals("audio/mpeg")) {
dlnaspec = "DLNA.ORG_PN=MP3";
} else if (mime.substring(0, 9).equals("audio/L16") || mime.equals("audio/wav")) {
dlnaspec = "DLNA.ORG_PN=LPCM";
}
}
if (dlnaspec != null) {
dlnaspec = "DLNA.ORG_PN=" + mediaRenderer.getDLNAPN(dlnaspec.substring(12));
}
}
String tempString = "http-get:*:" + mime + ":" + (dlnaspec != null ? (dlnaspec + ";") : "") + getDlnaOrgOpFlags();
wireshark.append(" ").append(tempString);
addAttribute(sb, "protocolInfo", tempString);
if (subsAreValid && !mediaRenderer.useClosedCaption()) {
addAttribute(sb, "pv:subtitleFileType", getMediaSubtitle().getType().getExtension().toUpperCase());
wireshark.append(" pv:subtitleFileType=").append(getMediaSubtitle().getType().getExtension().toUpperCase());
addAttribute(sb, "pv:subtitleFileUri", getSubsURL(getMediaSubtitle()));
wireshark.append(" pv:subtitleFileUri=").append(getSubsURL(getMediaSubtitle()));
}
if (getFormat() != null && getFormat().isVideo() && getMedia() != null && getMedia().isMediaparsed()) {
if (getPlayer() == null && getMedia() != null) {
wireshark.append(" size=").append(getMedia().getSize());
addAttribute(sb, "size", getMedia().getSize());
} else {
long transcoded_size = mediaRenderer.getTranscodedSize();
if (transcoded_size != 0) {
wireshark.append(" size=").append(transcoded_size);
addAttribute(sb, "size", transcoded_size);
}
}
if (getMedia().getDuration() != null) {
if (getSplitRange().isEndLimitAvailable()) {
wireshark.append(" duration=").append(convertTimeToString(getSplitRange().getDuration(), DURATION_TIME_FORMAT));
addAttribute(sb, "duration", convertTimeToString(getSplitRange().getDuration(), DURATION_TIME_FORMAT));
} else {
wireshark.append(" duration=").append(getMedia().getDurationString());
addAttribute(sb, "duration", getMedia().getDurationString());
}
}
if (getMedia().getResolution() != null) {
addAttribute(sb, "resolution", getMedia().getResolution());
}
addAttribute(sb, "bitrate", getMedia().getRealVideoBitrate());
if (firstAudioTrack != null) {
if (firstAudioTrack.getAudioProperties().getNumberOfChannels() > 0) {
addAttribute(sb, "nrAudioChannels", firstAudioTrack.getAudioProperties().getNumberOfChannels());
}
if (firstAudioTrack.getSampleFrequency() != null) {
addAttribute(sb, "sampleFrequency", firstAudioTrack.getSampleFrequency());
}
}
} else if (getFormat() != null && getFormat().isImage()) {
if (getMedia() != null && getMedia().isMediaparsed()) {
wireshark.append(" size=").append(getMedia().getSize());
addAttribute(sb, "size", getMedia().getSize());
if (getMedia().getResolution() != null) {
addAttribute(sb, "resolution", getMedia().getResolution());
}
} else {
wireshark.append(" size=").append(length());
addAttribute(sb, "size", length());
}
} else if (getFormat() != null && getFormat().isAudio()) {
if (getMedia() != null && getMedia().isMediaparsed()) {
addAttribute(sb, "bitrate", getMedia().getBitrate());
if (getMedia().getDuration() != null) {
wireshark.append(" duration=").append(convertTimeToString(getMedia().getDuration(), DURATION_TIME_FORMAT));
addAttribute(sb, "duration", convertTimeToString(getMedia().getDuration(), DURATION_TIME_FORMAT));
}
if (firstAudioTrack != null && firstAudioTrack.getSampleFrequency() != null) {
addAttribute(sb, "sampleFrequency", firstAudioTrack.getSampleFrequency());
}
if (firstAudioTrack != null) {
addAttribute(sb, "nrAudioChannels", firstAudioTrack.getAudioProperties().getNumberOfChannels());
}
if (getPlayer() == null) {
wireshark.append(" size=").append(getMedia().getSize());
addAttribute(sb, "size", getMedia().getSize());
} else {
// Calculate WAV size
if (firstAudioTrack != null) {
int defaultFrequency = mediaRenderer.isTranscodeAudioTo441() ? 44100 : 48000;
if (!configuration.isAudioResample()) {
try {
// FIXME: Which exception could be thrown here?
defaultFrequency = firstAudioTrack.getSampleRate();
} catch (Exception e) {
LOGGER.debug("Caught exception", e);
}
}
int na = firstAudioTrack.getAudioProperties().getNumberOfChannels();
if (na > 2) { // No 5.1 dump in MPlayer
na = 2;
}
int finalSize = (int) (getMedia().getDurationInSeconds() * defaultFrequency * 2 * na);
LOGGER.trace("Calculated size for " + getSystemName() + ": " + finalSize);
wireshark.append(" size=").append(finalSize);
addAttribute(sb, "size", finalSize);
}
}
} else {
wireshark.append(" size=").append(length());
addAttribute(sb, "size", length());
}
} else {
wireshark.append(" size=").append(DLNAMediaInfo.TRANS_SIZE).append(" duration=09:59:59");
addAttribute(sb, "size", DLNAMediaInfo.TRANS_SIZE);
addAttribute(sb, "duration", "09:59:59");
addAttribute(sb, "bitrate", "1000000");
}
endTag(sb);
wireshark.append(" ").append(getFileURL());
LOGGER.trace("Network debugger: " + wireshark.toString());
wireshark.setLength(0);
sb.append(getFileURL());
closeTag(sb, "res");
}
}
if (subsAreValid) {
String subsURL = getSubsURL(getMediaSubtitle());
if (mediaRenderer.useClosedCaption()) {
openTag(sb, "sec:CaptionInfoEx");
addAttribute(sb, "sec:type", "srt");
endTag(sb);
sb.append(subsURL);
closeTag(sb, "sec:CaptionInfoEx");
LOGGER.trace("Network debugger: sec:CaptionInfoEx: sec:type=srt " + subsURL);
} else {
openTag(sb, "res");
String format = getMediaSubtitle().getType().getExtension();
if (StringUtils.isBlank(format)) {
format = "plain";
}
addAttribute(sb, "protocolInfo", "http-get:*:text/" + format + ":*");
endTag(sb);
sb.append(subsURL);
closeTag(sb, "res");
LOGGER.trace("Network debugger: http-get:*:text/" + format + ":*" + subsURL);
}
}
appendThumbnail(mediaRenderer, sb);
if (getLastModified() > 0 && !mediaRenderer.isOmitDcDate()) {
addXMLTagAndAttribute(sb, "dc:date", SDF_DATE.format(new Date(getLastModified())));
}
String uclass;
if (first != null && getMedia() != null && !getMedia().isSecondaryFormatValid()) {
uclass = "dummy";
} else {
if (isFolder()) {
uclass = "object.container.storageFolder";
boolean xbox = mediaRenderer.isXBOX();
if (xbox && getFakeParentId() != null && getFakeParentId().equals("7")) {
uclass = "object.container.album.musicAlbum";
} else if (xbox && getFakeParentId() != null && getFakeParentId().equals("6")) {
uclass = "object.container.person.musicArtist";
} else if (xbox && getFakeParentId() != null && getFakeParentId().equals("5")) {
uclass = "object.container.genre.musicGenre";
} else if (xbox && getFakeParentId() != null && getFakeParentId().equals("F")) {
uclass = "object.container.playlistContainer";
}
} else if (getFormat() != null && getFormat().isVideo()) {
uclass = "object.item.videoItem";
} else if (getFormat() != null && getFormat().isImage()) {
uclass = "object.item.imageItem.photo";
} else if (getFormat() != null && getFormat().isAudio()) {
uclass = "object.item.audioItem.musicTrack";
} else {
uclass = "object.item.videoItem";
}
}
addXMLTagAndAttribute(sb, "upnp:class", uclass);
if (isFolder()) {
closeTag(sb, "container");
} else {
closeTag(sb, "item");
}
return sb.toString();
}
|
diff --git a/src/main/java/org/iplantc/iptol/client/ApplicationLayout.java b/src/main/java/org/iplantc/iptol/client/ApplicationLayout.java
index 206a27fd..e0cfd7aa 100644
--- a/src/main/java/org/iplantc/iptol/client/ApplicationLayout.java
+++ b/src/main/java/org/iplantc/iptol/client/ApplicationLayout.java
@@ -1,270 +1,271 @@
package org.iplantc.iptol.client;
import java.util.ArrayList;
import org.iplantc.iptol.client.events.LogoutEvent;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.event.BorderLayoutEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.Component;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.layout.BorderLayout;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.toolbar.FillToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Image;
/**
*
* @author sriram This class draws the layout for the discovery env.
*/
public class ApplicationLayout extends Viewport
{
private IptolClientConstants constants = (IptolClientConstants)GWT.create(IptolClientConstants.class);
private IptolDisplayStrings displayStrings = (IptolDisplayStrings) GWT.create(IptolDisplayStrings.class);
private ContentPanel north;
private Component west;
private Component center;
private ContentPanel south;
private ToolBar toolBar;
private final BorderLayout layout;
private HorizontalPanel headerPanel;
private HorizontalPanel footerPanel;
private ApplicationStatusBar statusBar;
private ArrayList<Button> buttonsSystem = new ArrayList<Button>();
public ApplicationLayout()
{
// build top level layout
layout = new BorderLayout();
//make sure we re-draw when a panel expands
layout.addListener(Events.Expand,new Listener<BorderLayoutEvent>()
{
public void handleEvent(BorderLayoutEvent be)
{
layout();
}
});
setLayout(layout);
north = new ContentPanel();
south = new ContentPanel();
toolBar = new ToolBar();
statusBar = new ApplicationStatusBar();
}
private void assembleHeader()
{
drawHeader();
north.add(headerPanel);
//add tool bar to north panel
north.add(toolBar);
}
private void assembleFooter()
{
drawFooter();
south.add(footerPanel);
statusBar.setHeight("22px");
south.add(statusBar);
south.addText(displayStrings.copyright());
}
private void drawFooter()
{
footerPanel = new HorizontalPanel();
footerPanel.setBorders(false);
}
private void drawHeader()
{
// add our logo...This should be changed to DE logo later
headerPanel = new HorizontalPanel();
headerPanel.addStyleName("iptol_logo");
headerPanel.setBorders(false);
Image logo = new Image(constants.iplantLogo());
logo.setHeight("85px");
headerPanel.add(logo);
}
private void drawNorth()
{
north.setHeaderVisible(false);
north.setBodyStyleName("iptol_header");
north.setBodyStyle("backgroundColor:#4B680C;");
BorderLayoutData data = new BorderLayoutData(LayoutRegion.NORTH, 115);
data.setCollapsible(false);
data.setFloatable(false);
data.setHideCollapseTool(true);
data.setSplit(false);
data.setMargins(new Margins(0, 0, 0, 0));
add(north,data);
}
private void drawSouth()
{
BorderLayoutData data = new BorderLayoutData(LayoutRegion.SOUTH, 47);
data.setSplit(false);
data.setCollapsible(false);
data.setFloatable(false);
data.setMargins(new Margins(0, 0, 0, 0));
south.setHeaderVisible(false);
south.setBodyStyleName("iptol_footer");
add(south,data);
}
private void doLogout()
{
statusBar.resetStatus();
EventBus eventbus = EventBus.getInstance();
LogoutEvent event = new LogoutEvent();
eventbus.fireEvent(event);
}
private Button buildButton(String caption,ArrayList<Button> dest,SelectionListener<ButtonEvent> event,int position)
{
Button ret = new Button(caption,event);
ret.setStyleAttribute("padding-right","5px");
ret.setIcon(IconHelper.createPath("./images/User.png"));
ret.setHeight("20px");
ret.hide();
dest.add(position,ret);
return ret;
}
private Button buildButton(String caption,ArrayList<Button> dest,SelectionListener<ButtonEvent> event)
{
return buildButton(caption,dest,event,dest.size());
}
private void assembleToolbar()
{
// Add basic tool bar
toolBar.setBorders(false);
toolBar.setStyleName("iptol_toolbar");
toolBar.setHeight("28px");
Button btn = buildButton(displayStrings.logout(),buttonsSystem,new SelectionListener<ButtonEvent>()
{
@Override
public void componentSelected(ButtonEvent ce)
{
doLogout();
}
});
toolBar.add(new FillToolItem());
toolBar.add(btn);
}
//////////////////////////////////////////
private void displayButtons(boolean show,ArrayList<Button> buttons)
{
for(Button btn : buttons)
{
btn.setVisible(show);
}
}
public void displaySystemButtons(boolean show)
{
displayButtons(show,buttonsSystem);
}
public void assembleLayout()
{
drawNorth();
drawSouth();
assembleToolbar();
assembleHeader();
assembleFooter();
}
public void replaceCenterPanel(Component view)
{
if(center != null)
{
remove(center);
}
center = view;
BorderLayoutData data = new BorderLayoutData(LayoutRegion.CENTER);
data.setMargins(new Margins(0));
if(center != null)
{
add(center,data);
}
layout();
}
public void replaceWestPanel(Component view)
{
if(west != null)
{
//make sure we are expanded before we try and remove
layout.expand(LayoutRegion.WEST);
remove(west);
}
west = view;
if(west == null)
{
layout.hide(LayoutRegion.WEST);
}
else
{
BorderLayoutData data = new BorderLayoutData(LayoutRegion.WEST,200);
data.setSplit(true);
- data.setCollapsible(true);
+ // true, this is false by default - but it might change in the future
+ data.setCollapsible(false);
data.setMargins(new Margins(0,5,0,0));
add(west,data);
}
layout();
}
public void initEventHandlers()
{
if(statusBar != null)
{
statusBar.initEventHandlers();
}
}
}
| true | true | public void replaceWestPanel(Component view)
{
if(west != null)
{
//make sure we are expanded before we try and remove
layout.expand(LayoutRegion.WEST);
remove(west);
}
west = view;
if(west == null)
{
layout.hide(LayoutRegion.WEST);
}
else
{
BorderLayoutData data = new BorderLayoutData(LayoutRegion.WEST,200);
data.setSplit(true);
data.setCollapsible(true);
data.setMargins(new Margins(0,5,0,0));
add(west,data);
}
layout();
}
| public void replaceWestPanel(Component view)
{
if(west != null)
{
//make sure we are expanded before we try and remove
layout.expand(LayoutRegion.WEST);
remove(west);
}
west = view;
if(west == null)
{
layout.hide(LayoutRegion.WEST);
}
else
{
BorderLayoutData data = new BorderLayoutData(LayoutRegion.WEST,200);
data.setSplit(true);
// true, this is false by default - but it might change in the future
data.setCollapsible(false);
data.setMargins(new Margins(0,5,0,0));
add(west,data);
}
layout();
}
|
diff --git a/tregmine/src/info/tregmine/portals/Portals.java b/tregmine/src/info/tregmine/portals/Portals.java
index ceccac5..3c71b8a 100644
--- a/tregmine/src/info/tregmine/portals/Portals.java
+++ b/tregmine/src/info/tregmine/portals/Portals.java
@@ -1,53 +1,55 @@
package info.tregmine.portals;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.Inventory;
public class Portals implements Listener {
private final Tregmine plugin;
public Portals(Tregmine instance) {
plugin = instance;
plugin.getServer();
}
private void portalButton(int button, Block block, TregminePlayer player, String world, Location loc) {
// Location loc = new Location(player.getServer().getWorld(world), x,y,z, yaw, pitch);
Inventory inventory = player.getInventory();
if(button == info.tregmine.api.math.Checksum.block(block)){
- if (inventory.getSize() > 0) {
- player.sendMessage(ChatColor.RED + "You carry to much for the portal magic to work");
- return;
+ for (int i = 0; i < inventory.getSize(); i++) {
+ if (inventory.getItem(i) != null) {
+ player.sendMessage(ChatColor.RED + "You carry to much for the portal magic to work");
+ return;
+ }
}
player.teleport(loc);
player.sendMessage(ChatColor.YELLOW + "Thanks for using TregPort's services");
}
}
@EventHandler
public void buttons(PlayerInteractEvent event) {
if(event.getAction() == Action.LEFT_CLICK_AIR || event.getAction() == Action.RIGHT_CLICK_AIR) return;
Block block = event.getClickedBlock();
TregminePlayer player = plugin.getPlayer(event.getPlayer());
portalButton(-1488547832, block, player, "world", player.getServer().getWorld("world").getSpawnLocation());
}
//-1488547832
}
| true | true | private void portalButton(int button, Block block, TregminePlayer player, String world, Location loc) {
// Location loc = new Location(player.getServer().getWorld(world), x,y,z, yaw, pitch);
Inventory inventory = player.getInventory();
if(button == info.tregmine.api.math.Checksum.block(block)){
if (inventory.getSize() > 0) {
player.sendMessage(ChatColor.RED + "You carry to much for the portal magic to work");
return;
}
player.teleport(loc);
player.sendMessage(ChatColor.YELLOW + "Thanks for using TregPort's services");
}
}
| private void portalButton(int button, Block block, TregminePlayer player, String world, Location loc) {
// Location loc = new Location(player.getServer().getWorld(world), x,y,z, yaw, pitch);
Inventory inventory = player.getInventory();
if(button == info.tregmine.api.math.Checksum.block(block)){
for (int i = 0; i < inventory.getSize(); i++) {
if (inventory.getItem(i) != null) {
player.sendMessage(ChatColor.RED + "You carry to much for the portal magic to work");
return;
}
}
player.teleport(loc);
player.sendMessage(ChatColor.YELLOW + "Thanks for using TregPort's services");
}
}
|
diff --git a/src/main/java/org/osmsurround/ra/search/QuickSearchController.java b/src/main/java/org/osmsurround/ra/search/QuickSearchController.java
index ec054c4..f754af0 100644
--- a/src/main/java/org/osmsurround/ra/search/QuickSearchController.java
+++ b/src/main/java/org/osmsurround/ra/search/QuickSearchController.java
@@ -1,26 +1,30 @@
package org.osmsurround.ra.search;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
@Controller
@RequestMapping("/quickSearch")
public class QuickSearchController {
@RequestMapping(method = RequestMethod.GET)
public ModelAndView get(String query) {
+ ModelAndView mav = new ModelAndView();
RedirectView view = null;
try {
- long relationId = Long.parseLong(query);
- view = new RedirectView("analyzeRelation?relationId=" + relationId, true);
+ Long.parseLong(query);
+ view = new RedirectView("analyzeRelation", true);
+ mav.addObject("relationId", query);
}
catch (NumberFormatException e) {
- view = new RedirectView("searchRelation?name=" + query, true);
+ view = new RedirectView("searchRelation", true);
+ mav.addObject("name", query);
}
view.setEncodingScheme("utf8");
- return new ModelAndView(view);
+ mav.setView(view);
+ return mav;
}
}
| false | true | public ModelAndView get(String query) {
RedirectView view = null;
try {
long relationId = Long.parseLong(query);
view = new RedirectView("analyzeRelation?relationId=" + relationId, true);
}
catch (NumberFormatException e) {
view = new RedirectView("searchRelation?name=" + query, true);
}
view.setEncodingScheme("utf8");
return new ModelAndView(view);
}
| public ModelAndView get(String query) {
ModelAndView mav = new ModelAndView();
RedirectView view = null;
try {
Long.parseLong(query);
view = new RedirectView("analyzeRelation", true);
mav.addObject("relationId", query);
}
catch (NumberFormatException e) {
view = new RedirectView("searchRelation", true);
mav.addObject("name", query);
}
view.setEncodingScheme("utf8");
mav.setView(view);
return mav;
}
|
diff --git a/src/Client.java b/src/Client.java
index d5fb5a0..933876f 100644
--- a/src/Client.java
+++ b/src/Client.java
@@ -1,466 +1,463 @@
import java.net.Socket;
import java.util.Random;
import java.lang.Math;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.Input;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.opengl.shader.ShaderProgram;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
//Player class to hold image, position, drunk_level;
class Player {
private static final float TERMINAL_VELOCITY = 5000.0f;
float x,y;
float speed_x;
float speed_y;
float acc_y; //acceleration along y
int direction; //1: right, -1: left
boolean is_jumping;
Rectangle hitbox, r_pushbox, l_pushbox;
Image sprite;
public Player() throws SlickException{
//Starting position
x = 355.0f;
y = 35.0f;
speed_x = 0;
speed_y = 0;
acc_y = 0;
direction = 0;
is_jumping = false;
sprite = new Image("img/ball.png");
hitbox = new Rectangle(x,y,sprite.getWidth(),sprite.getHeight());
l_pushbox = new Rectangle(x-hitbox.getWidth()*0.5f, y+hitbox.getHeight()*0.25f, hitbox.getWidth()*0.5f, hitbox.getHeight()*0.5f);
r_pushbox = new Rectangle(x+hitbox.getWidth(), y+hitbox.getHeight()*0.25f, hitbox.getWidth()*0.5f, hitbox.getHeight()*0.5f);
}
public float getX(){
return x;
}
public float getY(){
return y;
}
public void setX(float newx){
x = newx;
hitbox.setX(newx);
l_pushbox.setX(x-hitbox.getWidth()*0.5f);
r_pushbox.setX(x+hitbox.getWidth());
}
public void setY(float newy){
//limit maximum y
if(newy>600) newy = 600;
y = newy;
hitbox.setY(newy);
r_pushbox.setY(y+hitbox.getHeight()*0.25f);
l_pushbox.setY(y+hitbox.getHeight()*0.25f);
}
public Image getImage(){
return sprite;
}
public Rectangle getHitbox(){
return hitbox;
}
public Rectangle getRightPushBox(){
return r_pushbox;
}
public Rectangle getLeftPushBox(){
return l_pushbox;
}
public float getSpeedX(){
return speed_x;
}
public float getSpeedY(){
return speed_y;
}
public void setSpeedX(float newspeed_x){
speed_x = newspeed_x;
}
public void setSpeedY(float newspeed_y){
//set maximum downward movement
if(newspeed_y > TERMINAL_VELOCITY) newspeed_y = TERMINAL_VELOCITY;
speed_y = newspeed_y;
}
public boolean isJumping(){
return is_jumping;
}
public void setJumping(boolean newjumping){
is_jumping = newjumping;
}
public float getAccelerationY(){
return acc_y;
}
public void setAccelerationY(float newAccY){
acc_y = newAccY;
}
public void setDirection(int NEW_DIRECTIONS){
direction = NEW_DIRECTIONS;
}
public int getDirection(){
return direction;
}
}
class PlayerThread extends Thread {
Socket socket;
MyConnection conn;
String msg;
int active, id, drunk_level; // active = number of connected players
Player[] players; //reference to the players in the Client class
public PlayerThread(Socket socket, Player[] players) {
this.socket = socket;
this.conn = new MyConnection(socket);
this.msg = "connected!";
this.active = 0;
this.drunk_level = 0;
this.players = players;
}
//TODO manage protocols here
public void run() {
while (true) {
msg = conn.getMessage();
System.out.println("Message: " + msg);
if (msg.substring(0, 7).equals("Active ")) {
active = Integer.parseInt(msg.substring(7));
}
else if (msg.substring(0, 7).equals("Number:")) {
id = Integer.parseInt(msg.substring(8));
}
//PROTOCOL: MOVE <PLAYERID> <X> <Y>
//example: MOVE 2 356 45
else if(msg.substring(0,4).equals("MOVE")){
System.out.println("Moveing " + msg.charAt(5));
int player_id = msg.charAt(5) - 48;
float x,y;
String temp_x = "", temp_msg = msg.substring(7);
//PARSE THE <X> AND <Y>
temp_x = temp_msg.substring(0, temp_msg.indexOf(' '));
x = Float.parseFloat(temp_x);
y = Float.parseFloat(temp_msg.substring(temp_msg.indexOf(' ')));
players[player_id].setX(x);
players[player_id].setY(y);
}
//PROTOCOL: PUSH <PLAYERID> <PLAYER_DIRECTION>
//example: PUSH 1 -1
else if(msg.substring(0,4).equals("PUSH")){
System.out.println("PUSHING " + msg.charAt(5));
String temp_msg = msg.substring(7);
int pusher_id = msg.charAt(5) - 48;
int direction = Integer.parseInt(temp_msg.substring(0, temp_msg.indexOf(' ')));
int i = id;
if(pusher_id != i){
System.out.println("pusher_id: " + pusher_id + " direction: " + direction);
if((direction == -1 && players[i].getHitbox().intersects(players[pusher_id].getLeftPushBox())) || (direction == 1 && players[i].getHitbox().intersects(players[pusher_id].getRightPushBox()))){
float new_speed = direction * 1000f;
System.out.println("new_speed: " + new_speed + " i: " + i);
players[i].setSpeedX(new_speed);
}
}
}
//PROTOCOL: ALCOHOL
else if (msg.equals("ALCOHOL")) {
drunk_level += 1;
}
}
}
}
public class Client extends BasicGameState {
private static final float g = 300f; //GRAVITY
private static final int NUM_OF_PLATFORMS = 9;
Socket socket;
PlayerThread thread;
Player[] players = new Player[4];
Rectangle[] platforms = new Rectangle[NUM_OF_PLATFORMS];
int id, active, t;
Random random;
float randX, randY, sway, swayY;
ShaderProgram hShader, vShader;
Image hImage, vImage, bg;
Graphics hGraphics, vGraphics;
public Client(int state) {
try {
socket = new Socket("127.0.0.1", 8888);
} catch (Exception e) {}
}
@Override
public void init(GameContainer gc, StateBasedGame sbg)
throws SlickException {
bg = new Image("img/bg.jpg");
for (int i = 0; i < 4; i++) players[i] = new Player();
platforms[0] = new Rectangle(300,100,200,10);
platforms[1] = new Rectangle(100,180,200,10);
platforms[2] = new Rectangle(500,180,200,10);
platforms[3] = new Rectangle(300,260,200,10);
platforms[4] = new Rectangle(100,340,200,10);
platforms[5] = new Rectangle(500,340,200,10);
platforms[6] = new Rectangle(300,420,200,10);
platforms[7] = new Rectangle(100,500,200,10);
platforms[8] = new Rectangle(500,500,200,10);
thread = new PlayerThread(socket, players);
thread.start();
active = 1;
t = 0;
random = new Random();
randX = 0.0f;
randY = 0.0f;
hImage = Image.createOffscreenImage(800, 600);
hGraphics = hImage.getGraphics();
vImage = Image.createOffscreenImage(800, 600);
vGraphics = vImage.getGraphics();
// Shaders as well as their application are from
// the Slick2d tutorials
String h = "shaders/hvs.frag";
String v = "shaders/vvs.frag";
String vert = "shaders/hvs.vert";
hShader = ShaderProgram.loadProgram(vert, h);
vShader = ShaderProgram.loadProgram(vert, v);
hShader.bind();
hShader.setUniform1i("tex0", 0); //texture 0
hShader.setUniform1f("resolution", 800); //width of img
hShader.setUniform1f("radius", 0f);
vShader.bind();
vShader.setUniform1i("tex0", 0); //texture 0
vShader.setUniform1f("resolution", 600); //height of img
vShader.setUniform1f("radius", 0f);
ShaderProgram.unbindAll();
}
// While not drunk, do only this; otherwise do this and apply shader
public void prerender(GameContainer gc, StateBasedGame sbg, Graphics g)
throws SlickException {
g.drawImage(bg, 0, 0);
for (int i = 0; i < active; i++){
g.drawImage(players[i].getImage(), players[i].getX(), players[i].getY());
g.draw(players[i].getHitbox());
g.draw(players[i].getRightPushBox());
g.draw(players[i].getLeftPushBox());
}
for (int i = 0; i < NUM_OF_PLATFORMS; i++){
g.fill(platforms[i]);
g.draw(platforms[i]);
}
}
@Override
public void render(GameContainer gc, StateBasedGame sbg, Graphics g)
throws SlickException {
g.translate(sway, swayY);
if (thread.drunk_level > 0) {
Graphics.setCurrent(hGraphics);
hGraphics.clear();
hGraphics.flush();
prerender(gc, sbg, hGraphics);
hShader.bind();
hShader.setUniform1f("radius", 0.3f * thread.drunk_level);
Graphics.setCurrent(vGraphics);
vGraphics.clear();
vGraphics.drawImage(hImage, 0f, 0f);
vGraphics.flush();
hShader.unbind();
vShader.bind();
vShader.setUniform1f("radius", 0.3f * thread.drunk_level);
Graphics.setCurrent(g);
g.drawImage(vImage, 0f, 0f);
ShaderProgram.unbindAll();
}
else {
prerender(gc, sbg, g);
}
// Draw strings last; draw image first
g.drawString(" " + thread.msg, 20, 20);
g.drawString("ID: " + id, 700, 20);
g.drawString("Drunk level: " + thread.drunk_level, 600, 560);
g.translate(-sway, swayY);
}
@Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
float past_x = players[id].getX();
float past_y = players[id].getY();
//limit delta
if(delta>20) delta = 20;
float seconds = (float)delta/1000;
active = thread.active;
id = thread.id;
if (thread.drunk_level >= 5) {
randX = (thread.drunk_level - 4) * (random.nextInt(2) + 1);
randY = (thread.drunk_level - 4)* (random.nextInt(5) + 1);
}
Input input = gc.getInput();
if (input.isKeyDown(Input.KEY_RIGHT)) {
if(players[id].getSpeedX() + 400f + randX <= 600f){
players[id].setSpeedX(players[id].getSpeedX() + 400f + randX);
}
players[id].setDirection(1);
}
if (input.isKeyDown(Input.KEY_LEFT)) {
if(players[id].getSpeedX() - 400f + randX >= -600f){
players[id].setSpeedX(players[id].getSpeedX() - 400f + randX);
}
players[id].setDirection(-1);
}
if (input.isKeyDown(Input.KEY_UP) && !players[id].isJumping()) {
players[id].setSpeedY(-600f + randY);
players[id].setJumping(true);
}
if (input.isKeyPressed(Input.KEY_SPACE)){
thread.conn.sendMessage("PUSH "+players[id].getDirection());
}
//increment downward acceleration by g if player is on air
if(players[id].isJumping()) players[id].setAccelerationY(players[id].getAccelerationY() + g * seconds);
//set new speed using the acceleration along y
players[id].setSpeedY(players[id].getSpeedY() + players[id].getAccelerationY());
//set new speed along X because of friction
if(players[id].getSpeedX() != 0){
if(players[id].getSpeedX()>0){
players[id].setSpeedX(players[id].getSpeedX() - 100f - randX);
}
else{
players[id].setSpeedX(players[id].getSpeedX() + 100f + randX);
}
}
//set new x and y using the speed along x and y
players[id].setX(players[id].getX() + players[id].getSpeedX() * seconds);
players[id].setY(players[id].getY() + players[id].getSpeedY() * seconds);
//set jumping to true by default then set to false only when landing on ground
players[id].setJumping(true);
// check for player-to-player collisions
for (int i = 0; i < active; i++) {
if (i != id) {
if (players[i].getHitbox().intersects(players[id].getHitbox())) {
boolean flag = true;
if (past_x > (players[i].getX() + players[i].getHitbox().getWidth()) - 1) {
players[id].setX(players[i].getX() + players[i].getHitbox().getWidth());
flag = false;
}
if (past_x < players[i].getX()) {
players[id].setX(players[i].getX() - players[id].getHitbox().getWidth());
flag = false;
}
if (past_y < players[i].getY() && flag) {
players[id].setY(players[i].getY() - players[id].getHitbox().getHeight() - 1);
//set jumping to false, speed to 0, acceleration along y to 0 when touching a player below
players[id].setJumping(false);
players[id].setSpeedY(0);
players[id].setAccelerationY(0);
}
if (past_y > (players[i].getY() + players[i].getHitbox().getHeight())) {
players[id].setY(players[i].getY() + players[i].getHitbox().getHeight() + 1);
players[id].setSpeedY(0);
}
}
}
}
//check for player-to-platform collisions
for(int i=0; i<NUM_OF_PLATFORMS; i++){
if(platforms[i].intersects(players[id].getHitbox())){
- boolean flag = true;
- if (past_x>(platforms[i].getX()+platforms[i].getWidth()) - 1) {
- players[id].setX(platforms[i].getX() + platforms[i].getWidth());
- flag = false;
+ if (past_x>(platforms[i].getX()+platforms[i].getWidth() - 1) && (past_y + players[id].getHitbox().getHeight())>platforms[i].getY()) {
+ players[id].setX(platforms[i].getX() + platforms[i].getWidth() + 1);
}
- if (past_x<platforms[i].getX()) {
- players[id].setX(platforms[i].getX() - players[id].getHitbox().getWidth());
- flag = false;
- }
- if (past_y<platforms[i].getY() && flag) {
+ else if (past_y<platforms[i].getY() && (past_x + players[id].getHitbox().getWidth()) > platforms[i].getX()) {
players[id].setY(platforms[i].getY() - players[id].getHitbox().getHeight());
//set jumping to false, speed to 0, acceleration along y to 0 when touching the ground
players[id].setJumping(false);
players[id].setSpeedY(0);
players[id].setAccelerationY(0);
}
- if (past_y>(platforms[i].getY()+platforms[i].getHeight())) {
+ if (past_y>(platforms[i].getY()+platforms[i].getHeight() - 1) && (past_x + players[id].getHitbox().getWidth()) > platforms[i].getX()) {
players[id].setY(platforms[i].getY() + platforms[i].getHeight() + 1);
players[id].setSpeedY(0);
}
+ else if (past_x<platforms[i].getX() && (past_y + players[id].getHitbox().getHeight()) > platforms[i].getY()) {
+ players[id].setX(platforms[i].getX() - players[id].getHitbox().getWidth());
+ }
}
}
//sway
t++;
sway = 5 * thread.drunk_level * (float)Math.cos(0.1f * t);
swayY = 3 * thread.drunk_level * (float)Math.cos(0.1f * t - 2.1f);
//check for changes in coordinates then broadcast the MOVE message
if(past_x!=players[id].getX() || past_y!=players[id].getY()){
thread.conn.sendMessage("MOVE "+players[id].getX()+" "+players[id].getY());
}
}
@Override
public int getID() {
return 2;
}
}
| false | true | public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
float past_x = players[id].getX();
float past_y = players[id].getY();
//limit delta
if(delta>20) delta = 20;
float seconds = (float)delta/1000;
active = thread.active;
id = thread.id;
if (thread.drunk_level >= 5) {
randX = (thread.drunk_level - 4) * (random.nextInt(2) + 1);
randY = (thread.drunk_level - 4)* (random.nextInt(5) + 1);
}
Input input = gc.getInput();
if (input.isKeyDown(Input.KEY_RIGHT)) {
if(players[id].getSpeedX() + 400f + randX <= 600f){
players[id].setSpeedX(players[id].getSpeedX() + 400f + randX);
}
players[id].setDirection(1);
}
if (input.isKeyDown(Input.KEY_LEFT)) {
if(players[id].getSpeedX() - 400f + randX >= -600f){
players[id].setSpeedX(players[id].getSpeedX() - 400f + randX);
}
players[id].setDirection(-1);
}
if (input.isKeyDown(Input.KEY_UP) && !players[id].isJumping()) {
players[id].setSpeedY(-600f + randY);
players[id].setJumping(true);
}
if (input.isKeyPressed(Input.KEY_SPACE)){
thread.conn.sendMessage("PUSH "+players[id].getDirection());
}
//increment downward acceleration by g if player is on air
if(players[id].isJumping()) players[id].setAccelerationY(players[id].getAccelerationY() + g * seconds);
//set new speed using the acceleration along y
players[id].setSpeedY(players[id].getSpeedY() + players[id].getAccelerationY());
//set new speed along X because of friction
if(players[id].getSpeedX() != 0){
if(players[id].getSpeedX()>0){
players[id].setSpeedX(players[id].getSpeedX() - 100f - randX);
}
else{
players[id].setSpeedX(players[id].getSpeedX() + 100f + randX);
}
}
//set new x and y using the speed along x and y
players[id].setX(players[id].getX() + players[id].getSpeedX() * seconds);
players[id].setY(players[id].getY() + players[id].getSpeedY() * seconds);
//set jumping to true by default then set to false only when landing on ground
players[id].setJumping(true);
// check for player-to-player collisions
for (int i = 0; i < active; i++) {
if (i != id) {
if (players[i].getHitbox().intersects(players[id].getHitbox())) {
boolean flag = true;
if (past_x > (players[i].getX() + players[i].getHitbox().getWidth()) - 1) {
players[id].setX(players[i].getX() + players[i].getHitbox().getWidth());
flag = false;
}
if (past_x < players[i].getX()) {
players[id].setX(players[i].getX() - players[id].getHitbox().getWidth());
flag = false;
}
if (past_y < players[i].getY() && flag) {
players[id].setY(players[i].getY() - players[id].getHitbox().getHeight() - 1);
//set jumping to false, speed to 0, acceleration along y to 0 when touching a player below
players[id].setJumping(false);
players[id].setSpeedY(0);
players[id].setAccelerationY(0);
}
if (past_y > (players[i].getY() + players[i].getHitbox().getHeight())) {
players[id].setY(players[i].getY() + players[i].getHitbox().getHeight() + 1);
players[id].setSpeedY(0);
}
}
}
}
//check for player-to-platform collisions
for(int i=0; i<NUM_OF_PLATFORMS; i++){
if(platforms[i].intersects(players[id].getHitbox())){
boolean flag = true;
if (past_x>(platforms[i].getX()+platforms[i].getWidth()) - 1) {
players[id].setX(platforms[i].getX() + platforms[i].getWidth());
flag = false;
}
if (past_x<platforms[i].getX()) {
players[id].setX(platforms[i].getX() - players[id].getHitbox().getWidth());
flag = false;
}
if (past_y<platforms[i].getY() && flag) {
players[id].setY(platforms[i].getY() - players[id].getHitbox().getHeight());
//set jumping to false, speed to 0, acceleration along y to 0 when touching the ground
players[id].setJumping(false);
players[id].setSpeedY(0);
players[id].setAccelerationY(0);
}
if (past_y>(platforms[i].getY()+platforms[i].getHeight())) {
players[id].setY(platforms[i].getY() + platforms[i].getHeight() + 1);
players[id].setSpeedY(0);
}
}
}
//sway
t++;
sway = 5 * thread.drunk_level * (float)Math.cos(0.1f * t);
swayY = 3 * thread.drunk_level * (float)Math.cos(0.1f * t - 2.1f);
//check for changes in coordinates then broadcast the MOVE message
if(past_x!=players[id].getX() || past_y!=players[id].getY()){
thread.conn.sendMessage("MOVE "+players[id].getX()+" "+players[id].getY());
}
}
| public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
float past_x = players[id].getX();
float past_y = players[id].getY();
//limit delta
if(delta>20) delta = 20;
float seconds = (float)delta/1000;
active = thread.active;
id = thread.id;
if (thread.drunk_level >= 5) {
randX = (thread.drunk_level - 4) * (random.nextInt(2) + 1);
randY = (thread.drunk_level - 4)* (random.nextInt(5) + 1);
}
Input input = gc.getInput();
if (input.isKeyDown(Input.KEY_RIGHT)) {
if(players[id].getSpeedX() + 400f + randX <= 600f){
players[id].setSpeedX(players[id].getSpeedX() + 400f + randX);
}
players[id].setDirection(1);
}
if (input.isKeyDown(Input.KEY_LEFT)) {
if(players[id].getSpeedX() - 400f + randX >= -600f){
players[id].setSpeedX(players[id].getSpeedX() - 400f + randX);
}
players[id].setDirection(-1);
}
if (input.isKeyDown(Input.KEY_UP) && !players[id].isJumping()) {
players[id].setSpeedY(-600f + randY);
players[id].setJumping(true);
}
if (input.isKeyPressed(Input.KEY_SPACE)){
thread.conn.sendMessage("PUSH "+players[id].getDirection());
}
//increment downward acceleration by g if player is on air
if(players[id].isJumping()) players[id].setAccelerationY(players[id].getAccelerationY() + g * seconds);
//set new speed using the acceleration along y
players[id].setSpeedY(players[id].getSpeedY() + players[id].getAccelerationY());
//set new speed along X because of friction
if(players[id].getSpeedX() != 0){
if(players[id].getSpeedX()>0){
players[id].setSpeedX(players[id].getSpeedX() - 100f - randX);
}
else{
players[id].setSpeedX(players[id].getSpeedX() + 100f + randX);
}
}
//set new x and y using the speed along x and y
players[id].setX(players[id].getX() + players[id].getSpeedX() * seconds);
players[id].setY(players[id].getY() + players[id].getSpeedY() * seconds);
//set jumping to true by default then set to false only when landing on ground
players[id].setJumping(true);
// check for player-to-player collisions
for (int i = 0; i < active; i++) {
if (i != id) {
if (players[i].getHitbox().intersects(players[id].getHitbox())) {
boolean flag = true;
if (past_x > (players[i].getX() + players[i].getHitbox().getWidth()) - 1) {
players[id].setX(players[i].getX() + players[i].getHitbox().getWidth());
flag = false;
}
if (past_x < players[i].getX()) {
players[id].setX(players[i].getX() - players[id].getHitbox().getWidth());
flag = false;
}
if (past_y < players[i].getY() && flag) {
players[id].setY(players[i].getY() - players[id].getHitbox().getHeight() - 1);
//set jumping to false, speed to 0, acceleration along y to 0 when touching a player below
players[id].setJumping(false);
players[id].setSpeedY(0);
players[id].setAccelerationY(0);
}
if (past_y > (players[i].getY() + players[i].getHitbox().getHeight())) {
players[id].setY(players[i].getY() + players[i].getHitbox().getHeight() + 1);
players[id].setSpeedY(0);
}
}
}
}
//check for player-to-platform collisions
for(int i=0; i<NUM_OF_PLATFORMS; i++){
if(platforms[i].intersects(players[id].getHitbox())){
if (past_x>(platforms[i].getX()+platforms[i].getWidth() - 1) && (past_y + players[id].getHitbox().getHeight())>platforms[i].getY()) {
players[id].setX(platforms[i].getX() + platforms[i].getWidth() + 1);
}
else if (past_y<platforms[i].getY() && (past_x + players[id].getHitbox().getWidth()) > platforms[i].getX()) {
players[id].setY(platforms[i].getY() - players[id].getHitbox().getHeight());
//set jumping to false, speed to 0, acceleration along y to 0 when touching the ground
players[id].setJumping(false);
players[id].setSpeedY(0);
players[id].setAccelerationY(0);
}
if (past_y>(platforms[i].getY()+platforms[i].getHeight() - 1) && (past_x + players[id].getHitbox().getWidth()) > platforms[i].getX()) {
players[id].setY(platforms[i].getY() + platforms[i].getHeight() + 1);
players[id].setSpeedY(0);
}
else if (past_x<platforms[i].getX() && (past_y + players[id].getHitbox().getHeight()) > platforms[i].getY()) {
players[id].setX(platforms[i].getX() - players[id].getHitbox().getWidth());
}
}
}
//sway
t++;
sway = 5 * thread.drunk_level * (float)Math.cos(0.1f * t);
swayY = 3 * thread.drunk_level * (float)Math.cos(0.1f * t - 2.1f);
//check for changes in coordinates then broadcast the MOVE message
if(past_x!=players[id].getX() || past_y!=players[id].getY()){
thread.conn.sendMessage("MOVE "+players[id].getX()+" "+players[id].getY());
}
}
|
diff --git a/src/instructions/USI_MOVD.java b/src/instructions/USI_MOVD.java
index 6293f06..f4e2821 100644
--- a/src/instructions/USI_MOVD.java
+++ b/src/instructions/USI_MOVD.java
@@ -1,103 +1,103 @@
package instructions;
import static simulanator.Deformatter.breakDownOther;
import simulanator.Deformatter.Location;
import simulanator.Machine;
import simulanator.Deformatter.OpcodeBreakdownOther;
import assemblernator.Instruction;
import assemblernator.Module;
/**
* The MOVD instruction.
*
* @author Generate.java
* @date Apr 08, 2012; 08:26:19
* @specRef MV0
*/
public class USI_MOVD extends UIG_Arithmetic {
/**
* The operation identifier of this instruction; while comments should not
* be treated as an instruction, specification says they must be included in
* the user report. Hence, we will simply give this class a semicolon as its
* instruction ID.
*/
private static final String opId = "MOVD";
/** This instruction's identifying opcode. */
private static final int opCode = 0x00000000; // 0b00000000000000000000000000000000
/** The static instance for this instruction. */
static USI_MOVD staticInstance = new USI_MOVD(true);
/** @see assemblernator.Instruction#getNewLC(int, Module) */
@Override public int getNewLC(int lc, Module mod) {
return lc+1;
}
/** @see assemblernator.Instruction#execute(int, Machine) */
@Override public void execute(int instruction, Machine machine) {
OpcodeBreakdownOther brkDwn = breakDownOther(instruction);
int dest = brkDwn.destination;
Location kind = brkDwn.destKind;
//dest is a index register
if(kind == Location.INDEXREGISTER){
int srcValue = brkDwn.readFromSource(machine);
- machine.indexRegisters[dest] = srcValue;
+ brkDwn.putToDest(srcValue, machine);
//dest is a memory
}else if(kind == Location.MEMORY){
int srcValue = brkDwn.readFromSource(machine);
- machine.memory[dest] = srcValue;
+ brkDwn.putToDest(srcValue, machine);
//dest is a register
}else if(kind == Location.REGISTER){
int srcValue = brkDwn.readFromSource(machine);
- machine.registers[dest] = srcValue;
+ brkDwn.putToDest(srcValue, machine);
}
}
// =========================================================
// === Redundant code ======================================
// =========================================================
// === This code's the same in all instruction classes, ====
// === But Java lacks the mechanism to allow stuffing it ===
// === in super() where it belongs. ========================
// =========================================================
/**
* @see Instruction
* @return The static instance of this instruction.
*/
public static Instruction getInstance() {
return staticInstance;
}
/** @see assemblernator.Instruction#getOpId() */
@Override public String getOpId() {
return opId;
}
/** @see assemblernator.Instruction#getOpcode() */
@Override public int getOpcode() {
return opCode;
}
/** @see assemblernator.Instruction#getNewInstance() */
@Override public Instruction getNewInstance() {
return new USI_MOVD();
}
/**
* Calls the Instance(String,int) constructor to track this instruction.
*
* @param ignored
* Unused parameter; used to distinguish the constructor for the
* static instance.
*/
private USI_MOVD(boolean ignored) {
super(opId, opCode);
}
/** Default constructor; does nothing. */
private USI_MOVD() {}
}
| false | true | @Override public void execute(int instruction, Machine machine) {
OpcodeBreakdownOther brkDwn = breakDownOther(instruction);
int dest = brkDwn.destination;
Location kind = brkDwn.destKind;
//dest is a index register
if(kind == Location.INDEXREGISTER){
int srcValue = brkDwn.readFromSource(machine);
machine.indexRegisters[dest] = srcValue;
//dest is a memory
}else if(kind == Location.MEMORY){
int srcValue = brkDwn.readFromSource(machine);
machine.memory[dest] = srcValue;
//dest is a register
}else if(kind == Location.REGISTER){
int srcValue = brkDwn.readFromSource(machine);
machine.registers[dest] = srcValue;
}
}
| @Override public void execute(int instruction, Machine machine) {
OpcodeBreakdownOther brkDwn = breakDownOther(instruction);
int dest = brkDwn.destination;
Location kind = brkDwn.destKind;
//dest is a index register
if(kind == Location.INDEXREGISTER){
int srcValue = brkDwn.readFromSource(machine);
brkDwn.putToDest(srcValue, machine);
//dest is a memory
}else if(kind == Location.MEMORY){
int srcValue = brkDwn.readFromSource(machine);
brkDwn.putToDest(srcValue, machine);
//dest is a register
}else if(kind == Location.REGISTER){
int srcValue = brkDwn.readFromSource(machine);
brkDwn.putToDest(srcValue, machine);
}
}
|
diff --git a/ini/trakem2/display/Display.java b/ini/trakem2/display/Display.java
index b347e69a..ee8c8c6a 100644
--- a/ini/trakem2/display/Display.java
+++ b/ini/trakem2/display/Display.java
@@ -1,3517 +1,3525 @@
/**
TrakEM2 plugin for ImageJ(C).
Copyright (C) 2005, 2006 Albert Cardona and Rodney Douglas.
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 (http://www.gnu.org/licenses/gpl.txt )
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.
You may contact Albert Cardona at acardona at ini.phys.ethz.ch
Institute of Neuroinformatics, University of Zurich / ETH, Switzerland.
**/
package ini.trakem2.display;
import ij.*;
import ij.io.*;
import ij.gui.*;
import ij.process.*;
import ij.measure.Calibration;
import ini.trakem2.Project;
import ini.trakem2.ControlWindow;
import ini.trakem2.persistence.DBObject;
import ini.trakem2.persistence.Loader;
import ini.trakem2.utils.IJError;
import ini.trakem2.imaging.PatchStack;
import ini.trakem2.imaging.LayerStack;
import ini.trakem2.imaging.Registration;
import ini.trakem2.imaging.StitchingTEM;
import ini.trakem2.utils.ProjectToolbar;
import ini.trakem2.utils.Utils;
import ini.trakem2.utils.DNDInsertImage;
import ini.trakem2.utils.Search;
import ini.trakem2.utils.Bureaucrat;
import ini.trakem2.utils.Worker;
import ini.trakem2.utils.Dispatcher;
import ini.trakem2.utils.Lock;
import ini.trakem2.tree.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.lang.reflect.Method;
import java.io.File;
import java.io.Writer;
/** A Display is a class to show a Layer and enable mouse and keyboard manipulation of all its components. */
public class Display extends DBObject implements ActionListener, ImageListener {
/** The Layer this Display is showing. */
private Layer layer;
private Displayable active = null;
/** All selected Displayable objects, including the active one. */
final private Selection selection = new Selection(this);
private ImagePlus last_temp = null;
private JFrame frame;
private JTabbedPane tabs;
private Hashtable<Class,JScrollPane> ht_tabs;
private JScrollPane scroll_patches;
private JPanel panel_patches;
private JScrollPane scroll_profiles;
private JPanel panel_profiles;
private JScrollPane scroll_zdispl;
private JPanel panel_zdispl;
private JScrollPane scroll_channels;
private JPanel panel_channels;
private JScrollPane scroll_labels;
private JPanel panel_labels;
private JSlider transp_slider;
private DisplayNavigator navigator;
private JScrollBar scroller;
private DisplayCanvas canvas; // WARNING this is an AWT component, since it extends ImageCanvas
private JPanel canvas_panel; // and this is a workaround, to better (perhaps) integrate the awt canvas inside a JSplitPane
private JSplitPane split;
private JPopupMenu popup = null;
/** Contains the packed alphas of every channel. */
private int c_alphas = 0xffffffff; // all 100 % visible
private Channel[] channels;
private Hashtable<Displayable,DisplayablePanel> ht_panels = new Hashtable<Displayable,DisplayablePanel>();
/** Handle drop events, to insert image files. */
private DNDInsertImage dnd;
private boolean size_adjusted = false;
private int scroll_step = 1;
/** Keep track of all existing Display objects. */
static private ArrayList<Display> al_displays = new ArrayList<Display>();
/** The currently focused Display, if any. */
static private Display front = null;
/** Displays to open when all objects have been reloaded from the database. */
static private Hashtable ht_later = null;
/** A thread to handle user actions, for example an event sent from a popup menu. */
private final Dispatcher dispatcher = new Dispatcher();
static private WindowAdapter window_listener = new WindowAdapter() {
/** Unregister the closed Display. */
public void windowClosing(WindowEvent we) {
final Object source = we.getSource();
for (Iterator it = al_displays.iterator(); it.hasNext(); ) {
Display d = (Display)it.next();
if (source == d.frame) {
it.remove();
if (d == front) front = null;
d.remove(false); //calls destroy
break;
}
}
}
/** Set the source Display as front. */
public void windowActivated(WindowEvent we) {
// find which was it to make it be the front
final Object source = we.getSource();
for (Display d : al_displays) {
if (source == d.frame) {
front = d;
// set toolbar
ProjectToolbar.setProjectToolbar();
// now, select the layer in the LayerTree
front.getProject().select(front.layer);
// finally, set the virtual ImagePlus that ImageJ will see
d.setTempCurrentImage();
// copied from ij.gui.ImageWindow, with modifications
if (IJ.isMacintosh() && IJ.getInstance()!=null) {
IJ.wait(10); // may be needed for Java 1.4 on OS X
d.frame.setMenuBar(ij.Menus.getMenuBar());
}
return;
}
}
// else, restore the ImageJ toolbar for non-project images
//if (!source.equals(IJ.getInstance())) {
// ProjectToolbar.setImageJToolbar();
//}
}
/** Restore the ImageJ toolbar */
public void windowDeactivated(WindowEvent we) {
// Can't, the user can never click the ProjectToolbar then. This has to be done in a different way, for example checking who is the WindowManager.getCurrentImage (and maybe setting a dummy image into it) //ProjectToolbar.setImageJToolbar();
}
/** Call a pack() when the window is maximized to fit the canvas correctly. */
public void windowStateChanged(WindowEvent we) {
final Object source = we.getSource();
for (Display d : al_displays) {
d.pack();
break;
}
}
};
static private MouseListener frame_mouse_listener = new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
Object ob = me.getSource();
if (ob instanceof JFrame) {
Display d = null;
for (Iterator it = al_displays.iterator(); it.hasNext(); ) {
d = (Display)it.next();
if (d == ob) break;
}
if (d == null) return;
if (d.size_adjusted) {
d.pack();
d.size_adjusted = false;
}
}
}
};
private int last_frame_state = frame.NORMAL;
static private ComponentListener component_listener = new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
Display d = getDisplaySource(ce);
if (null != d) {
//if (!d.size_adjusted) {
// keep a minimum width and height
Rectangle r = d.frame.getBounds();
int w = r.width;
int h = r.height;
if (h < 600) h = 600;
if (w < 500) w = 500;
if (w != r.width || h != r.height) {
d.frame.setSize(w, h);
//d.size_adjusted = true;
}
//} else {
//d.size_adjusted = false;
//}
d.size_adjusted = true; // works in combination with mouseReleased to call pack(), avoiding infinite loops.
d.adjustCanvas();
int frame_state = d.frame.getExtendedState();
if (frame_state != d.last_frame_state) { // this setup avoids infinite loops (for pack() calls componentResized as well
d.last_frame_state = frame_state;
if (d.frame.ICONIFIED != frame_state) d.pack();
}
}
}
public void componentMoved(ComponentEvent ce) {
Display d = getDisplaySource(ce);
if (null != d) d.updateInDatabase("position");
}
private Display getDisplaySource(ComponentEvent ce) {
final Object source = ce.getSource();
for (Display d : al_displays) {
if (source == d.frame) {
return d;
}
}
return null;
}
};
static private ChangeListener tabs_listener = new ChangeListener() {
/** Listen to tab changes. */
public void stateChanged(final ChangeEvent ce) {
final Object source = ce.getSource();
for (Display dd : al_displays) {
if (source == dd.tabs) {
final Display d = dd;
d.dispatcher.exec(new Runnable() { public void run() {
// creating tabs fires the event!!!
if (null == d.frame || null == d.canvas) return;
final Container tab = (Container)d.tabs.getSelectedComponent();
if (tab == d.scroll_channels) {
// find active channel if any
for (int i=0; i<d.channels.length; i++) {
if (d.channels[i].isActive()) {
d.transp_slider.setValue((int)(d.channels[i].getAlpha() * 100));
break;
}
}
} else {
// recreate contents
/*
int count = tab.getComponentCount();
if (0 == count || (1 == count && tab.getComponent(0).getClass().equals(JLabel.class))) {
*/ // ALWAYS, because it could be the case that the user changes layer while on one specific tab, and then clicks on the other tab which may not be empty and shows totally the wrong contents (i.e. for another layer)
String label = null;
ArrayList al = null;
JPanel p = null;
if (tab == d.scroll_zdispl) {
label = "Z-space objects";
al = d.layer.getParent().getZDisplayables();
p = d.panel_zdispl;
} else if (tab == d.scroll_patches) {
label = "Patches";
al = d.layer.getDisplayables(Patch.class);
p = d.panel_patches;
} else if (tab == d.scroll_labels) {
label = "Labels";
al = d.layer.getDisplayables(DLabel.class);
p = d.panel_labels;
} else if (tab == d.scroll_profiles) {
label = "Profiles";
al = d.layer.getDisplayables(Profile.class);
p = d.panel_profiles;
}
d.updateTab(p, label, al);
//Utils.updateComponent(d.tabs.getSelectedComponent());
//Utils.log2("updated tab: " + p + " with " + al.size() + " objects.");
//}
if (null != d.active) {
// set the transp slider to the alpha value of the active Displayable if any
d.transp_slider.setValue((int)(d.active.getAlpha() * 100));
DisplayablePanel dp = d.ht_panels.get(d.active);
if (null != dp) dp.setActive(true);
}
}
}});
break;
}
}
}
};
private final ScrollLayerListener scroller_listener = new ScrollLayerListener();
private class ScrollLayerListener implements AdjustmentListener {
public void adjustmentValueChanged(AdjustmentEvent ae) {
int index = scroller.getValue();
new SetLayerThread(Display.this, layer.getParent().getLayer(index));
return;
}
}
private Object setting_layer_lock = new Object();
private boolean setting_layer = false;
private SetLayerThread set_layer_thread = null;
private class SetLayerThread extends Thread {
private boolean quit = false;
private Display d;
private Layer layer;
SetLayerThread(Display d, Layer layer) {
setPriority(Thread.NORM_PRIORITY);
if (null != set_layer_thread) set_layer_thread.quit();
set_layer_thread = this;
this.d = d;
this.layer = layer;
start();
}
public void run() {
if (quit) return;
synchronized (setting_layer_lock) {
while (setting_layer) {
try { setting_layer_lock.wait(); } catch (InterruptedException ie) {}
}
if (quit) {
setting_layer = false;
setting_layer_lock.notifyAll();
return;
}
setting_layer = true;
try {
d.setLayer(layer);
updateInDatabase("layer_id"); // not being done at the setLayer method to avoid thread locking design problems (the setLayer is used when reconstructing from the database)
Thread.yield();
} catch (Exception e) {
IJError.print(e);
} finally {
// cleanup (removal of reference necessary for join() calls to this thread to succeed)
if (this == set_layer_thread) {
set_layer_thread = null;
}
}
setting_layer = false;
setting_layer_lock.notifyAll();
}
}
public void quit() {
quit = true;
}
}
/** Creates a new Display with adjusted magnification to fit in the screen. */
static public void createDisplay(final Project project, final Layer layer) {
// Swing is ... horrible?
new Thread() { public void run() { SwingUtilities.invokeLater(new Runnable() { public void run() {
Display display = new Display(project, layer);
ij.gui.GUI.center(display.frame);
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle srcRect = new Rectangle(0, 0, (int)layer.getLayerWidth(), (int)layer.getLayerHeight());
double mag = screen.width / layer.getLayerWidth();
if (mag * layer.getLayerHeight() > screen.height) mag = screen.height / layer.getLayerHeight();
mag = display.canvas.getLowerZoomLevel2(mag);
if (mag > 1.0) mag = 1.0;
display.getCanvas().setup(mag, srcRect);
display.updateTitle();
ij.gui.GUI.center(display.frame);
}});}}.start();
}
/** A new Display from scratch, to show the given Layer. */
public Display(Project project, final Layer layer) {
super(project);
front = this;
makeGUI(layer, null);
ImagePlus.addImageListener(this);
setLayer(layer);
this.layer = layer; // after, or it doesn't update properly
al_displays.add(this);
addToDatabase();
}
/** For reconstruction purposes. The Display will be stored in the ht_later.*/
public Display(Project project, long id, Layer layer, Object[] props) {
super(project, id);
if (null == ht_later) ht_later = new Hashtable();
Display.ht_later.put(this, props);
this.layer = layer;
}
/** Open a new Display centered around the given Displayable. */
public Display(Project project, Layer layer, Displayable displ) {
super(project);
front = this;
active = displ;
makeGUI(layer, null);
ImagePlus.addImageListener(this);
setLayer(layer);
this.layer = layer; // after set layer!
al_displays.add(this);
addToDatabase();
}
/** Reconstruct a Display from an XML entry, to be opened when everything is ready. */
public Display(Project project, long id, Layer layer, HashMap ht_attributes) {
super(project, id);
if (null == layer) {
Utils.log2("Display: need a non-null Layer for id=" + id);
return;
}
Rectangle srcRect = new Rectangle(0, 0, (int)layer.getLayerWidth(), (int)layer.getLayerHeight());
double magnification = 0.25;
Point p = new Point(0, 0);
int c_alphas = 0xffffffff;
int c_alphas_state = 0xffffffff;
for (Iterator it = ht_attributes.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry = (Map.Entry)it.next();
String key = (String)entry.getKey();
String data = (String)entry.getValue();
if (key.equals("srcrect_x")) { // reflection! Reflection!
srcRect.x = Integer.parseInt(data);
} else if (key.equals("srcrect_y")) {
srcRect.y = Integer.parseInt(data);
} else if (key.equals("srcrect_width")) {
srcRect.width = Integer.parseInt(data);
} else if (key.equals("srcrect_height")) {
srcRect.height = Integer.parseInt(data);
} else if (key.equals("magnification")) {
magnification = Double.parseDouble(data);
} else if (key.equals("x")) {
p.x = Integer.parseInt(data);
} else if (key.equals("y")) {
p.y = Integer.parseInt(data);
} else if (key.equals("c_alphas")) {
try {
c_alphas = Integer.parseInt(data);
} catch (Exception ex) {
c_alphas = 0xffffffff;
}
} else if (key.equals("c_alphas_state")) {
try {
c_alphas_state = Integer.parseInt(data);
} catch (Exception ex) {
IJError.print(ex);
c_alphas_state = 0xffffffff;
}
} else if (key.equals("scroll_step")) {
try {
setScrollStep(Integer.parseInt(data));
} catch (Exception ex) {
IJError.print(ex);
setScrollStep(1);
}
}
// TODO the above is insecure, in that data is not fully checked to be within bounds.
}
Object[] props = new Object[]{p, new Double(magnification), srcRect, new Long(layer.getId()), new Integer(c_alphas), new Integer(c_alphas_state)};
if (null == ht_later) ht_later = new Hashtable();
Display.ht_later.put(this, props);
this.layer = layer;
}
/** After reloading a project from the database, open the Displays that the project had. */
static public Bureaucrat openLater() {
if (null == ht_later || 0 == ht_later.size()) return null;
final Worker worker = new Worker("Opening displays") {
public void run() {
startedWorking();
try {
Thread.sleep(300); // waiting for Swing
for (Enumeration e = ht_later.keys(); e.hasMoreElements(); ) {
final Display d = (Display)e.nextElement();
front = d; // must be set before repainting any ZDisplayable!
Object[] props = (Object[])ht_later.get(d);
if (ControlWindow.isGUIEnabled()) d.makeGUI(d.layer, props);
d.setLayerLater(d.layer, d.layer.get(((Long)props[3]).longValue())); //important to do it after makeGUI
if (!ControlWindow.isGUIEnabled()) continue;
ImagePlus.addImageListener(d);
al_displays.add(d);
d.updateTitle();
// force a repaint if a prePaint was done TODO this should be properly managed with repaints using always the invokeLater, but then it's DOG SLOW
if (d.canvas.getMagnification() > 0.499) {
SwingUtilities.invokeLater(new Runnable() { public void run() { d.repaint(d.layer); }});
}
}
ht_later.clear();
ht_later = null;
if (null != front) front.getProject().select(front.layer);
} catch (Throwable t) {
IJError.print(t);
} finally {
finishedWorking();
}
}
};
final Bureaucrat burro = new Bureaucrat(worker, ((Display)ht_later.keySet().iterator().next()).getProject()); // gets the project from the first Display
burro.goHaveBreakfast();
return burro;
}
private void makeGUI(final Layer layer, final Object[] props) {
// gather properties
Point p = null;
double mag = 1.0D;
Rectangle srcRect = null;
if (null != props) {
p = (Point)props[0];
mag = ((Double)props[1]).doubleValue();
srcRect = (Rectangle)props[2];
}
// transparency slider
this.transp_slider = new JSlider(javax.swing.SwingConstants.HORIZONTAL, 0, 100, 100);
this.transp_slider.setBackground(Color.white);
this.transp_slider.setMinimumSize(new Dimension(250, 20));
this.transp_slider.setMaximumSize(new Dimension(250, 20));
this.transp_slider.setPreferredSize(new Dimension(250, 20));
TransparencySliderListener tsl = new TransparencySliderListener();
this.transp_slider.addChangeListener(tsl);
this.transp_slider.addMouseListener(tsl);
KeyListener[] kl = this.transp_slider.getKeyListeners();
for (int i=0; i<kl.length; i++) {
this.transp_slider.removeKeyListener(kl[i]);
}
// Tabbed pane on the left
this.tabs = new JTabbedPane();
this.tabs.setMinimumSize(new Dimension(250, 300));
this.tabs.setBackground(Color.white);
this.tabs.addChangeListener(tabs_listener);
// Tab 1: Patches
this.panel_patches = new JPanel();
BoxLayout patches_layout = new BoxLayout(panel_patches, BoxLayout.Y_AXIS);
this.panel_patches.setLayout(patches_layout);
this.panel_patches.add(new JLabel("No patches."));
this.scroll_patches = makeScrollPane(panel_patches);
this.scroll_patches.setPreferredSize(new Dimension(250, 300));
this.scroll_patches.setMinimumSize(new Dimension(250, 300));
this.tabs.add("Patches", scroll_patches);
// Tab 2: Profiles
this.panel_profiles = new JPanel();
BoxLayout profiles_layout = new BoxLayout(panel_profiles, BoxLayout.Y_AXIS);
this.panel_profiles.setLayout(profiles_layout);
this.panel_profiles.add(new JLabel("No profiles."));
this.scroll_profiles = makeScrollPane(panel_profiles);
this.scroll_profiles.setPreferredSize(new Dimension(250, 300));
this.scroll_profiles.setMinimumSize(new Dimension(250, 300));
this.tabs.add("Profiles", scroll_profiles);
// Tab 3: pipes
this.panel_zdispl = new JPanel();
BoxLayout pipes_layout = new BoxLayout(panel_zdispl, BoxLayout.Y_AXIS);
this.panel_zdispl.setLayout(pipes_layout);
this.panel_zdispl.add(new JLabel("No objects."));
this.scroll_zdispl = makeScrollPane(panel_zdispl);
this.scroll_zdispl.setPreferredSize(new Dimension(250, 300));
this.scroll_zdispl.setMinimumSize(new Dimension(250, 300));
this.tabs.add("Z space", scroll_zdispl);
// Tab 4: channels
this.panel_channels = new JPanel();
BoxLayout channels_layout = new BoxLayout(panel_channels, BoxLayout.Y_AXIS);
this.panel_channels.setLayout(channels_layout);
this.scroll_channels = makeScrollPane(panel_channels);
this.scroll_channels.setPreferredSize(new Dimension(250, 300));
this.scroll_channels.setMinimumSize(new Dimension(250, 300));
this.channels = new Channel[4];
this.channels[0] = new Channel(this, Channel.MONO);
this.channels[1] = new Channel(this, Channel.RED);
this.channels[2] = new Channel(this, Channel.GREEN);
this.channels[3] = new Channel(this, Channel.BLUE);
//this.panel_channels.add(this.channels[0]);
this.panel_channels.add(this.channels[1]);
this.panel_channels.add(this.channels[2]);
this.panel_channels.add(this.channels[3]);
this.tabs.add("Opacity", scroll_channels);
// Tab 5: labels
this.panel_labels = new JPanel();
BoxLayout labels_layout = new BoxLayout(panel_labels, BoxLayout.Y_AXIS);
this.panel_labels.setLayout(labels_layout);
this.panel_labels.add(new JLabel("No labels."));
this.scroll_labels = makeScrollPane(panel_labels);
this.scroll_labels.setPreferredSize(new Dimension(250, 300));
this.scroll_labels.setMinimumSize(new Dimension(250, 300));
this.tabs.add("Labels", scroll_labels);
this.ht_tabs = new Hashtable<Class,JScrollPane>();
this.ht_tabs.put(Patch.class, scroll_patches);
this.ht_tabs.put(Profile.class, scroll_profiles);
this.ht_tabs.put(ZDisplayable.class, scroll_zdispl);
this.ht_tabs.put(AreaList.class, scroll_zdispl);
this.ht_tabs.put(Pipe.class, scroll_zdispl);
this.ht_tabs.put(Ball.class, scroll_zdispl);
this.ht_tabs.put(Dissector.class, scroll_zdispl);
this.ht_tabs.put(DLabel.class, scroll_labels);
// channels not included
// Navigator
this.navigator = new DisplayNavigator(this, layer.getLayerWidth(), layer.getLayerHeight());
// Layer scroller (to scroll slices)
int extent = (int)(250.0 / layer.getParent().size());
if (extent < 10) extent = 10;
this.scroller = new JScrollBar(JScrollBar.HORIZONTAL);
updateLayerScroller(layer);
this.scroller.addAdjustmentListener(scroller_listener);
// Left panel, contains the transp slider, the tabbed pane, the navigation panel and the layer scroller
JPanel left = new JPanel();
BoxLayout left_layout = new BoxLayout(left, BoxLayout.Y_AXIS);
left.setLayout(left_layout);
left.add(transp_slider);
left.add(tabs);
left.add(navigator);
left.add(scroller);
// Canvas
this.canvas = new DisplayCanvas(this, (int)Math.ceil(layer.getLayerWidth()), (int)Math.ceil(layer.getLayerHeight()));
this.canvas_panel = new JPanel();
GridBagLayout gb = new GridBagLayout();
this.canvas_panel.setLayout(gb);
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.NORTHWEST;
gb.setConstraints(this.canvas_panel, c);
gb.setConstraints(this.canvas, c);
// prevent new Displays from screweing up if input is globally disabled
if (!project.isInputEnabled()) this.canvas.setReceivesInput(false);
this.canvas_panel.add(canvas);
this.navigator.addMouseWheelListener(canvas);
this.transp_slider.addKeyListener(canvas);
// Split pane to contain everything
this.split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left, canvas_panel);
this.split.setOneTouchExpandable(true); // NOT present in all L&F (?)
// fix
gb.setConstraints(split.getRightComponent(), c);
// JFrame to show the split pane
this.frame = new JFrame(layer.toString());
if (IJ.isMacintosh() && IJ.getInstance()!=null) {
IJ.wait(10); // may be needed for Java 1.4 on OS X
this.frame.setMenuBar(ij.Menus.getMenuBar());
}
this.frame.addWindowListener(window_listener);
this.frame.addComponentListener(component_listener);
this.frame.getContentPane().add(split);
this.frame.addMouseListener(frame_mouse_listener);
//doesn't exist//this.frame.setMinimumSize(new Dimension(270, 600));
if (null != props) {
// restore canvas
canvas.setup(mag, srcRect);
// restore visibility of each channel
int cs = ((Integer)props[5]).intValue(); // aka c_alphas_state
int[] sel = new int[4];
sel[0] = ((cs&0xff000000)>>24);
sel[1] = ((cs&0xff0000)>>16);
sel[2] = ((cs&0xff00)>>8);
sel[3] = (cs&0xff);
// restore channel alphas
this.c_alphas = ((Integer)props[4]).intValue();
channels[0].setAlpha( (float)((c_alphas&0xff000000)>>24) / 255.0f , 0 != sel[0]);
channels[1].setAlpha( (float)((c_alphas&0xff0000)>>16) / 255.0f , 0 != sel[1]);
channels[2].setAlpha( (float)((c_alphas&0xff00)>>8) / 255.0f , 0 != sel[2]);
channels[3].setAlpha( (float) (c_alphas&0xff) / 255.0f , 0 != sel[3]);
// restore visibility in the working c_alphas
this.c_alphas = ((0 != sel[0] ? (int)(255 * channels[0].getAlpha()) : 0)<<24) + ((0 != sel[1] ? (int)(255 * channels[1].getAlpha()) : 0)<<16) + ((0 != sel[2] ? (int)(255 * channels[2].getAlpha()) : 0)<<8) + (0 != sel[3] ? (int)(255 * channels[3].getAlpha()) : 0);
}
if (null != active && null != layer) {
Rectangle r = active.getBoundingBox();
r.x -= r.width/2;
r.y -= r.height/2;
r.width += r.width;
r.height += r.height;
if (r.x < 0) r.x = 0;
if (r.y < 0) r.y = 0;
if (r.width > layer.getLayerWidth()) r.width = (int)layer.getLayerWidth();
if (r.height> layer.getLayerHeight())r.height= (int)layer.getLayerHeight();
double magn = layer.getLayerWidth() / (double)r.width;
canvas.setup(magn, r);
}
// add keyListener to the whole frame
this.tabs.addKeyListener(canvas);
this.canvas_panel.addKeyListener(canvas);
this.frame.addKeyListener(canvas);
this.frame.pack();
ij.gui.GUI.center(this.frame);
this.frame.setVisible(true);
ProjectToolbar.setProjectToolbar(); // doesn't get it through events
final Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
if (null != props) {
// fix positioning outside the screen (dual to single monitor)
if (p.x >= 0 && p.x < screen.width - 50 && p.y >= 0 && p.y <= screen.height - 50) this.frame.setLocation(p);
else frame.setLocation(0, 0);
}
// fix excessive size
final Rectangle box = this.frame.getBounds();
int x = box.x;
int y = box.y;
int width = box.width;
int height = box.height;
if (box.width > screen.width) { x = 0; width = screen.width; }
if (box.height > screen.height) { y = 0; height = screen.height; }
if (x != box.x || y != box.y) {
this.frame.setLocation(x, y + (0 == y ? 30 : 0)); // added insets for bad window managers
updateInDatabase("position");
}
if (width != box.width || height != box.height) {
this.frame.setSize(new Dimension(width -10, height -30)); // added insets for bad window managers
}
if (null == props) {
// try to optimize canvas dimensions and magn
double magn = layer.getLayerHeight() / screen.height;
if (magn > 1.0) magn = 1.0;
long size = 0;
// limit magnification if appropriate
for (Iterator it = layer.getDisplayables(Patch.class).iterator(); it.hasNext(); ) {
final Patch pa = (Patch)it.next();
final Rectangle ba = pa.getBoundingBox();
size += (long)(ba.width * ba.height);
}
if (size > 10000000) canvas.setInitialMagnification(0.25); // 10 Mb
else {
this.frame.setSize(new Dimension((int)(screen.width * 0.66), (int)(screen.height * 0.66)));
}
}
Utils.updateComponent(tabs); // otherwise fails in FreeBSD java 1.4.2 when reconstructing
// Set the calibration of the FakeImagePlus to that of the LayerSet
((FakeImagePlus)canvas.getFakeImagePlus()).setCalibrationSuper(layer.getParent().getCalibrationCopy());
// Set the FakeImagePlus as the current image
setTempCurrentImage();
// create a drag and drop listener
dnd = new DNDInsertImage(this);
// start a repainting thread
if (null != props) {
canvas.repaint(true); // repaint() is unreliable
}
// Set the minimum size of the tabbed pane on the left, so it can be completely collapsed now that it has been properly displayed. This is a patch to the lack of respect for the setDividerLocation method.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
tabs.setMinimumSize(new Dimension(0, 100));
}
});
}
private JScrollPane makeScrollPane(Component c) {
JScrollPane jsp = new JScrollPane(c);
// adjust scrolling to use one DisplayablePanel as the minimal unit
jsp.getVerticalScrollBar().setBlockIncrement(DisplayablePanel.HEIGHT); // clicking within the track
jsp.getVerticalScrollBar().setUnitIncrement(DisplayablePanel.HEIGHT); // clicking on an arrow
return jsp;
}
public JPanel getCanvasPanel() {
return canvas_panel;
}
public DisplayCanvas getCanvas() {
return canvas;
}
public void setLayer(final Layer layer) {
if (null == layer || layer == this.layer) return;
final boolean set_zdispl = null == Display.this.layer || layer.getParent() != Display.this.layer.getParent();
if (selection.isTransforming()) {
Utils.log("Can't browse layers while transforming.\nCANCEL the transform first with the ESCAPE key or right-click -> cancel.");
scroller.setValue(Display.this.layer.getParent().getLayerIndex(Display.this.layer.getId()));
return;
}
Display.this.layer = layer;
scroller.setValue(layer.getParent().getLayerIndex(layer.getId()));
// update the current Layer pointer in ZDisplayable objects
for (Iterator it = layer.getParent().getZDisplayables().iterator(); it.hasNext(); ) {
((ZDisplayable)it.next()).setLayer(layer); // the active layer
}
// update only the visible tab
switch (tabs.getSelectedIndex()) {
case 0:
ht_panels.clear();
updateTab(panel_patches, "Patches", layer.getDisplayables(Patch.class));
break;
case 1:
ht_panels.clear();
updateTab(panel_profiles, "Profiles", layer.getDisplayables(Profile.class));
break;
case 2:
if (set_zdispl) {
ht_panels.clear();
updateTab(panel_zdispl, "Z-space objects", layer.getParent().getZDisplayables());
}
break;
// case 3: channel opacities
case 4:
ht_panels.clear();
updateTab(panel_labels, "Labels", layer.getDisplayables(DLabel.class));
break;
}
// see if a lot has to be reloaded, put the relevant ones at the end
project.getLoader().prepare(layer);
updateTitle(); // to show the new 'z'
// select the Layer in the LayerTree
project.select(Display.this.layer); // does so in a separate thread
// update active Displayable:
// deselect all except ZDisplayables
final ArrayList sel = selection.getSelected();
final Displayable last_active = Display.this.active;
int sel_next = -1;
for (Iterator it = sel.iterator(); it.hasNext(); ) {
Displayable d = (Displayable)it.next();
if (!(d instanceof ZDisplayable)) {
it.remove();
selection.remove(d);
if (d == last_active && sel.size() > 0) {
// select the last one of the remaining, if any
sel_next = sel.size()-1;
}
}
}
if (-1 != sel_next && sel.size() > 0) select((Displayable)sel.get(sel_next), true);
else if (null != last_active && last_active.getClass() == Patch.class && null != last_temp && last_temp instanceof PatchStack) {
Displayable d = ((PatchStack)last_temp).getPatch(layer, (Patch)last_active);
if (null != d) selection.add(d);
}
// TODO last_temp doesn't remain the PatchStack // Utils.log2("last_temp is: " + last_temp.getClass().getName());
// repaint everything
navigator.repaint(true);
canvas.repaint(true);
// repaint tabs (hard as hell)
Utils.updateComponent(tabs);
// @#$%^! The above works half the times, so explicit repaint as well:
Component c = tabs.getSelectedComponent();
if (null == c) {
c = scroll_patches;
tabs.setSelectedComponent(scroll_patches);
}
Utils.updateComponent(c);
project.getLoader().setMassiveMode(false); // resetting if it was set true
// update the coloring in the ProjectTree
project.getProjectTree().updateUILater();
setTempCurrentImage();
}
private void setLayerLater(final Layer layer, final Displayable active) {
if (null == layer) return;
this.layer = layer;
if (!ControlWindow.isGUIEnabled()) return;
SwingUtilities.invokeLater(new Runnable() { public void run() {
// empty the tabs, except channels and pipes
clearTab(panel_profiles, "Profiles");
clearTab(panel_patches, "Patches");
clearTab(panel_labels, "Labels");
// distribute Displayable to the tabs. Ignore LayerSet instances.
if (null == ht_panels) ht_panels = new Hashtable<Displayable,DisplayablePanel>();
else ht_panels.clear();
Iterator it = layer.getDisplayables().iterator();
while (it.hasNext()) {
add((Displayable)it.next(), false, false);
}
it = layer.getParent().getZDisplayables().iterator(); // the pipes, that live in the LayerSet
while (it.hasNext()) {
add((Displayable)it.next(), false, false);
}
navigator.repaint(true); // was not done when adding
Utils.updateComponent(tabs.getSelectedComponent());
//
setActive(active);
}});
// swing issues:
/*
new Thread() {
public void run() {
setPriority(Thread.NORM_PRIORITY);
try { Thread.sleep(1000); } catch (Exception e) {}
setActive(active);
}
}.start();
*/
}
/** Remove all components from the tab and add a "No [label]" label to each. */
private void clearTab(final Container c, final String label) {
c.removeAll();
c.add(new JLabel("No " + label + "."));
// magic cocktail:
if (tabs.getSelectedComponent() == c) {
Utils.updateComponent(c);
}
}
/** A class to listen to the transparency_slider of the DisplayablesSelectorWindow. */
private class TransparencySliderListener extends MouseAdapter implements ChangeListener {
public void stateChanged(ChangeEvent ce) {
//change the transparency value of the current active displayable
float new_value = (float)((JSlider)ce.getSource()).getValue();
setTransparency(new_value / 100.0f);
}
public void mouseReleased(MouseEvent me) {
// update navigator window
navigator.repaint(true);
}
}
/** Context-sensitive: to a Displayable, or to a channel. */
private void setTransparency(float value) {
JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent();
if (scroll == scroll_channels) {
for (int i=0; i<4; i++) {
if (channels[i].getBackground() == Color.cyan) {
channels[i].setAlpha(value); // will call back and repaint the Display
return;
}
}
} else if (null != active) {
canvas.invalidateVolatile();
active.setAlpha(value);
}
}
public void setTransparencySlider(float transp) {
if (transp >= 0.0f && transp <= 1.0f) {
// fire event
transp_slider.setValue((int)(transp * 100));
}
}
/** Mark the canvas for updating the offscreen images if the given Displayable is NOT the active. */ // Used by the Displayable.setVisible for example.
static public void setUpdateGraphics(final Layer layer, final Displayable displ) {
for (Display d : al_displays) {
if (layer == d.layer && null != d.active && d.active != displ) {
d.canvas.setUpdateGraphics(true);
}
}
}
/** Flag the DisplayCanvas of Displays showing the given Layer to update their offscreen images.*/
static public void setUpdateGraphics(final Layer layer, final boolean update) {
for (Display d : al_displays) {
if (layer == d.layer) {
d.canvas.setUpdateGraphics(update);
}
}
}
/** Whether to update the offscreen images or not. */
public void setUpdateGraphics(boolean b) {
canvas.setUpdateGraphics(b);
}
/** Find all Display instances that contain the layer and repaint them, in the Swing GUI thread. */
static public void update(final Layer layer) {
if (null == layer) return;
SwingUtilities.invokeLater(new Runnable() { public void run() {
for (Display d : al_displays) {
if (d.isShowing(layer)) {
d.repaintAll();
}
}
}});
}
static public void update(final LayerSet set) {
update(set, true);
}
/** Find all Display instances showing a Layer of this LayerSet, and update the dimensions of the navigator and canvas and snapshots, and repaint, in the Swing GUI thread. */
static public void update(final LayerSet set, final boolean update_canvas_dimensions) {
if (null == set) return;
SwingUtilities.invokeLater(new Runnable() { public void run() {
for (Display d : al_displays) {
if (set.contains(d.layer)) {
d.updateSnapshots();
if (update_canvas_dimensions) d.canvas.setDimensions(set.getLayerWidth(), set.getLayerHeight());
d.repaintAll();
}
}
}});
}
/** Release all resources held by this Display and close the frame. */
protected void destroy() {
dispatcher.quit();
canvas.setReceivesInput(false);
synchronized (setting_layer_lock) {
while (setting_layer) {
try { setting_layer_lock.wait(); } catch (InterruptedException ie) {}
}
setting_layer = true;
if (null != set_layer_thread) set_layer_thread.quit();
// update the coloring in the ProjectTree and LayerTree
if (!project.isBeingDestroyed()) {
try {
project.getProjectTree().updateUILater();
project.getLayerTree().updateUILater();
} catch (Exception e) {
Utils.log2("updateUI failed at Display.destroy()");
}
}
frame.removeComponentListener(component_listener);
frame.removeWindowListener(window_listener);
frame.removeWindowFocusListener(window_listener);
frame.removeWindowStateListener(window_listener);
frame.removeKeyListener(canvas);
frame.removeMouseListener(frame_mouse_listener);
canvas_panel.removeKeyListener(canvas);
canvas.removeKeyListener(canvas);
tabs.removeChangeListener(tabs_listener);
tabs.removeKeyListener(canvas);
ImagePlus.removeImageListener(this);
canvas.destroy();
navigator.destroy();
scroller.removeAdjustmentListener(scroller_listener);
frame.setVisible(false);
//no need, and throws exception//frame.dispose();
active = null;
if (null != selection) selection.clear();
//Utils.log2("destroying selection");
// below, need for SetLayerThread threads to quit if any.
setting_layer = false;
setting_layer_lock.notifyAll();
// set a new front if any
if (null == front && al_displays.size() > 0) {
front = (Display)al_displays.get(al_displays.size() -1);
}
// repaint layer tree (to update the label color)
try {
project.getLayerTree().updateUILater(); // works only after setting the front above
} catch (Exception e) {} // ignore swing sync bullshit when closing everything too fast
// remove the drag and drop listener
dnd.destroy();
}
}
/** Find all Display instances that contain a Layer of the given project and close them without removing the Display entries from the database. */
static synchronized public void close(final Project project) {
/* // concurrent modifications if more than 1 Display are being removed asynchronously
for (Display d : al_displays) {
if (d.getLayer().getProject().equals(project)) {
it.remove();
d.destroy();
}
}
*/
Display[] d = new Display[al_displays.size()];
al_displays.toArray(d);
for (int i=0; i<d.length; i++) {
if (d[i].getProject() == project) {
al_displays.remove(d[i]);
d[i].destroy();
}
}
}
/** Find all Display instances that contain the layer and close them and remove the Display from the database. */
static public void close(final Layer layer) {
for (Iterator it = al_displays.iterator(); it.hasNext(); ) {
Display d = (Display)it.next();
if (d.isShowing(layer)) {
d.remove(false);
it.remove();
}
}
}
public boolean remove(boolean check) {
if (check) {
if (!Utils.check("Delete the Display ?")) return false;
}
// flush the offscreen images and close the frame
destroy();
removeFromDatabase();
return true;
}
public Layer getLayer() {
return layer;
}
public boolean isShowing(final Layer layer) {
return this.layer == layer;
}
public DisplayNavigator getNavigator() {
return navigator;
}
/** Repaint both the canvas and the navigator, updating the graphics, and the title and tabs. */
public void repaintAll() {
if (repaint_disabled) return;
navigator.repaint(true);
canvas.repaint(true);
Utils.updateComponent(tabs);
updateTitle();
}
/** Repaint the canvas updating graphics, the navigator without updating graphics, and the title. */
public void repaintAll2() {
if (repaint_disabled) return;
navigator.repaint(false);
canvas.repaint(true);
updateTitle();
}
static public void repaintSnapshots(final LayerSet set) {
if (repaint_disabled) return;
for (Display d : al_displays) {
if (d.getLayer().getParent() == set) {
d.navigator.repaint(true);
Utils.updateComponent(d.tabs);
}
}
}
static public void repaintSnapshots(final Layer layer) {
if (repaint_disabled) return;
for (Display d : al_displays) {
if (d.getLayer() == layer) {
d.navigator.repaint(true);
Utils.updateComponent(d.tabs);
}
}
}
public void pack() {
dispatcher.exec(new Runnable() { public void run() {
try {
SwingUtilities.invokeAndWait(new Runnable() { public void run() {
frame.pack();
}});
} catch (Exception e) { IJError.print(e); }
}});
}
static public void pack(final LayerSet ls) {
for (Display d : al_displays) {
if (d.layer.getParent() == ls) d.pack();
}
}
protected void adjustCanvas() {
Rectangle r = split.getRightComponent().getBounds();
canvas.setDrawingSize(r.width, r.height, true);
//frame.pack(); // don't! Would go into an infinite loop
canvas.repaint(true);
updateInDatabase("srcRect");
}
/** Grab the last selected display (or create an new one if none) and show in it the layer,centered on the Displayable object. */
static public void setFront(Layer layer, Displayable displ) {
if (null == front) {
Display display = new Display(layer.getProject(), layer); // gets set to front
display.showCentered(displ);
} else {
front.showCentered(displ);
}
}
/** Find the displays that show the given Layer, and add the given Displayable to the GUI and sets it active only in the front Display and only if 'activate' is true. */
static public void add(final Layer layer, final Displayable displ, final boolean activate) {
for (Display d : al_displays) {
if (d.layer == layer) {
if (front == d) {
d.add(displ, activate, true);
//front.frame.toFront();
} else {
d.add(displ, false, true);
}
}
}
}
static public void add(final Layer layer, final Displayable displ) {
add(layer, displ, true);
}
/** Add the ZDisplayable to all Displays that show a Layer belonging to the given LayerSet. */
static public void add(final LayerSet set, final ZDisplayable zdispl) {
for (Display d : al_displays) {
if (set.contains(d.layer)) {
if (front == d) {
zdispl.setLayer(d.layer); // the active one
d.add(zdispl, true, true); // calling add(Displayable, boolean, boolean)
//front.frame.toFront();
} else {
d.add(zdispl, false, true);
}
}
}
}
/** Add it to the proper panel, at the top, and set it active. */
private final void add(final Displayable d, final boolean activate, final boolean repaint_snapshot) {
DisplayablePanel dp = ht_panels.get(d);
if (null != dp && activate) { // for ZDisplayable objects (TODO I think this is not used anymore)
dp.setActive(true);
//setActive(d);
selection.clear();
selection.add(d);
return;
}
// add to the proper list
JPanel p = null;
if (d instanceof Profile) {
p = panel_profiles;
} else if (d instanceof Patch) {
p = panel_patches;
} else if (d instanceof DLabel) {
p = panel_labels;
} else if (d instanceof ZDisplayable) { //both pipes and balls and AreaList
p = panel_zdispl;
} else {
// LayerSet objects
return;
}
dp = new DisplayablePanel(this, d); // TODO: instead of destroying/recreating, we could just recycle them by reassigning a different Displayable. See how it goes! It'd need a pool of objects
addToPanel(p, 0, dp, activate);
ht_panels.put(d, dp);
if (activate) {
dp.setActive(true);
//setActive(d);
selection.clear();
selection.add(d);
}
if (repaint_snapshot) navigator.repaint(true);
}
private void addToPanel(JPanel panel, int index, DisplayablePanel dp, boolean repaint) {
// remove the label
if (1 == panel.getComponentCount() && panel.getComponent(0) instanceof JLabel) {
panel.removeAll();
}
panel.add(dp, index);
if (repaint) {
Utils.updateComponent(tabs);
}
}
/** Find the displays that show the given Layer, and remove the given Displayable from the GUI. */
static public void remove(final Layer layer, final Displayable displ) {
for (Display d : al_displays) {
if (layer == d.layer) d.remove(displ);
}
}
private void remove(final Displayable displ) {
DisplayablePanel ob = ht_panels.remove(displ);
if (null != ob) {
final JScrollPane jsp = ht_tabs.get(displ.getClass());
if (null != jsp) {
JPanel p = (JPanel)jsp.getViewport().getView();
p.remove((Component)ob);
Utils.revalidateComponent(p);
}
}
if (null == active || !selection.contains(displ)) {
canvas.setUpdateGraphics(true);
}
layer.getParent().removeFromUndo(displ);
canvas.invalidateVolatile(); // removing active, no need to update offscreen but yes the volatile
repaint(displ, null, 5, true, false);
selection.remove(displ);
}
static public void remove(final ZDisplayable zdispl) {
for (Display d : al_displays) {
if (zdispl.getLayerSet() == d.layer.getParent()) {
d.remove((Displayable)zdispl);
}
}
}
static public void repaint(final Layer layer, final Displayable displ, final int extra) {
repaint(layer, displ, displ.getBoundingBox(), extra);
}
static public void repaint(final Layer layer, final Displayable displ, final Rectangle r, final int extra) {
repaint(layer, displ, r, extra, true);
}
/** Find the displays that show the given Layer, and repaint the given Displayable. */
static public void repaint(final Layer layer, final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator) {
if (repaint_disabled) return;
for (Display d : al_displays) {
if (layer == d.layer) {
d.repaint(displ, r, extra, repaint_navigator, false);
}
}
}
static public void repaint(final Displayable d) {
if (d instanceof ZDisplayable) repaint(d.getLayerSet(), d, d.getBoundingBox(null), 5, true);
repaint(d.getLayer(), d, d.getBoundingBox(null), 5, true);
}
/** Repaint as much as the bounding box around the given Displayable, or the r if not null. */
private void repaint(final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator, final boolean update_graphics) {
if (repaint_disabled || null == displ) return;
if (update_graphics || displ.getClass() == Patch.class || displ != active) {
canvas.setUpdateGraphics(true);
}
if (null != r) canvas.repaint(r, extra);
else canvas.repaint(displ, extra);
if (repaint_navigator) {
DisplayablePanel dp = ht_panels.get(displ);
if (null != dp) dp.repaint(); // is null when creating it, or after deleting it
navigator.repaint(true); // everything
}
}
/** Repaint the snapshot for the given Displayable both at the DisplayNavigator and on its panel,and only if it has not been painted before. This method is intended for the loader to know when to paint a snap, to avoid overhead. */
static public void repaintSnapshot(final Displayable displ) {
for (Display d : al_displays) {
if (d.layer.contains(displ)) {
if (!d.navigator.isPainted(displ)) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) dp.repaint(); // is null when creating it, or after deleting it
d.navigator.repaint(displ);
}
}
}
}
/** Repaint the given Rectangle in all Displays showing the layer, updating the offscreen image if any. */
static public void repaint(final Layer layer, final Rectangle r, final int extra) {
repaint(layer, extra, r, true, true);
}
static public void repaint(final Layer layer, final int extra, final Rectangle r, final boolean update_navigator) {
repaint(layer, extra, r, update_navigator, true);
}
static public void repaint(final Layer layer, final int extra, final Rectangle r, final boolean update_navigator, final boolean update_graphics) {
if (repaint_disabled) return;
for (Display d : al_displays) {
if (layer == d.layer) {
d.canvas.setUpdateGraphics(update_graphics);
d.canvas.repaint(r, extra);
if (update_navigator) {
d.navigator.repaint(true);
Utils.updateComponent(d.tabs.getSelectedComponent());
}
}
}
}
/** Repaint the given Rectangle in all Displays showing the layer, optionally updating the offscreen image (if any). */
static public void repaint(final Layer layer, final Rectangle r, final int extra, final boolean update_graphics) {
if (repaint_disabled) return;
for (Display d : al_displays) {
if (layer == d.layer) {
d.canvas.setUpdateGraphics(update_graphics);
d.canvas.repaint(r, extra);
d.navigator.repaint(update_graphics);
if (update_graphics) Utils.updateComponent(d.tabs.getSelectedComponent());
}
}
}
/** Repaint the DisplayablePanel (and DisplayNavigator) only for the given Displayable, in all Displays showing the given Layer. */
static public void repaint(final Layer layer, final Displayable displ) {
if (repaint_disabled) return;
for (Display d : al_displays) {
if (layer == d.layer) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) dp.repaint();
d.navigator.repaint(true);
}
}
}
static public void repaint(LayerSet set, Displayable displ, int extra) {
repaint(set, displ, null, extra);
}
static public void repaint(LayerSet set, Displayable displ, Rectangle r, int extra) {
repaint(set, displ, r, extra, true);
}
/** Repaint the Displayable in every Display that shows a Layer belonging to the given LayerSet. */
static public void repaint(final LayerSet set, final Displayable displ, final Rectangle r, final int extra, final boolean repaint_navigator) {
if (repaint_disabled) return;
for (Display d : al_displays) {
if (set.contains(d.layer)) {
if (repaint_navigator) {
if (null != displ) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) dp.repaint();
}
d.navigator.repaint(true);
}
if (null == displ || displ != d.active) d.setUpdateGraphics(true); // safeguard
// paint the given box or the actual Displayable's box
if (null != r) d.canvas.repaint(r, extra);
else d.canvas.repaint(displ, extra);
}
}
}
/** Repaint the entire LayerSet, in all Displays showing a Layer of it.*/
static public void repaint(final LayerSet set) {
if (repaint_disabled) return;
for (Display d : al_displays) {
if (set.contains(d.layer)) {
d.navigator.repaint(true);
d.canvas.repaint(true);
}
}
}
/** Repaint the given box in the LayerSet, in all Displays showing a Layer of it.*/
static public void repaint(final LayerSet set, final Rectangle box) {
if (repaint_disabled) return;
for (Display d : al_displays) {
if (set.contains(d.layer)) {
d.navigator.repaint(box);
d.canvas.repaint(box, 0, true);
}
}
}
/** Repaint the entire Layer, in all Displays showing it, including the tabs.*/
static public void repaint(final Layer layer) { // TODO this method overlaps with update(layer)
if (repaint_disabled) return;
for (Display d : al_displays) {
if (layer == d.layer) {
d.navigator.repaint(true);
d.canvas.repaint(true);
}
}
}
static private boolean repaint_disabled = false;
/** Set a flag to enable/disable repainting of all Display instances. */
static protected void setRepaint(boolean b) {
repaint_disabled = !b;
}
public Rectangle getBounds() {
return frame.getBounds();
}
public Point getLocation() {
return frame.getLocation();
}
public JFrame getFrame() {
return frame;
}
public void setLocation(Point p) {
this.frame.setLocation(p);
}
public Displayable getActive() {
return active; //TODO this should return selection.active !!
}
public void select(Displayable d) {
select(d, false);
}
/** Select/deselect accordingly to the current state and the shift key. */
public void select(final Displayable d, final boolean shift_down) {
if (null != active && active != d && active.getClass() != Patch.class) {
// active is being deselected, so link underlying patches
active.linkPatches();
}
if (null == d) {
//Utils.log2("Display.select: clearing selection");
canvas.setUpdateGraphics(true);
selection.clear();
return;
}
if (!shift_down) {
//Utils.log2("Display.select: single selection");
if (d != active) {
selection.clear();
selection.add(d);
}
} else if (selection.contains(d)) {
if (active == d) {
selection.remove(d);
//Utils.log2("Display.select: removing from a selection");
} else {
//Utils.log2("Display.select: activing within a selection");
selection.setActive(d);
}
} else {
//Utils.log2("Display.select: adding to an existing selection");
selection.add(d);
}
// update the image shown to ImageJ
setTempCurrentImage();
}
protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p, final Class c) {
choose(screen_x_p, screen_y_p, x_p, y_p, false, c);
}
protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p) {
choose(screen_x_p, screen_y_p, x_p, y_p, false, null);
}
/** Find a Displayable to add to the selection under the given point (which is in offscreen coords); will use a popup menu to give the user a range of Displayable objects to select from. */
protected void choose(int screen_x_p, int screen_y_p, int x_p, int y_p, boolean shift_down, Class c) {
//Utils.log("Display.choose: x,y " + x_p + "," + y_p);
final ArrayList<Displayable> al = new ArrayList<Displayable>(layer.find(x_p, y_p, true));
al.addAll(layer.getParent().findZDisplayables(layer, x_p, y_p, true)); // only visible ones
if (al.isEmpty()) {
Displayable act = this.active;
selection.clear();
canvas.setUpdateGraphics(true);
//Utils.log("choose: set active to null");
// fixing lack of repainting for unknown reasons, of the active one TODO this is a temporary solution
if (null != act) Display.repaint(layer, act, 5);
} else if (1 == al.size()) {
Displayable d = (Displayable)al.get(0);
if (null != c && d.getClass() != c) {
selection.clear();
return;
}
select(d, shift_down);
//Utils.log("choose 1: set active to " + active);
} else {
if (al.contains(active) && !shift_down) {
// do nothing
} else {
if (null != c) {
// check if at least one of them is of class c
// if only one is of class c, set as selected
// else show menu
for (Iterator it = al.iterator(); it.hasNext(); ) {
Object ob = it.next();
if (ob.getClass() != c) it.remove();
}
if (0 == al.size()) {
// deselect
selection.clear();
return;
}
if (1 == al.size()) {
select((Displayable)al.get(0), shift_down);
return;
}
// else, choose among the many
}
choose(screen_x_p, screen_y_p, al, shift_down, x_p, y_p);
}
//Utils.log("choose many: set active to " + active);
}
}
private void choose(final int screen_x_p, final int screen_y_p, final Collection al, final boolean shift_down, final int x_p, final int y_p) {
// show a popup on the canvas to choose
new Thread() {
public void run() {
final Object lock = new Object();
final DisplayableChooser d_chooser = new DisplayableChooser(al, lock);
final JPopupMenu pop = new JPopupMenu("Select:");
final Iterator itu = al.iterator();
while (itu.hasNext()) {
Displayable d = (Displayable)itu.next();
JMenuItem menu_item = new JMenuItem(d.toString());
menu_item.addActionListener(d_chooser);
pop.add(menu_item);
}
new Thread() {
public void run() {
pop.show(canvas, screen_x_p, screen_y_p);
}
}.start();
//now wait until selecting something
synchronized(lock) {
do {
try {
lock.wait();
} catch (InterruptedException ie) {}
} while (d_chooser.isWaiting() && pop.isShowing());
}
//grab the chosen Displayable object
Displayable d = d_chooser.getChosen();
//Utils.log("Chosen: " + d.toString());
if (null == d) { Utils.log2("Display.choose: returning a null!"); }
select(d, shift_down);
pop.setVisible(false);
// fix selection bug: never receives mouseReleased event when the popup shows
selection.mouseReleased(x_p, y_p, x_p, y_p, x_p, y_p);
}
}.start();
}
/** Used by the Selection exclusively. This method will change a lot in the near future, and may disappear in favor of getSelection().getActive(). All this method does is update GUI components related to the currently active and the newly active Displayable; called through SwingUtilities.invokeLater. */
protected void setActive(final Displayable displ) {
final Displayable prev_active = this.active;
this.active = displ;
SwingUtilities.invokeLater(new Runnable() { public void run() {
// renew current image if necessary
if (null != displ && displ == prev_active) {
// make sure the proper tab is selected.
selectTab(displ);
return; // the same
}
// deactivate previously active
if (null != prev_active) {
final DisplayablePanel ob = ht_panels.get(prev_active);
if (null != ob) ob.setActive(false);
// erase "decorations" of the previously active
canvas.repaint(selection.getBox(), 4);
}
// activate the new active
if (null != displ) {
final DisplayablePanel ob = ht_panels.get(displ);
if (null != ob) ob.setActive(true);
updateInDatabase("active_displayable_id");
if (displ.getClass() != Patch.class) project.select(displ); // select the node in the corresponding tree, if any.
// select the proper tab, and scroll to visible
selectTab(displ);
boolean update_graphics = null == prev_active || paintsBelow(prev_active, displ); // or if it's an image, but that's by default in the repaint method
repaint(displ, null, 5, false, update_graphics); // to show the border, and to repaint out of the background image
transp_slider.setValue((int)(displ.getAlpha() * 100));
} else {
//ensure decorations are removed from the panels, for Displayables in a selection besides the active one
Utils.updateComponent(tabs.getSelectedComponent());
}
}});
}
/** If the other paints under the base. */
public boolean paintsBelow(Displayable base, Displayable other) {
boolean zd_base = base instanceof ZDisplayable;
boolean zd_other = other instanceof ZDisplayable;
if (zd_other) {
if (base instanceof DLabel) return true; // zd paints under label
if (!zd_base) return false; // any zd paints over a mere displ if not a label
else {
// both zd, compare indices
ArrayList<ZDisplayable> al = other.getLayerSet().getZDisplayables();
return al.indexOf(base) > al.indexOf(other);
}
} else {
if (!zd_base) {
// both displ, compare indices
ArrayList<Displayable> al = other.getLayer().getDisplayables();
return al.indexOf(base) > al.indexOf(other);
} else {
// base is zd, other is d
if (other instanceof DLabel) return false;
return true;
}
}
}
/** Select the proper tab, and also scroll it to show the given Displayable -unless it's a LayerSet, and unless the proper tab is already showing. */
private void selectTab(final Displayable displ) {
Method method = null;
try {
if (!(displ instanceof LayerSet)) {
method = Display.class.getDeclaredMethod("selectTab", new Class[]{displ.getClass()});
}
} catch (Exception e) {
IJError.print(e);
}
if (null != method) {
final Method me = method;
dispatcher.exec(new Runnable() { public void run() {
try {
me.setAccessible(true);
me.invoke(Display.this, new Object[]{displ});
} catch (Exception e) { IJError.print(e); }
}});
}
}
private void selectTab(Patch patch) {
tabs.setSelectedComponent(scroll_patches);
scrollToShow(scroll_patches, ht_panels.get(patch));
}
private void selectTab(Profile profile) {
tabs.setSelectedComponent(scroll_profiles);
scrollToShow(scroll_profiles, ht_panels.get(profile));
}
private void selectTab(DLabel label) {
tabs.setSelectedComponent(scroll_labels);
scrollToShow(scroll_labels, ht_panels.get(label));
}
private void selectTab(ZDisplayable zd) {
tabs.setSelectedComponent(scroll_zdispl);
scrollToShow(scroll_zdispl, ht_panels.get(zd));
}
private void selectTab(Pipe d) { selectTab((ZDisplayable)d); }
private void selectTab(AreaList d) { selectTab((ZDisplayable)d); }
private void selectTab(Ball d) { selectTab((ZDisplayable)d); }
private void selectTab(Dissector d) { selectTab((ZDisplayable)d); }
/** A method to update the given tab, creating a new DisplayablePanel for each Displayable present in the given ArrayList, and storing it in the ht_panels (which is cleared first). */
private void updateTab(final Container tab, final String label, final ArrayList al) {
final boolean[] recreated = new boolean[]{false, true, true};
dispatcher.execSwing(new Runnable() { public void run() {
try {
if (0 == al.size()) {
tab.removeAll();
tab.add(new JLabel("No " + label + "."));
} else {
Component[] comp = tab.getComponents();
int next = 0;
if (1 == comp.length && comp[0].getClass() == JLabel.class) {
next = 1;
tab.remove(0);
}
for (Iterator it = al.iterator(); it.hasNext(); ) {
Displayable d = (Displayable)it.next();
DisplayablePanel dp = null;
if (next < comp.length) {
dp = (DisplayablePanel)comp[next++]; // recycling panels
dp.set(d);
} else {
dp = new DisplayablePanel(Display.this, d);
tab.add(dp);
}
ht_panels.put(d, dp);
}
if (next < comp.length) {
// remove from the end, to avoid potential repaints of other panels
for (int i=comp.length-1; i>=next; i--) {
tab.remove(i);
}
}
recreated[0] = true;
}
if (recreated[0]) {
tab.invalidate();
tab.validate();
tab.repaint();
}
if (null != Display.this.active) scrollToShow(Display.this.active);
} catch (Throwable e) { IJError.print(e); }
}});
}
static public void setActive(final Object event, final Displayable displ) {
if (!(event instanceof InputEvent)) return;
// find which Display
for (Display d : al_displays) {
if (d.isOrigin((InputEvent)event)) {
d.setActive(displ);
break;
}
}
}
/** Find out whether this Display is Transforming its active Displayable. */
public boolean isTransforming() {
return canvas.isTransforming();
}
/** Find whether any Display is transforming the given Displayable. */
static public boolean isTransforming(final Displayable displ) {
for (Display d : al_displays) {
if (null != d.active && d.active == displ && d.canvas.isTransforming()) return true;
}
return false;
}
static public boolean isAligning(final LayerSet set) {
for (Display d : al_displays) {
if (d.layer.getParent() == set && set.isAligning()) {
return true;
}
}
return false;
}
/** Set the front Display to transform the Displayable only if no other canvas is transforming it. */
static public void setTransforming(final Displayable displ) {
if (null == front) return;
if (front.active != displ) return;
for (Display d : al_displays) {
if (d.active == displ) {
if (d.canvas.isTransforming()) {
Utils.showMessage("Already transforming " + displ.getTitle());
return;
}
}
}
front.canvas.setTransforming(true);
}
/** Check whether the source of the event is located in this instance.*/
private boolean isOrigin(InputEvent event) {
Object source = event.getSource();
// find it ... check the canvas for now TODO
if (canvas == source) {
return true;
}
return false;
}
/** Get the layer of the front Display, or null if none.*/
static public Layer getFrontLayer() {
if (null == front) return null;
return front.layer;
}
/** Get the layer of an open Display of the given Project, or null if none.*/
static public Layer getFrontLayer(final Project project) {
if (null == front) return null;
if (front.project == project) return front.layer;
// else, find an open Display for the given Project, if any
for (Display d : al_displays) {
if (d.project == project) {
d.frame.toFront();
return d.layer;
}
}
return null; // none found
}
static public Display getFront(final Project project) {
if (null == front) return null;
if (front.project == project) return front;
for (Display d : al_displays) {
if (d.project == project) {
d.frame.toFront();
return d;
}
}
return null;
}
public boolean isReadOnly() {
// TEMPORARY: in the future one will be able show displays as read-only to other people, remotely
return false;
}
static public void showPopup(Component c, int x, int y) {
if (null != front) front.getPopupMenu().show(c, x, y);
}
/** Return a context-sensitive popup menu. */
public JPopupMenu getPopupMenu() { // called from canvas
// get the job canceling dialog
if (!canvas.isInputEnabled()) {
return project.getLoader().getJobsPopup(this);
}
// create new
this.popup = new JPopupMenu();
JMenuItem item = null;
JMenu menu = null;
if (ProjectToolbar.ALIGN == Toolbar.getToolId()) {
boolean aligning = layer.getParent().isAligning();
item = new JMenuItem("Cancel alignment"); item.addActionListener(this); popup.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true));
if (!aligning) item.setEnabled(false);
item = new JMenuItem("Align with landmarks"); item.addActionListener(this); popup.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true));
if (!aligning) item.setEnabled(false);
item = new JMenuItem("Align and register"); item.addActionListener(this); popup.add(item);
if (!aligning) item.setEnabled(false);
item = new JMenuItem("Align using profiles"); item.addActionListener(this); popup.add(item);
if (!aligning || selection.isEmpty() || !selection.contains(Profile.class)) item.setEnabled(false);
item = new JMenuItem("Align stack slices"); item.addActionListener(this); popup.add(item);
if (selection.isEmpty() || ! (getActive().getClass() == Patch.class && ((Patch)getActive()).isStack())) item.setEnabled(false);
item = new JMenuItem("Align layers (layer-wise)"); item.addActionListener(this); popup.add(item);
if (1 == layer.getParent().size()) item.setEnabled(false);
item = new JMenuItem("Align layers (tile-wise global minimization)"); item.addActionListener(this); popup.add(item);
if (1 == layer.getParent().size()) item.setEnabled(false);
return popup;
}
JMenu adjust_menu = new JMenu("Adjust");
if (null != active) {
if (!canvas.isTransforming()) {
if (active instanceof Profile) {
item = new JMenuItem("Duplicate, link and send to next layer"); item.addActionListener(this); popup.add(item);
Layer nl = layer.getParent().next(layer);
if (nl == layer) item.setEnabled(false);
item = new JMenuItem("Duplicate, link and send to previous layer"); item.addActionListener(this); popup.add(item);
nl = layer.getParent().previous(layer);
if (nl == layer) item.setEnabled(false);
menu = new JMenu("Duplicate, link and send to");
ArrayList al = layer.getParent().getLayers();
Iterator it = al.iterator();
int i = 1;
while (it.hasNext()) {
Layer la = (Layer)it.next();
item = new JMenuItem(i + ": z = " + la.getZ()); item.addActionListener(this); menu.add(item); // TODO should label which layers contain Profile instances linked to the one being duplicated
if (la == this.layer) item.setEnabled(false);
i++;
}
popup.add(menu);
item = new JMenuItem("Duplicate, link and send to..."); item.addActionListener(this); popup.add(item);
popup.addSeparator();
item = new JMenuItem("Unlink from images"); item.addActionListener(this); popup.add(item);
if (!active.isLinked()) item.setEnabled(false); // isLinked() checks if it's linked to a Patch in its own layer
item = new JMenuItem("Show in 3D"); item.addActionListener(this); popup.add(item);
popup.addSeparator();
} else if (active instanceof Patch) {
item = new JMenuItem("Unlink from images"); item.addActionListener(this); popup.add(item);
if (!active.isLinked(Patch.class)) item.setEnabled(false);
if (((Patch)active).isStack()) {
item = new JMenuItem("Unlink slices"); item.addActionListener(this); popup.add(item);
}
int n_sel_patches = selection.getSelected(Patch.class).size();
if (1 == n_sel_patches) {
item = new JMenuItem("Snap"); item.addActionListener(this); popup.add(item);
} else if (n_sel_patches > 1) {
item = new JMenuItem("Montage"); item.addActionListener(this); popup.add(item);
}
item = new JMenuItem("Link images..."); item.addActionListener(this); popup.add(item);
item = new JMenuItem("View volume"); item.addActionListener(this); popup.add(item);
HashSet hs = active.getLinked(Patch.class);
if (null == hs || 0 == hs.size()) item.setEnabled(false);
item = new JMenuItem("View orthoslices"); item.addActionListener(this); popup.add(item);
if (null == hs || 0 == hs.size()) item.setEnabled(false); // if no Patch instances among the directly linked, then it's not a stack
popup.addSeparator();
} else {
item = new JMenuItem("Unlink"); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Show in 3D"); item.addActionListener(this); popup.add(item);
popup.addSeparator();
}
if (active instanceof AreaList) {
item = new JMenuItem("Merge"); item.addActionListener(this); popup.add(item);
ArrayList al = selection.getSelected();
int n = 0;
for (Iterator it = al.iterator(); it.hasNext(); ) {
if (it.next().getClass() == AreaList.class) n++;
}
if (n < 2) item.setEnabled(false);
} else if (active instanceof Pipe) {
item = new JMenuItem("Identify..."); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Identify with axes..."); item.addActionListener(this); popup.add(item);
}
}
if (canvas.isTransforming()) {
item = new JMenuItem("Apply transform"); item.addActionListener(this); popup.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, true)); // dummy, for I don't add a MenuKeyListener, but "works" through the normal key listener. It's here to provide a visual cue
} else {
item = new JMenuItem("Transform"); item.addActionListener(this); popup.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, 0, true));
}
item = new JMenuItem("Cancel transform"); item.addActionListener(this); popup.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true));
if (!canvas.isTransforming()) item.setEnabled(false);
if (canvas.isTransforming()) {
item = new JMenuItem("Specify transform..."); item.addActionListener(this); popup.add(item);
}
if (!canvas.isTransforming()) {
item = new JMenuItem("Color..."); item.addActionListener(this); popup.add(item);
if (active instanceof LayerSet) item.setEnabled(false);
if (active.isLocked()) {
item = new JMenuItem("Unlock"); item.addActionListener(this); popup.add(item);
} else {
item = new JMenuItem("Lock"); item.addActionListener(this); popup.add(item);
}
menu = new JMenu("Move");
popup.addSeparator();
LayerSet ls = layer.getParent();
item = new JMenuItem("Move to top"); item.addActionListener(this); menu.add(item);
if (ls.isTop(active)) item.setEnabled(false);
item = new JMenuItem("Move up"); item.addActionListener(this); menu.add(item);
if (ls.isTop(active)) item.setEnabled(false);
item = new JMenuItem("Move down"); item.addActionListener(this); menu.add(item);
if (ls.isBottom(active)) item.setEnabled(false);
item = new JMenuItem("Move to bottom"); item.addActionListener(this); menu.add(item);
if (ls.isBottom(active)) item.setEnabled(false);
popup.add(menu);
popup.addSeparator();
item = new JMenuItem("Delete..."); item.addActionListener(this); popup.add(item);
try {
if (active instanceof Patch) {
if (!active.isOnlyLinkedTo(Patch.class)) {
item.setEnabled(false);
}
} else if (!(active instanceof DLabel)) { // can't delete elements from the trees (Profile, Pipe, LayerSet)
item.setEnabled(false);
}
} catch (Exception e) { IJError.print(e); item.setEnabled(false); }
if (active instanceof Patch) {
item = new JMenuItem("Revert"); item.addActionListener(this); popup.add(item);
popup.addSeparator();
}
item = new JMenuItem("Properties..."); item.addActionListener(this); popup.add(item);
item = new JMenuItem("Show centered"); item.addActionListener(this); popup.add(item);
popup.addSeparator();
if (! (active instanceof ZDisplayable)) {
ArrayList al_layers = layer.getParent().getLayers();
int i_layer = al_layers.indexOf(layer);
int n_layers = al_layers.size();
item = new JMenuItem("Send to previous layer"); item.addActionListener(this); popup.add(item);
if (1 == n_layers || 0 == i_layer || active.isLinked()) item.setEnabled(false);
// check if the active is a profile and contains a link to another profile in the layer it is going to be sent to, or it is linked
else if (active instanceof Profile && !active.canSendTo(layer.getParent().previous(layer))) item.setEnabled(false);
item = new JMenuItem("Send to next layer"); item.addActionListener(this); popup.add(item);
if (1 == n_layers || n_layers -1 == i_layer || active.isLinked()) item.setEnabled(false);
else if (active instanceof Profile && !active.canSendTo(layer.getParent().next(layer))) item.setEnabled(false);
menu = new JMenu("Send linked group to...");
if (active.hasLinkedGroupWithinLayer(this.layer)) {
int i = 1;
for (Layer la : ls.getLayers()) {
String layer_title = i + ": " + la.getTitle();
if (-1 == layer_title.indexOf(' ')) layer_title += " ";
item = new JMenuItem(layer_title); item.addActionListener(this); menu.add(item);
if (la == this.layer) item.setEnabled(false);
i++;
}
popup.add(menu);
} else {
menu.setEnabled(false);
//Utils.log("Active's linked group not within layer.");
}
popup.add(menu);
popup.addSeparator();
item = new JMenuItem("Homogenize contrast (selected images)"); item.addActionListener(this); adjust_menu.add(item);
if (selection.getSelected(Patch.class).size() < 2) item.setEnabled(false);
}
}
}
if (!canvas.isTransforming()) {
item = new JMenuItem("Undo transforms");item.addActionListener(this); popup.add(item);
if (!layer.getParent().canUndo() || canvas.isTransforming()) item.setEnabled(false);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.SHIFT_MASK, true));
item = new JMenuItem("Redo transforms");item.addActionListener(this); popup.add(item);
if (!layer.getParent().canRedo() || canvas.isTransforming()) item.setEnabled(false);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.ALT_MASK, true));
item = new JMenuItem("Homogenize contrast layer-wise..."); item.addActionListener(this); adjust_menu.add(item);
item = new JMenuItem("Set Min and Max..."); item.addActionListener(this); adjust_menu.add(item);
popup.add(adjust_menu);
popup.addSeparator();
try {
menu = new JMenu("Hide/Unhide");
boolean none = 0 == selection.getNSelected();
item = new JMenuItem("Hide deselected"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.SHIFT_MASK, true));
if (none) item.setEnabled(false);
item = new JMenuItem("Hide selected"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, 0, true));
if (none) item.setEnabled(false);
none = ! layer.getParent().containsDisplayable(DLabel.class);
item = new JMenuItem("Hide all labels"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all labels"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(AreaList.class);
item = new JMenuItem("Hide all arealists"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all arealists"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.contains(Profile.class);
item = new JMenuItem("Hide all profiles"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all profiles"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(Pipe.class);
item = new JMenuItem("Hide all pipes"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all pipes"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().contains(Ball.class);
item = new JMenuItem("Hide all balls"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all balls"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
none = ! layer.getParent().containsDisplayable(Patch.class);
item = new JMenuItem("Hide all images"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Unhide all images"); item.addActionListener(this); menu.add(item);
if (none) item.setEnabled(false);
item = new JMenuItem("Hide all but images"); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Unhide all"); item.addActionListener(this); menu.add(item); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, Event.ALT_MASK, true));
popup.add(menu);
} catch (Exception e) { IJError.print(e); }
menu = new JMenu("Import");
item = new JMenuItem("Import image"); item.addActionListener(this); menu.add(item);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, Event.ALT_MASK & Event.SHIFT_MASK, true));
item = new JMenuItem("Import stack..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Import grid..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Import sequence as grid..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Import from text file..."); item.addActionListener(this); menu.add(item);
popup.add(menu);
menu = new JMenu("Display");
item = new JMenuItem("Make flat image..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Resize canvas/LayerSet..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Autoresize canvas/LayerSet"); item.addActionListener(this); menu.add(item);
// OBSOLETE // item = new JMenuItem("Rotate Layer/LayerSet..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Properties ..."); item.addActionListener(this); menu.add(item);
popup.add(menu);
menu = new JMenu("Project");
this.project.getLoader().setupMenuItems(menu, this.getProject());
item = new JMenuItem("Project properties..."); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Create subproject"); item.addActionListener(this); menu.add(item);
if (null == canvas.getFakeImagePlus().getRoi()) item.setEnabled(false);
item = new JMenuItem("Export arealists as labels"); item.addActionListener(this); menu.add(item);
if (0 == layer.getParent().getZDisplayables(AreaList.class).size()) item.setEnabled(false);
item = new JMenuItem("Release memory..."); item.addActionListener(this); menu.add(item);
if (menu.getItemCount() > 0) popup.add(menu);
menu = new JMenu("Selection");
item = new JMenuItem("Select all"); item.addActionListener(this); menu.add(item);
if (0 == layer.getDisplayables().size() && 0 == layer.getParent().getZDisplayables().size()) item.setEnabled(false);
item = new JMenuItem("Select none"); item.addActionListener(this); menu.add(item);
if (0 == selection.getNSelected()) item.setEnabled(false);
item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, true));
item = new JMenuItem("Restore selection"); item.addActionListener(this); menu.add(item);
item = new JMenuItem("Select under ROI"); item.addActionListener(this); menu.add(item);
if (canvas.getFakeImagePlus().getRoi() == null) item.setEnabled(false);
popup.add(menu);
item = new JMenuItem("Search..."); item.addActionListener(this); popup.add(item);
}
//canvas.add(popup);
return popup;
}
/** Check if a panel for the given Displayable is completely visible in the JScrollPane */
public boolean isWithinViewport(final Displayable d) {
final JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent();
if (ht_tabs.get(d.getClass()) == scroll) return isWithinViewport(scroll, ht_panels.get(d));
return false;
}
private boolean isWithinViewport(JScrollPane scroll, DisplayablePanel dp) {
if(null == dp) return false;
JViewport view = scroll.getViewport();
java.awt.Dimension dimensions = view.getExtentSize();
java.awt.Point p = view.getViewPosition();
int y = dp.getY();
if ((y + DisplayablePanel.HEIGHT - p.y) <= dimensions.height && y >= p.y) {
return true;
}
return false;
}
/** Check if a panel for the given Displayable is partially visible in the JScrollPane */
public boolean isPartiallyWithinViewport(final Displayable d) {
final JScrollPane scroll = ht_tabs.get(d.getClass());
if (tabs.getSelectedComponent() == scroll) return isPartiallyWithinViewport(scroll, ht_panels.get(d));
return false;
}
/** Check if a panel for the given Displayable is at least partially visible in the JScrollPane */
private boolean isPartiallyWithinViewport(final JScrollPane scroll, final DisplayablePanel dp) {
if(null == dp) {
//Utils.log2("Display.isPartiallyWithinViewport: null DisplayablePanel ??");
return false; // to fast for you baby
}
JViewport view = scroll.getViewport();
java.awt.Dimension dimensions = view.getExtentSize();
java.awt.Point p = view.getViewPosition();
int y = dp.getY();
if ( ((y + DisplayablePanel.HEIGHT - p.y) <= dimensions.height && y >= p.y) // completely visible
|| ((y + DisplayablePanel.HEIGHT - p.y) > dimensions.height && y < p.y + dimensions.height) // partially hovering at the bottom
|| ((y + DisplayablePanel.HEIGHT) > p.y && y < p.y) // partially hovering at the top
) {
return true;
}
return false;
}
/** A function to make a Displayable panel be visible in the screen, by scrolling the viewport of the JScrollPane. */
private void scrollToShow(final Displayable d) {
dispatcher.execSwing(new Runnable() { public void run() {
final JScrollPane scroll = (JScrollPane)tabs.getSelectedComponent();
if (d instanceof ZDisplayable && scroll == scroll_zdispl) {
scrollToShow(scroll_zdispl, ht_panels.get(d));
return;
}
final Class c = d.getClass();
if (Patch.class == c && scroll == scroll_patches) {
scrollToShow(scroll_patches, ht_panels.get(d));
} else if (DLabel.class == c && scroll == scroll_labels) {
scrollToShow(scroll_labels, ht_panels.get(d));
} else if (Profile.class == c && scroll == scroll_profiles) {
scrollToShow(scroll_profiles, ht_panels.get(d));
}
}});
}
private void scrollToShow(final JScrollPane scroll, final DisplayablePanel dp) {
if (null == dp) return;
JViewport view = scroll.getViewport();
Point current = view.getViewPosition();
Dimension extent = view.getExtentSize();
int panel_y = dp.getY();
if ((panel_y + DisplayablePanel.HEIGHT - current.y) <= extent.height && panel_y >= current.y) {
// it's completely visible already
return;
} else {
// scroll just enough
// if it's above, show at the top
if (panel_y - current.y < 0) {
view.setViewPosition(new Point(0, panel_y));
}
// if it's below (even if partially), show at the bottom
else if (panel_y + 50 > current.y + extent.height) {
view.setViewPosition(new Point(0, panel_y - extent.height + 50));
//Utils.log("Display.scrollToShow: panel_y: " + panel_y + " current.y: " + current.y + " extent.height: " + extent.height);
}
}
}
/** Update the title of the given Displayable in its DisplayablePanel, if any. */
static public void updateTitle(final Layer layer, final Displayable displ) {
for (Display d : al_displays) {
if (layer == d.layer) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) dp.updateTitle();
}
}
}
/** Update the Display's title in all Displays showing the given Layer. */
static public void updateTitle(final Layer layer) {
for (Display d : al_displays) {
if (d.layer == layer) {
d.updateTitle();
}
}
}
/** Update the Display's title in all Displays showing a Layer of the given LayerSet. */
static public void updateTitle(final LayerSet ls) {
for (Display d : al_displays) {
if (d.layer.getParent() == ls) {
d.updateTitle();
}
}
}
/** Set a new title in the JFrame, showing info on the layer 'z' and the magnification. */
public void updateTitle() {
// From ij.ImagePlus class, the solution:
String scale = "";
double magnification = canvas.getMagnification();
if (magnification!=1.0) {
double percent = magnification*100.0;
if (percent==(int)percent)
scale = " (" + Utils.d2s(percent,0) + "%)";
else
scale = " (" + Utils.d2s(percent,1) + "%)";
}
Calibration cal = layer.getParent().getCalibration();
String title = new StringBuffer().append(layer.getParent().indexOf(layer) + 1).append('/').append(layer.getParent().size()).append(' ').append((null == layer.getTitle() ? "" : layer.getTitle())).append(scale).append(" -- ").append(getProject().toString()).append(' ').append(' ').append(layer.getParent().getLayerWidth() * cal.pixelWidth).append('x').append(layer.getParent().getLayerHeight() * cal.pixelHeight).append(' ').append(cal.getUnit()).toString();
frame.setTitle(title);
// fix the title for the FakeImageWindow and thus the WindowManager listing in the menus
canvas.getFakeImagePlus().setTitle(title);
}
/** If shift is down, scroll to the next non-empty layer; otherwise, if scroll_step is larger than 1, then scroll 'scroll_step' layers ahead; else just the next Layer. */
public void nextLayer(final int modifiers) {
//setLayer(layer.getParent().next(layer));
//scroller.setValue(layer.getParent().getLayerIndex(layer.getId()));
if (0 == (modifiers ^ Event.SHIFT_MASK)) {
new SetLayerThread(this, layer.getParent().nextNonEmpty(layer));
} else if (scroll_step > 1) {
int i = layer.getParent().indexOf(this.layer);
Layer la = layer.getParent().getLayer(i + scroll_step);
if (null != la) new SetLayerThread(this, la);
} else {
new SetLayerThread(this, layer.getParent().next(layer));
}
updateInDatabase("layer_id");
}
/** If shift is down, scroll to the previous non-empty layer; otherwise, if scroll_step is larger than 1, then scroll 'scroll_step' layers backward; else just the previous Layer. */
public void previousLayer(final int modifiers) {
//setLayer(layer.getParent().previous(layer));
//scroller.setValue(layer.getParent().getLayerIndex(layer.getId()));
if (0 == (modifiers ^ Event.SHIFT_MASK)) {
new SetLayerThread(this, layer.getParent().previousNonEmpty(layer));
} else if (scroll_step > 1) {
int i = layer.getParent().indexOf(this.layer);
Layer la = layer.getParent().getLayer(i - scroll_step);
if (null != la) new SetLayerThread(this, la);
} else {
new SetLayerThread(this, layer.getParent().previous(layer));
}
updateInDatabase("layer_id");
}
static public void updateLayerScroller(LayerSet set) {
for (Display d : al_displays) {
if (d.layer.getParent() == set) {
d.updateLayerScroller(d.layer);
}
}
}
private void updateLayerScroller(Layer layer) {
int size = layer.getParent().size();
if (size <= 1) {
scroller.setValues(0, 1, 0, 0);
scroller.setEnabled(false);
} else {
scroller.setEnabled(true);
scroller.setValues(layer.getParent().getLayerIndex(layer.getId()), 1, 0, size);
}
}
private void updateSnapshots() {
Enumeration<DisplayablePanel> e = ht_panels.elements();
while (e.hasMoreElements()) {
e.nextElement().remake();
}
Utils.updateComponent(tabs.getSelectedComponent());
}
static public void updatePanel(Layer layer, final Displayable displ) {
if (null == layer && null != front) layer = front.layer; // the front layer
for (Display d : al_displays) {
if (d.layer == layer) {
d.updatePanel(displ);
}
}
}
private void updatePanel(Displayable d) {
JPanel c = null;
if (d instanceof Profile) {
c = panel_profiles;
} else if (d instanceof Patch) {
c = panel_patches;
} else if (d instanceof DLabel) {
c = panel_labels;
} else if (d instanceof Pipe) {
c = panel_zdispl;
}
if (null == c) return;
DisplayablePanel dp = ht_panels.get(d);
dp.remake();
Utils.updateComponent(c);
}
static public void updatePanelIndex(final Layer layer, final Displayable displ) {
for (Display d : al_displays) {
if (d.layer == layer || displ instanceof ZDisplayable) {
d.updatePanelIndex(displ);
}
}
}
private void updatePanelIndex(final Displayable d) {
// find first of the kind, then remove and insert its panel
int i = 0;
JPanel c = null;
if (d instanceof ZDisplayable) {
i = layer.getParent().indexOf((ZDisplayable)d);
c = panel_zdispl;
} else {
i = layer.relativeIndexOf(d);
if (d instanceof Profile) {
c = panel_profiles;
} else if (d instanceof Patch) {
c = panel_patches;
} else if (d instanceof DLabel) {
c = panel_labels;
}
}
if (null == c) return;
DisplayablePanel dp = ht_panels.get(d);
if (null == dp) return; // may be half-baked, wait
c.remove(dp);
c.add(dp, i); // java and its fabulous consistency
// not enough! Utils.updateComponent(c);
// So, cocktail:
c.invalidate();
c.validate();
Utils.updateComponent(c);
}
/** Repair possibly missing panels and other components by simply resetting the same Layer */
public void repairGUI() {
Layer layer = this.layer;
this.layer = null;
setLayer(layer);
}
public void actionPerformed(final ActionEvent ae) {
dispatcher.exec(new Runnable() { public void run() {
String command = ae.getActionCommand();
if (command.startsWith("Job")) {
if (Utils.checkYN("Really cancel job?")) {
project.getLoader().quitJob(command);
repairGUI();
}
return;
} else if (command.equals("Move to top")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.TOP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move up")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.UP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move down")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.DOWN, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move to bottom")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.BOTTOM, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Duplicate, link and send to next layer")) {
if (null == active || !(active instanceof Profile)) return;
Layer next_layer = layer.getParent().next(layer);
if (layer.equals(next_layer)) return; // no next layer! The menu item will be disabled anyway
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 1, next_layer);
if (null == profile) return;
active.link(profile);
next_layer.add(profile);
Thread thread = new SetLayerThread(Display.this, next_layer);//setLayer(next_layer);
try { thread.join(); } catch (InterruptedException ie) {} // wait until finished!
selection.add(profile); //setActive(profile);
} else if (command.equals("Duplicate, link and send to previous layer")) {
if (null == active || !(active instanceof Profile)) return;
Layer previous_layer = layer.getParent().previous(layer);
if (layer.equals(previous_layer)) return; // no previous layer!
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 0, previous_layer);
if (null == profile) return;
active.link(profile);
previous_layer.add(profile);
Thread thread = new SetLayerThread(Display.this, previous_layer);//setLayer(previous_layer);
try { thread.join(); } catch (InterruptedException ie) {} // wait until finished!
selection.add(profile); //setActive(profile);
} else if (command.equals("Duplicate, link and send to...")) {
// fix non-scrolling popup menu
GenericDialog gd = new GenericDialog("Send to");
gd.addMessage("Duplicate, link and send to...");
String[] sl = new String[layer.getParent().size()];
int next = 0;
for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) {
sl[next++] = project.findLayerThing(it.next()).toString();
}
gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex());
if (layer == la) {
Utils.showMessage("Can't duplicate, link and send to the same layer.");
return;
}
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 0, la);
if (null == profile) return;
active.link(profile);
la.add(profile);
Thread thread = new SetLayerThread(Display.this, la);//setLayer(la);
try { thread.join(); } catch (InterruptedException ie) {} // waint until finished!
selection.add(profile);
} else if (-1 != command.indexOf("z = ")) {
// this is an item from the "Duplicate, link and send to" menu of layer z's
Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1)));
Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__");
if (null == target_layer) return;
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 0, target_layer);
if (null == profile) return;
active.link(profile);
target_layer.add(profile);
Thread thread = new SetLayerThread(Display.this, target_layer);//setLayer(target_layer);
try { thread.join(); } catch (InterruptedException ie) {} // waint until finished!
selection.add(profile); // setActive(profile); // this is repainting only the active, not everything, because it cancels the repaint sent by the setLayer ! BUT NO, it should add up to the max box.
} else if (-1 != command.indexOf("z=")) {
// WARNING the indexOf is very similar to the previous one
// Send the linked group to the selected layer
int iz = command.indexOf("z=")+2;
Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2));
- double lz = Double.parseDouble(command.substring(iz, command.indexOf(' ', iz+2)));
+ int end = command.indexOf(' ', iz);
+ if (-1 == end) end = command.length();
+ double lz = Double.parseDouble(command.substring(iz, end));
Layer target = layer.getParent().getLayer(lz);
HashSet hs = active.getLinkedGroup(new HashSet());
layer.getParent().move(hs, active.getLayer(), target);
} else if (command.equals("Unlink")) {
if (null == active || active instanceof Patch) return;
active.unlink();
updateSelection();//selection.update();
} else if (command.equals("Unlink from images")) {
if (null == active) return;
try {
- active.unlinkAll(Patch.class);
+ for (Displayable displ: selection.getSelected()) {
+ displ.unlinkAll(Patch.class);
+ }
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
} else if (command.equals("Unlink slices")) {
YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo.");
if (!yn.yesPressed()) return;
final ArrayList<Patch> pa = ((Patch)active).getStackPatches();
for (int i=pa.size()-1; i>0; i--) {
pa.get(i).unlink(pa.get(i-1));
}
} else if (command.equals("Send to next layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
- active.unlinkAll(Patch.class);
+ for (Displayable displ : selection.getSelected()) {
+ displ.unlinkAll(Patch.class);
+ }
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers
selection.moveDown();
repaint(layer.getParent(), box);
} else if (command.equals("Send to previous layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
- active.unlinkAll(Patch.class);
+ for (Displayable displ : selection.getSelected()) {
+ displ.unlinkAll(Patch.class);
+ }
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers
selection.moveUp();
repaint(layer.getParent(), box);
} else if (command.equals("Show centered")) {
if (active == null) return;
showCentered(active);
} else if (command.equals("Delete...")) {
/*
if (null != active) {
Displayable d = active;
selection.remove(d);
d.remove(true); // will repaint
}
*/
// remove all selected objects
selection.deleteAll();
} else if (command.equals("Color...")) {
IJ.doCommand("Color Picker...");
} else if (command.equals("Revert")) {
if (null == active || active.getClass() != Patch.class) return;
Patch p = (Patch)active;
if (!p.revert()) {
if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId());
else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId());
}
} else if (command.equals("Undo transforms")) {
if (canvas.isTransforming()) return;
if (!layer.getParent().canRedo()) {
// catch the current
layer.getParent().appendCurrent(selection.getTransformationsCopy());
}
layer.getParent().undoOneStep();
} else if (command.equals("Redo transforms")) {
if (canvas.isTransforming()) return;
layer.getParent().redoOneStep();
} else if (command.equals("Transform")) {
if (null == active) {
Utils.log2("Display \"Transform\": null active!");
return;
}
canvas.setTransforming(true);
} else if (command.equals("Apply transform")) {
if (null == active) return;
canvas.setTransforming(false);
} else if (command.equals("Cancel transform")) {
if (null == active) return;
canvas.cancelTransform();
} else if (command.equals("Specify transform...")) {
if (null == active) return;
selection.specify();
} else if (command.equals("Hide all but images")) {
ArrayList<Class> type = new ArrayList<Class>();
type.add(Patch.class);
selection.removeAll(layer.getParent().hideExcept(type, false));
Display.update(layer.getParent(), false);
} else if (command.equals("Unhide all")) {
layer.getParent().setAllVisible(false);
Display.update(layer.getParent(), false);
} else if (command.startsWith("Hide all ")) {
String type = command.substring(9, command.length() -1); // skip the ending plural 's'
type = type.substring(0, 1).toUpperCase() + type.substring(1);
selection.removeAll(layer.getParent().setVisible(type, false, true));
} else if (command.startsWith("Unhide all ")) {
String type = command.substring(11, command.length() -1); // skip the ending plural 's'
type = type.substring(0, 1).toUpperCase() + type.substring(1);
layer.getParent().setVisible(type, true, true);
} else if (command.equals("Hide deselected")) {
hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers()));
} else if (command.equals("Hide selected")) {
selection.setVisible(false); // TODO should deselect them too? I don't think so.
} else if (command.equals("Resize canvas/LayerSet...")) {
resizeCanvas();
} else if (command.equals("Autoresize canvas/LayerSet")) {
layer.getParent().setMinimumDimensions();
} else if (command.equals("Import image")) {
importImage();
} else if (command.equals("Import next image")) {
importNextImage();
} else if (command.equals("Import stack...")) {
project.getLoader().importStack(layer, null, true);
} else if (command.equals("Import grid...")) {
project.getLoader().importGrid(layer);
} else if (command.equals("Import sequence as grid...")) {
project.getLoader().importSequenceAsGrid(layer);
} else if (command.equals("Import from text file...")) {
project.getLoader().importImages(layer);
} else if (command.equals("Make flat image...")) {
// if there's a ROI, just use that as cropping rectangle
Rectangle srcRect = null;
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null != roi) {
srcRect = roi.getBounds();
} else {
// otherwise, whatever is visible
//srcRect = canvas.getSrcRect();
// The above is confusing. That is what ROIs are for. So paint all:
srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight()));
}
double scale = 1.0;
final String[] types = new String[]{"8-bit grayscale", "RGB"};
int the_type = ImagePlus.GRAY8;
final GenericDialog gd = new GenericDialog("Choose", frame);
gd.addNumericField("Scale: ", 1.0, 2);
gd.addChoice("Type: ", types, types[0]);
if (layer.getParent().size() > 1) {
/*
String[] layers = new String[layer.getParent().size()];
int i = 0;
for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) {
layers[i] = layer.getProject().findLayerThing((Layer)it.next()).toString();
i++;
}
int i_layer = layer.getParent().indexOf(layer);
gd.addChoice("Start: ", layers, layers[i_layer]);
gd.addChoice("End: ", layers, layers[i_layer]);
*/
Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros
gd.addCheckbox("Include non-empty layers only", true);
}
gd.addCheckbox("Best quality", false);
gd.addMessage("");
gd.addCheckbox("Save to file", false);
gd.addCheckbox("Save for web", false);
gd.showDialog();
if (gd.wasCanceled()) return;
scale = gd.getNextNumber();
the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB);
if (Double.isNaN(scale) || scale <= 0.0) {
Utils.showMessage("Invalid scale.");
return;
}
Layer[] layer_array = null;
boolean non_empty_only = false;
if (layer.getParent().size() > 1) {
non_empty_only = gd.getNextBoolean();
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
ArrayList al = new ArrayList();
ArrayList al_zd = layer.getParent().getZDisplayables();
ZDisplayable[] zd = new ZDisplayable[al_zd.size()];
al_zd.toArray(zd);
for (int i=i_start, j=0; i <= i_end; i++, j++) {
Layer la = layer.getParent().getLayer(i);
if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet
}
if (0 == al.size()) {
Utils.showMessage("All layers are empty!");
return;
}
layer_array = new Layer[al.size()];
al.toArray(layer_array);
} else {
layer_array = new Layer[]{Display.this.layer};
}
final boolean quality = gd.getNextBoolean();
final boolean save_to_file = gd.getNextBoolean();
final boolean save_for_web = gd.getNextBoolean();
// in its own thread
if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type);
else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality);
} else if (command.equals("Lock")) {
selection.setLocked(true);
} else if (command.equals("Unlock")) {
selection.setLocked(false);
} else if (command.equals("Properties...")) {
active.adjustProperties();
updateSelection();
} else if (command.equals("Cancel alignment")) {
layer.getParent().cancelAlign();
} else if (command.equals("Align with landmarks")) {
layer.getParent().applyAlign(false);
} else if (command.equals("Align and register")) {
layer.getParent().applyAlign(true);
} else if (command.equals("Align using profiles")) {
if (!selection.contains(Profile.class)) {
Utils.showMessage("No profiles are selected.");
return;
}
// ask for range of layers
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer la_start = layer.getParent().getLayer(gd.getNextChoiceIndex());
Layer la_end = layer.getParent().getLayer(gd.getNextChoiceIndex());
if (la_start == la_end) {
Utils.showMessage("Need at least two layers.");
return;
}
if (selection.isLocked()) {
Utils.showMessage("There are locked objects.");
return;
}
layer.getParent().startAlign(Display.this);
layer.getParent().applyAlign(la_start, la_end, selection);
} else if (command.equals("Align stack slices")) {
if (getActive() instanceof Patch) {
final Patch slice = (Patch)getActive();
if (slice.isStack()) {
// check linked group
final HashSet hs = slice.getLinkedGroup(new HashSet());
for (Iterator it = hs.iterator(); it.hasNext(); ) {
if (it.next().getClass() != Patch.class) {
Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that
return;
}
}
slice.getLayer().getParent().createUndoStep(); // full
Registration.registerStackSlices((Patch)getActive()); // will repaint
} else {
Utils.log("Align stack slices: selected image is not part of a stack.");
}
}
} else if (command.equals("Align layers (layer-wise)")) {
Registration.registerLayers(layer, Registration.LAYER_SIFT);
} else if (command.equals("Align layers (tile-wise global minimization)")) {
Registration.registerLayers(layer, Registration.GLOBAL_MINIMIZATION);
} else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects.
GenericDialog gd = new GenericDialog("Properties", Display.this.frame);
//gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0);
gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step);
gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]);
gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality());
Loader lo = getProject().getLoader();
boolean using_mipmaps = lo.isMipMapsEnabled();
gd.addCheckbox("enable_mipmaps", using_mipmaps);
String preprocessor = project.getLoader().getPreprocessor();
gd.addStringField("image_preprocessor: ", null == preprocessor ? "" : preprocessor);
gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled());
double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight();
gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsDimension());
// --------
gd.showDialog();
if (gd.wasCanceled()) return;
// --------
int sc = (int) gd.getNextNumber();
if (sc < 1) sc = 1;
Display.this.scroll_step = sc;
updateInDatabase("scroll_step");
//
layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex());
layer.getParent().setSnapshotsQuality(gd.getNextBoolean());
//
boolean generate_mipmaps = gd.getNextBoolean();
if (using_mipmaps && generate_mipmaps) {
// nothing changed
} else {
if (using_mipmaps) { // and !generate_mipmaps
lo.flushMipMaps(true);
} else {
// not using mipmaps before, and true == generate_mipmaps
lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class));
}
}
//
final String prepro = gd.getNextString();
if (!project.getLoader().setPreprocessor(prepro.trim())) {
Utils.showMessage("Could NOT set the preprocessor to " + prepro);
}
//
layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean());
layer.getParent().setPixelsDimension((int)gd.getNextNumber());
} else if (command.equals("Search...")) {
new Search();
} else if (command.equals("Select all")) {
selection.selectAll();
repaint(Display.this.layer, selection.getBox(), 0);
} else if (command.equals("Select none")) {
Rectangle box = selection.getBox();
selection.clear();
repaint(Display.this.layer, box, 0);
} else if (command.equals("Restore selection")) {
selection.restore();
} else if (command.equals("Select under ROI")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return;
selection.selectAll(roi, true);
} else if (command.equals("Merge")) {
ArrayList al_sel = selection.getSelected();
// put active at the beginning, to work as the base on which other's will get merged
al_sel.remove(Display.this.active);
al_sel.add(0, Display.this.active);
AreaList ali = AreaList.merge(al_sel);
if (null != ali) {
// remove all but the first from the selection
for (int i=1; i<al_sel.size(); i++) {
Object ob = al_sel.get(i);
if (ob.getClass() == AreaList.class) {
selection.remove((Displayable)ob);
}
}
selection.updateTransform(ali);
repaint(ali.getLayerSet(), ali, 0);
}
} else if (command.equals("Identify...")) {
// for pipes only for now
if (!(active instanceof Pipe)) return;
ini.trakem2.vector.Compare.findSimilar((Pipe)active);
} else if (command.equals("Identify with axes...")) {
if (!(active instanceof Pipe)) return;
if (Project.getProjects().size() < 2) {
Utils.showMessage("You need at least two projects open:\n-A reference project\n-The current project with the pipe to identify");
return;
}
ini.trakem2.vector.Compare.findSimilarWithAxes((Pipe)active);
} else if (command.equals("View orthoslices")) {
if (!(active instanceof Patch)) return;
Display3D.showOrthoslices(((Patch)active));
} else if (command.equals("View volume")) {
if (!(active instanceof Patch)) return;
Display3D.showVolume(((Patch)active));
} else if (command.equals("Show in 3D")) {
for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) {
ZDisplayable zd = (ZDisplayable)it.next();
Display3D.show(zd.getProject().findProjectThing(zd));
}
// handle profile lists ...
HashSet hs = new HashSet();
for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) {
Displayable d = (Displayable)it.next();
ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent();
if (!hs.contains(profile_list)) {
Display3D.show(profile_list);
hs.add(profile_list);
}
}
} else if (command.equals("Snap")) {
if (!(active instanceof Patch)) return;
StitchingTEM.snap(getActive(), Display.this);
} else if (command.equals("Montage")) {
if (!(active instanceof Patch)) {
Utils.showMessage("Please select only images.");
return;
}
for (Object ob : selection.getSelected()) {
if (!(ob instanceof Patch)) {
Utils.showMessage("Please select only images.\nCurrently, a " + Project.getName(ob.getClass()) + " is also selected.");
return;
}
}
HashSet hs = new HashSet();
hs.addAll(selection.getSelected(Patch.class));
// make an undo step!
layer.getParent().addUndoStep(selection.getAffected());
Registration.registerTilesSIFT(hs, (Patch)active, null, false);
} else if (command.equals("Link images...")) {
GenericDialog gd = new GenericDialog("Options");
gd.addMessage("Linking images to images (within their own layer only):");
String[] options = {"all images to all images", "each image with any other overlapping image"};
gd.addChoice("Link: ", options, options[1]);
String[] options2 = {"selected images only", "all images in this layer", "all images in all layers"};
gd.addChoice("Apply to: ", options2, options2[0]);
gd.showDialog();
if (gd.wasCanceled()) return;
boolean overlapping_only = 1 == gd.getNextChoiceIndex();
switch (gd.getNextChoiceIndex()) {
case 0:
Patch.crosslink(selection.getSelected(Patch.class), overlapping_only);
break;
case 1:
Patch.crosslink(layer.getDisplayables(Patch.class), overlapping_only);
break;
case 2:
for (Layer la : layer.getParent().getLayers()) {
Patch.crosslink(la.getDisplayables(Patch.class), overlapping_only);
}
break;
}
} else if (command.equals("Homogenize contrast (selected images)")) {
ArrayList al = selection.getSelected(Patch.class);
if (al.size() < 2) return;
getProject().getLoader().homogenizeContrast(al);
} else if (command.equals("Homogenize contrast layer-wise...")) {
// ask for range of layers
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
java.util.List list = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
Layer[] la = new Layer[list.size()];
list.toArray(la);
project.getLoader().homogenizeContrast(la);
} else if (command.equals("Set Min and Max...")) {
final GenericDialog gd = new GenericDialog("Choices");
gd.addMessage("Either process all images of all layers\nwithin the selected range,\nor check the box for using selected images only.");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.addCheckbox("use_selected_images_only", false);
gd.addMessage("-------");
gd.addNumericField("min: ", 0, 2);
gd.addNumericField("max: ", 255, 2);
gd.addCheckbox("drift_mean", true);
gd.addMessage("Or let each image find its optimal:");
gd.addCheckbox("independent", false);
gd.showDialog();
if (gd.wasCanceled()) return;
boolean use_selected_images = gd.getNextBoolean();
double min = gd.getNextNumber();
double max = gd.getNextNumber();
if (Double.isNaN(min) || Double.isNaN(max) || min < 0 || max < min) {
Utils.showMessage("Improper min and max values.");
return;
}
boolean drift_hist_peak = gd.getNextBoolean();
boolean independent = gd.getNextBoolean();
Utils.log2("Di Using: " + min + ", " + max + ", " + drift_hist_peak + " use_selected_images: " + use_selected_images);
if (use_selected_images) {
ArrayList al_images = selection.getSelected(Patch.class);
if (al_images.size() < 1) {
Utils.log2("You need at least 2 images selected.");
return;
}
if (independent) {
project.getLoader().optimizeContrast(al_images);
} else {
project.getLoader().homogenizeContrast(al_images, min, max, drift_hist_peak);
}
} else {
java.util.List list = list = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
Layer[] la = new Layer[list.size()];
list.toArray(la);
if (independent) {
ArrayList al_images = new ArrayList();
for (int i=0; i<la.length; i++) {
al_images.addAll(la[i].getDisplayables(Patch.class));
}
project.getLoader().optimizeContrast(al_images);
} else {
project.getLoader().homogenizeContrast(la, min, max, drift_hist_peak);
}
}
} else if (command.equals("Create subproject")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return; // the menu item is not active unless there is a ROI
Layer first, last;
if (1 == layer.getParent().size()) {
first = last = layer;
} else {
GenericDialog gd = new GenericDialog("Choose layer range");
Utils.addLayerRangeChoices(layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
first = layer.getParent().getLayer(gd.getNextChoiceIndex());
last = layer.getParent().getLayer(gd.getNextChoiceIndex());
Utils.log2("first, last: " + first + ", " + last);
}
Project sub = getProject().createSubproject(roi.getBounds(), first, last);
final LayerSet subls = sub.getRootLayerSet();
final Display d = new Display(sub, subls.getLayer(0));
SwingUtilities.invokeLater(new Runnable() { public void run() {
d.canvas.showCentered(new Rectangle(0, 0, (int)subls.getLayerWidth(), (int)subls.getLayerHeight()));
}});
} else if (command.equals("Export arealists as labels")) {
GenericDialog gd = new GenericDialog("Export labels");
gd.addSlider("Scale: ", 1, 100, 100);
final String[] options = {"All area list", "Selected area lists"};
gd.addChoice("Export: ", options, options[0]);
Utils.addLayerRangeChoices(layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final float scale = (float)(gd.getNextNumber() / 100);
java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class);
if (null == al) {
Utils.log("No area lists found to export.");
return;
}
if (al.size() > 255) {
YesNoCancelDialog yn = new YesNoCancelDialog(frame, "WARNING", "Found more than 255 area lists to export:\nExport only the first 255?");
if (yn.cancelPressed()) return;
if (yn.yesPressed()) al = al.subList(0, 255); // only 255 total: the 0 is left for background
}
int first = gd.getNextChoiceIndex();
int last = gd.getNextChoiceIndex();
AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last);
} else if (command.equals("Project properties...")) {
project.adjustProperties();
} else if (command.equals("Release memory...")) {
new Bureaucrat(new Worker("Releasing memory") {
public void run() {
startedWorking();
try {
GenericDialog gd = new GenericDialog("Release Memory");
int max = (int)(IJ.maxMemory() / 1000000);
gd.addSlider("Megabytes: ", 0, max, max/2);
gd.showDialog();
if (!gd.wasCanceled()) {
int n_mb = (int)gd.getNextNumber();
project.getLoader().releaseToFit((long)n_mb*1000000);
}
} catch (Throwable e) {
IJError.print(e);
} finally {
finishedWorking();
}
}
}, project).goHaveBreakfast();
} else {
Utils.log2("Display: don't know what to do with command " + command);
}
}});
}
/** Update in all displays the Transform for the given Displayable if it's selected. */
static public void updateTransform(final Displayable displ) {
for (Display d : al_displays) {
if (d.selection.contains(displ)) d.selection.updateTransform(displ);
}
}
/** Order the profiles of the parent profile_list by Z order, and fix the ProjectTree.*/
/*
private void fixZOrdering(Profile profile) {
ProjectThing thing = project.findProjectThing(profile);
if (null == thing) {
Utils.log2("Display.fixZOrdering: null thing?");
return;
}
((ProjectThing)thing.getParent()).fixZOrdering();
project.getProjectTree().updateList(thing.getParent());
}
*/
/** The number of layers to scroll through with the wheel; 1 by default.*/
public int getScrollStep() { return this.scroll_step; }
public void setScrollStep(int scroll_step) {
if (scroll_step < 1) scroll_step = 1;
this.scroll_step = scroll_step;
updateInDatabase("scroll_step");
}
protected Bureaucrat importImage() {
Worker worker = new Worker("Import image") { /// all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN
public void run() {
startedWorking();
try {
///
Rectangle srcRect = canvas.getSrcRect();
int x = srcRect.x + srcRect.width / 2;
int y = srcRect.y + srcRect.height/ 2;
Patch p = project.getLoader().importImage(project, x, y);
if (null == p) {
finishedWorking();
Utils.showMessage("Could not open the image.");
return;
}
layer.add(p); // will add it to the proper Displays
///
} catch (Exception e) {
IJError.print(e);
}
finishedWorking();
}
};
Bureaucrat burro = new Bureaucrat(worker, getProject());
burro.goHaveBreakfast();
return burro;
}
protected Bureaucrat importNextImage() {
Worker worker = new Worker("Import image") { /// all this verbosity is what happens when functions are not first class citizens. I could abstract it away by passing a string name "importImage" and invoking it with reflection, but that is an even bigger PAIN
public void run() {
startedWorking();
try {
Rectangle srcRect = canvas.getSrcRect();
int x = srcRect.x + srcRect.width / 2;// - imp.getWidth() / 2;
int y = srcRect.y + srcRect.height/ 2;// - imp.getHeight()/ 2;
Patch p = project.getLoader().importNextImage(project, x, y);
if (null == p) {
Utils.showMessage("Could not open next image.");
finishedWorking();
return;
}
layer.add(p); // will add it to the proper Displays
} catch (Exception e) {
IJError.print(e);
}
finishedWorking();
}
};
Bureaucrat burro = new Bureaucrat(worker, getProject());
burro.goHaveBreakfast();
return burro;
}
/** Make the given channel have the given alpha (transparency). */
public void setChannel(int c, float alpha) {
int a = (int)(255 * alpha);
int l = (c_alphas&0xff000000)>>24;
int r = (c_alphas&0xff0000)>>16;
int g = (c_alphas&0xff00)>>8;
int b = c_alphas&0xff;
switch (c) {
case Channel.MONO:
// all to the given alpha
c_alphas = (l<<24) + (r<<16) + (g<<8) + b; // parenthesis are NECESSARY
break;
case Channel.RED:
// modify only the red
c_alphas = (l<<24) + (a<<16) + (g<<8) + b;
break;
case Channel.GREEN:
c_alphas = (l<<24) + (r<<16) + (a<<8) + b;
break;
case Channel.BLUE:
c_alphas = (l<<24) + (r<<16) + (g<<8) + a;
break;
}
//Utils.log2("c_alphas: " + c_alphas);
//canvas.setUpdateGraphics(true);
canvas.repaint(true);
updateInDatabase("c_alphas");
}
/** Set the channel as active and the others as inactive. */
public void setActiveChannel(Channel channel) {
for (int i=0; i<4; i++) {
if (channel != channels[i]) channels[i].setActive(false);
else channel.setActive(true);
}
Utils.updateComponent(panel_channels);
transp_slider.setValue((int)(channel.getAlpha() * 100));
}
public int getDisplayChannelAlphas() { return c_alphas; }
// rename this method and the getDisplayChannelAlphas ! They sound the same!
public int getChannelAlphas() {
return ((int)(channels[0].getAlpha() * 255)<<24) + ((int)(channels[1].getAlpha() * 255)<<16) + ((int)(channels[2].getAlpha() * 255)<<8) + (int)(channels[3].getAlpha() * 255);
}
public int getChannelAlphasState() {
return ((channels[0].isSelected() ? 255 : 0)<<24)
+ ((channels[1].isSelected() ? 255 : 0)<<16)
+ ((channels[2].isSelected() ? 255 : 0)<<8)
+ (channels[3].isSelected() ? 255 : 0);
}
/** Show the layer in the front Display, or in a new Display if the front Display is showing a layer from a different LayerSet. */
static public void showFront(final Layer layer) {
Display display = front;
if (null == display || display.layer.getParent() != layer.getParent()) {
display = new Display(layer.getProject(), layer, null); // gets set to front
}
}
/** Show the given Displayable centered and selected. If select is false, the selection is cleared. */
static public void showCentered(Layer layer, Displayable displ, boolean select, boolean shift_down) {
// see if the given layer belongs to the layer set being displayed
Display display = front; // to ensure thread consistency to some extent
if (null == display || display.layer.getParent() != layer.getParent()) {
display = new Display(layer.getProject(), layer, displ); // gets set to front
} else if (display.layer != layer) {
display.setLayer(layer);
}
if (select) {
if (!shift_down) display.selection.clear();
display.selection.add(displ);
} else {
display.selection.clear();
}
display.showCentered(displ);
}
private final void showCentered(final Displayable displ) {
if (null == displ) return;
SwingUtilities.invokeLater(new Runnable() { public void run() {
displ.setVisible(true);
Rectangle box = displ.getBoundingBox();
if (0 == box.width || 0 == box.height) {
box.width = (int)layer.getLayerWidth();
box.height = (int)layer.getLayerHeight();
}
canvas.showCentered(box);
scrollToShow(displ);
if (displ instanceof ZDisplayable) {
// scroll to first layer that has a point
ZDisplayable zd = (ZDisplayable)displ;
setLayer(zd.getFirstLayer());
}
}});
}
/** Listen to interesting updates, such as the ColorPicker and updates to Patch objects. */
public void imageUpdated(ImagePlus updated) {
// detect ColorPicker WARNING this will work even if the Display is not the window immediately active under the color picker.
if (this == front && updated instanceof ij.plugin.ColorPicker) {
if (null != active && project.isInputEnabled()) {
Color color = Toolbar.getForegroundColor();
for (Iterator it = selection.getSelected().iterator(); it.hasNext(); ) {
Displayable displ = (Displayable)it.next();
displ.setColor(color);
}
}
return;
}
// $%#@!! LUT changes don't set the image as changed
//if (updated instanceof PatchStack) {
// updated.changes = 1
//}
//Utils.log2("imageUpdated: " + updated + " " + updated.getClass());
/* // never gets called (?)
// the above is overkill. Instead:
if (updated instanceof PatchStack) {
Patch p = ((PatchStack)updated).getCurrentPatch();
ImageProcessor ip = updated.getProcessor();
p.setMinAndMax(ip.getMin(), ip.getMax());
Utils.log2("setting min and max: " + ip.getMin() + ", " + ip.getMax());
project.getLoader().decacheAWT(p.getId()); // including level 0, which will be editable
// on repaint, it will be recreated
//((PatchStack)updated).decacheAll(); // so that it will repaint with a newly created image
}
*/
// detect LUT changes: DONE at PatchStack, which is the active (virtual) image
//Utils.log2("calling decache for " + updated);
//getProject().getLoader().decache(updated);
}
public void imageClosed(ImagePlus imp) {}
public void imageOpened(ImagePlus imp) {}
/** Release memory captured by the offscreen images */
static public void flushAll() {
for (Display d : al_displays) {
d.canvas.flush();
}
//System.gc();
Thread.yield();
}
/** Can be null. */
static public Display getFront() {
return front;
}
static public void setCursorToAll(final Cursor c) {
for (Display d : al_displays) {
d.frame.setCursor(c);
}
}
protected void setCursor(Cursor c) {
frame.setCursor(c);
}
/** Used by the Displayable to update the visibility checkbox in other Displays. */
static protected void updateVisibilityCheckbox(final Layer layer, final Displayable displ, final Display calling_display) {
//LOCKS ALL //SwingUtilities.invokeLater(new Runnable() { public void run() {
for (Display d : al_displays) {
if (d == calling_display) continue;
if (d.layer.contains(displ) || (displ instanceof ZDisplayable && d.layer.getParent().contains((ZDisplayable)displ))) {
DisplayablePanel dp = d.ht_panels.get(displ);
if (null != dp) dp.updateVisibilityCheckbox();
}
}
//}});
}
protected boolean isActiveWindow() {
return frame.isActive();
}
/** Toggle user input; pan and zoom are always enabled though.*/
static public void setReceivesInput(final Project project, final boolean b) {
for (Display d : al_displays) {
if (d.project == project) d.canvas.setReceivesInput(b);
}
}
/** Export the DTD that defines this object. */
static public void exportDTD(StringBuffer sb_header, HashSet hs, String indent) {
if (hs.contains("t2_display")) return; // TODO to avoid collisions the type shoud be in a namespace such as tm2:display
hs.add("t2_display");
sb_header.append(indent).append("<!ELEMENT t2_display EMPTY>\n")
.append(indent).append("<!ATTLIST t2_display id NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display layer_id NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display x NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display y NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display magnification NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display srcrect_x NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display srcrect_y NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display srcrect_width NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display srcrect_height NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display scroll_step NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display c_alphas NMTOKEN #REQUIRED>\n")
.append(indent).append("<!ATTLIST t2_display c_alphas_state NMTOKEN #REQUIRED>\n")
;
}
/** Export all displays of the given project as XML entries. */
static public void exportXML(final Project project, final Writer writer, final String indent, final Object any) throws Exception {
final StringBuffer sb_body = new StringBuffer();
final String in = indent + "\t";
for (Display d : al_displays) {
if (d.project != project) continue;
final Rectangle r = d.frame.getBounds();
final Rectangle srcRect = d.canvas.getSrcRect();
final double magnification = d.canvas.getMagnification();
sb_body.append(indent).append("<t2_display id=\"").append(d.id).append("\"\n")
.append(in).append("layer_id=\"").append(d.layer.getId()).append("\"\n")
.append(in).append("c_alphas=\"").append(d.c_alphas).append("\"\n")
.append(in).append("c_alphas_state=\"").append(d.getChannelAlphasState()).append("\"\n")
.append(in).append("x=\"").append(r.x).append("\"\n")
.append(in).append("y=\"").append(r.y).append("\"\n")
.append(in).append("magnification=\"").append(magnification).append("\"\n")
.append(in).append("srcrect_x=\"").append(srcRect.x).append("\"\n")
.append(in).append("srcrect_y=\"").append(srcRect.y).append("\"\n")
.append(in).append("srcrect_width=\"").append(srcRect.width).append("\"\n")
.append(in).append("srcrect_height=\"").append(srcRect.height).append("\"\n")
.append(in).append("scroll_step=\"").append(d.scroll_step).append("\"\n")
;
sb_body.append(indent).append("/>\n");
}
writer.write(sb_body.toString());
}
static public void toolChanged(final String tool_name) {
Utils.log2("tool name: " + tool_name);
if (!tool_name.equals("ALIGN")) {
for (Display d : al_displays) {
d.layer.getParent().cancelAlign();
}
}
}
static public void toolChanged(final int tool) {
//Utils.log2("int tool is " + tool);
if (ProjectToolbar.PEN == tool) {
// erase bounding boxes
for (Display d : al_displays) {
if (null != d.active) d.repaint(d.layer, d.selection.getBox(), 2);
}
}
if (null != front) {
WindowManager.setTempCurrentImage(front.canvas.getFakeImagePlus());
}
}
public Selection getSelection() {
return selection;
}
public boolean isSelected(Displayable d) {
return selection.contains(d);
}
static public void updateSelection() {
Display.updateSelection(null);
}
static public void updateSelection(final Display calling) {
final HashSet hs = new HashSet();
for (Display d : al_displays) {
if (hs.contains(d.layer)) continue;
hs.add(d.layer);
if (null == d || null == d.selection) {
Utils.log2("d is : "+ d + " d.selection is " + d.selection);
} else {
d.selection.update(); // recomputes box
}
if (d != calling) { // TODO this is so dirty!
if (d.selection.getNLinked() > 1) d.canvas.setUpdateGraphics(true); // this is overkill anyway
d.canvas.repaint(d.selection.getLinkedBox(), Selection.PADDING);
d.navigator.repaint(true); // everything
}
}
}
static public void clearSelection(final Layer layer) {
for (Display d : al_displays) {
if (d.layer == layer) d.selection.clear();
}
}
private void setTempCurrentImage() {
WindowManager.setTempCurrentImage(canvas.getFakeImagePlus());
}
/** Check if any display will paint the given Displayable at the given magnification. */
static public boolean willPaint(final Displayable displ, final double magnification) {
Rectangle box = null; ;
for (Display d : al_displays) {
if (d.canvas.getMagnification() != magnification) {
continue;
}
if (null == box) box = displ.getBoundingBox(null);
if (d.canvas.getSrcRect().intersects(box)) {
return true;
}
}
return false;
}
public void hideDeselected(boolean not_images) {
// hide deselected
ArrayList all = layer.getParent().getZDisplayables();
all.addAll(layer.getDisplayables());
all.removeAll(selection.getSelected());
if (not_images) all.removeAll(layer.getDisplayables(Patch.class));
for (Displayable d : (ArrayList<Displayable>)all) {
if (d.isVisible()) d.setVisible(false);
}
Display.update(layer);
}
/** Cleanup internal lists that may contain the given Displayable. */
static public void flush(final Displayable displ) {
for (Display d : al_displays) {
d.selection.removeFromPrev(displ);
}
}
public void resizeCanvas() {
GenericDialog gd = new GenericDialog("Resize LayerSet");
gd.addNumericField("new width: ", layer.getLayerWidth(), 3);
gd.addNumericField("new height: ",layer.getLayerHeight(),3);
gd.addChoice("Anchor: ", LayerSet.ANCHORS, LayerSet.ANCHORS[7]);
gd.showDialog();
if (gd.wasCanceled()) return;
double new_width = gd.getNextNumber();
double new_height =gd.getNextNumber();
layer.getParent().setDimensions(new_width, new_height, gd.getNextChoiceIndex()); // will complain and prevent cropping existing Displayable objects
}
}
| false | true | public void actionPerformed(final ActionEvent ae) {
dispatcher.exec(new Runnable() { public void run() {
String command = ae.getActionCommand();
if (command.startsWith("Job")) {
if (Utils.checkYN("Really cancel job?")) {
project.getLoader().quitJob(command);
repairGUI();
}
return;
} else if (command.equals("Move to top")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.TOP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move up")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.UP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move down")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.DOWN, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move to bottom")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.BOTTOM, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Duplicate, link and send to next layer")) {
if (null == active || !(active instanceof Profile)) return;
Layer next_layer = layer.getParent().next(layer);
if (layer.equals(next_layer)) return; // no next layer! The menu item will be disabled anyway
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 1, next_layer);
if (null == profile) return;
active.link(profile);
next_layer.add(profile);
Thread thread = new SetLayerThread(Display.this, next_layer);//setLayer(next_layer);
try { thread.join(); } catch (InterruptedException ie) {} // wait until finished!
selection.add(profile); //setActive(profile);
} else if (command.equals("Duplicate, link and send to previous layer")) {
if (null == active || !(active instanceof Profile)) return;
Layer previous_layer = layer.getParent().previous(layer);
if (layer.equals(previous_layer)) return; // no previous layer!
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 0, previous_layer);
if (null == profile) return;
active.link(profile);
previous_layer.add(profile);
Thread thread = new SetLayerThread(Display.this, previous_layer);//setLayer(previous_layer);
try { thread.join(); } catch (InterruptedException ie) {} // wait until finished!
selection.add(profile); //setActive(profile);
} else if (command.equals("Duplicate, link and send to...")) {
// fix non-scrolling popup menu
GenericDialog gd = new GenericDialog("Send to");
gd.addMessage("Duplicate, link and send to...");
String[] sl = new String[layer.getParent().size()];
int next = 0;
for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) {
sl[next++] = project.findLayerThing(it.next()).toString();
}
gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex());
if (layer == la) {
Utils.showMessage("Can't duplicate, link and send to the same layer.");
return;
}
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 0, la);
if (null == profile) return;
active.link(profile);
la.add(profile);
Thread thread = new SetLayerThread(Display.this, la);//setLayer(la);
try { thread.join(); } catch (InterruptedException ie) {} // waint until finished!
selection.add(profile);
} else if (-1 != command.indexOf("z = ")) {
// this is an item from the "Duplicate, link and send to" menu of layer z's
Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1)));
Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__");
if (null == target_layer) return;
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 0, target_layer);
if (null == profile) return;
active.link(profile);
target_layer.add(profile);
Thread thread = new SetLayerThread(Display.this, target_layer);//setLayer(target_layer);
try { thread.join(); } catch (InterruptedException ie) {} // waint until finished!
selection.add(profile); // setActive(profile); // this is repainting only the active, not everything, because it cancels the repaint sent by the setLayer ! BUT NO, it should add up to the max box.
} else if (-1 != command.indexOf("z=")) {
// WARNING the indexOf is very similar to the previous one
// Send the linked group to the selected layer
int iz = command.indexOf("z=")+2;
Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2));
double lz = Double.parseDouble(command.substring(iz, command.indexOf(' ', iz+2)));
Layer target = layer.getParent().getLayer(lz);
HashSet hs = active.getLinkedGroup(new HashSet());
layer.getParent().move(hs, active.getLayer(), target);
} else if (command.equals("Unlink")) {
if (null == active || active instanceof Patch) return;
active.unlink();
updateSelection();//selection.update();
} else if (command.equals("Unlink from images")) {
if (null == active) return;
try {
active.unlinkAll(Patch.class);
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
} else if (command.equals("Unlink slices")) {
YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo.");
if (!yn.yesPressed()) return;
final ArrayList<Patch> pa = ((Patch)active).getStackPatches();
for (int i=pa.size()-1; i>0; i--) {
pa.get(i).unlink(pa.get(i-1));
}
} else if (command.equals("Send to next layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
active.unlinkAll(Patch.class);
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers
selection.moveDown();
repaint(layer.getParent(), box);
} else if (command.equals("Send to previous layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
active.unlinkAll(Patch.class);
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers
selection.moveUp();
repaint(layer.getParent(), box);
} else if (command.equals("Show centered")) {
if (active == null) return;
showCentered(active);
} else if (command.equals("Delete...")) {
/*
if (null != active) {
Displayable d = active;
selection.remove(d);
d.remove(true); // will repaint
}
*/
// remove all selected objects
selection.deleteAll();
} else if (command.equals("Color...")) {
IJ.doCommand("Color Picker...");
} else if (command.equals("Revert")) {
if (null == active || active.getClass() != Patch.class) return;
Patch p = (Patch)active;
if (!p.revert()) {
if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId());
else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId());
}
} else if (command.equals("Undo transforms")) {
if (canvas.isTransforming()) return;
if (!layer.getParent().canRedo()) {
// catch the current
layer.getParent().appendCurrent(selection.getTransformationsCopy());
}
layer.getParent().undoOneStep();
} else if (command.equals("Redo transforms")) {
if (canvas.isTransforming()) return;
layer.getParent().redoOneStep();
} else if (command.equals("Transform")) {
if (null == active) {
Utils.log2("Display \"Transform\": null active!");
return;
}
canvas.setTransforming(true);
} else if (command.equals("Apply transform")) {
if (null == active) return;
canvas.setTransforming(false);
} else if (command.equals("Cancel transform")) {
if (null == active) return;
canvas.cancelTransform();
} else if (command.equals("Specify transform...")) {
if (null == active) return;
selection.specify();
} else if (command.equals("Hide all but images")) {
ArrayList<Class> type = new ArrayList<Class>();
type.add(Patch.class);
selection.removeAll(layer.getParent().hideExcept(type, false));
Display.update(layer.getParent(), false);
} else if (command.equals("Unhide all")) {
layer.getParent().setAllVisible(false);
Display.update(layer.getParent(), false);
} else if (command.startsWith("Hide all ")) {
String type = command.substring(9, command.length() -1); // skip the ending plural 's'
type = type.substring(0, 1).toUpperCase() + type.substring(1);
selection.removeAll(layer.getParent().setVisible(type, false, true));
} else if (command.startsWith("Unhide all ")) {
String type = command.substring(11, command.length() -1); // skip the ending plural 's'
type = type.substring(0, 1).toUpperCase() + type.substring(1);
layer.getParent().setVisible(type, true, true);
} else if (command.equals("Hide deselected")) {
hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers()));
} else if (command.equals("Hide selected")) {
selection.setVisible(false); // TODO should deselect them too? I don't think so.
} else if (command.equals("Resize canvas/LayerSet...")) {
resizeCanvas();
} else if (command.equals("Autoresize canvas/LayerSet")) {
layer.getParent().setMinimumDimensions();
} else if (command.equals("Import image")) {
importImage();
} else if (command.equals("Import next image")) {
importNextImage();
} else if (command.equals("Import stack...")) {
project.getLoader().importStack(layer, null, true);
} else if (command.equals("Import grid...")) {
project.getLoader().importGrid(layer);
} else if (command.equals("Import sequence as grid...")) {
project.getLoader().importSequenceAsGrid(layer);
} else if (command.equals("Import from text file...")) {
project.getLoader().importImages(layer);
} else if (command.equals("Make flat image...")) {
// if there's a ROI, just use that as cropping rectangle
Rectangle srcRect = null;
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null != roi) {
srcRect = roi.getBounds();
} else {
// otherwise, whatever is visible
//srcRect = canvas.getSrcRect();
// The above is confusing. That is what ROIs are for. So paint all:
srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight()));
}
double scale = 1.0;
final String[] types = new String[]{"8-bit grayscale", "RGB"};
int the_type = ImagePlus.GRAY8;
final GenericDialog gd = new GenericDialog("Choose", frame);
gd.addNumericField("Scale: ", 1.0, 2);
gd.addChoice("Type: ", types, types[0]);
if (layer.getParent().size() > 1) {
/*
String[] layers = new String[layer.getParent().size()];
int i = 0;
for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) {
layers[i] = layer.getProject().findLayerThing((Layer)it.next()).toString();
i++;
}
int i_layer = layer.getParent().indexOf(layer);
gd.addChoice("Start: ", layers, layers[i_layer]);
gd.addChoice("End: ", layers, layers[i_layer]);
*/
Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros
gd.addCheckbox("Include non-empty layers only", true);
}
gd.addCheckbox("Best quality", false);
gd.addMessage("");
gd.addCheckbox("Save to file", false);
gd.addCheckbox("Save for web", false);
gd.showDialog();
if (gd.wasCanceled()) return;
scale = gd.getNextNumber();
the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB);
if (Double.isNaN(scale) || scale <= 0.0) {
Utils.showMessage("Invalid scale.");
return;
}
Layer[] layer_array = null;
boolean non_empty_only = false;
if (layer.getParent().size() > 1) {
non_empty_only = gd.getNextBoolean();
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
ArrayList al = new ArrayList();
ArrayList al_zd = layer.getParent().getZDisplayables();
ZDisplayable[] zd = new ZDisplayable[al_zd.size()];
al_zd.toArray(zd);
for (int i=i_start, j=0; i <= i_end; i++, j++) {
Layer la = layer.getParent().getLayer(i);
if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet
}
if (0 == al.size()) {
Utils.showMessage("All layers are empty!");
return;
}
layer_array = new Layer[al.size()];
al.toArray(layer_array);
} else {
layer_array = new Layer[]{Display.this.layer};
}
final boolean quality = gd.getNextBoolean();
final boolean save_to_file = gd.getNextBoolean();
final boolean save_for_web = gd.getNextBoolean();
// in its own thread
if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type);
else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality);
} else if (command.equals("Lock")) {
selection.setLocked(true);
} else if (command.equals("Unlock")) {
selection.setLocked(false);
} else if (command.equals("Properties...")) {
active.adjustProperties();
updateSelection();
} else if (command.equals("Cancel alignment")) {
layer.getParent().cancelAlign();
} else if (command.equals("Align with landmarks")) {
layer.getParent().applyAlign(false);
} else if (command.equals("Align and register")) {
layer.getParent().applyAlign(true);
} else if (command.equals("Align using profiles")) {
if (!selection.contains(Profile.class)) {
Utils.showMessage("No profiles are selected.");
return;
}
// ask for range of layers
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer la_start = layer.getParent().getLayer(gd.getNextChoiceIndex());
Layer la_end = layer.getParent().getLayer(gd.getNextChoiceIndex());
if (la_start == la_end) {
Utils.showMessage("Need at least two layers.");
return;
}
if (selection.isLocked()) {
Utils.showMessage("There are locked objects.");
return;
}
layer.getParent().startAlign(Display.this);
layer.getParent().applyAlign(la_start, la_end, selection);
} else if (command.equals("Align stack slices")) {
if (getActive() instanceof Patch) {
final Patch slice = (Patch)getActive();
if (slice.isStack()) {
// check linked group
final HashSet hs = slice.getLinkedGroup(new HashSet());
for (Iterator it = hs.iterator(); it.hasNext(); ) {
if (it.next().getClass() != Patch.class) {
Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that
return;
}
}
slice.getLayer().getParent().createUndoStep(); // full
Registration.registerStackSlices((Patch)getActive()); // will repaint
} else {
Utils.log("Align stack slices: selected image is not part of a stack.");
}
}
} else if (command.equals("Align layers (layer-wise)")) {
Registration.registerLayers(layer, Registration.LAYER_SIFT);
} else if (command.equals("Align layers (tile-wise global minimization)")) {
Registration.registerLayers(layer, Registration.GLOBAL_MINIMIZATION);
} else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects.
GenericDialog gd = new GenericDialog("Properties", Display.this.frame);
//gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0);
gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step);
gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]);
gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality());
Loader lo = getProject().getLoader();
boolean using_mipmaps = lo.isMipMapsEnabled();
gd.addCheckbox("enable_mipmaps", using_mipmaps);
String preprocessor = project.getLoader().getPreprocessor();
gd.addStringField("image_preprocessor: ", null == preprocessor ? "" : preprocessor);
gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled());
double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight();
gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsDimension());
// --------
gd.showDialog();
if (gd.wasCanceled()) return;
// --------
int sc = (int) gd.getNextNumber();
if (sc < 1) sc = 1;
Display.this.scroll_step = sc;
updateInDatabase("scroll_step");
//
layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex());
layer.getParent().setSnapshotsQuality(gd.getNextBoolean());
//
boolean generate_mipmaps = gd.getNextBoolean();
if (using_mipmaps && generate_mipmaps) {
// nothing changed
} else {
if (using_mipmaps) { // and !generate_mipmaps
lo.flushMipMaps(true);
} else {
// not using mipmaps before, and true == generate_mipmaps
lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class));
}
}
//
final String prepro = gd.getNextString();
if (!project.getLoader().setPreprocessor(prepro.trim())) {
Utils.showMessage("Could NOT set the preprocessor to " + prepro);
}
//
layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean());
layer.getParent().setPixelsDimension((int)gd.getNextNumber());
} else if (command.equals("Search...")) {
new Search();
} else if (command.equals("Select all")) {
selection.selectAll();
repaint(Display.this.layer, selection.getBox(), 0);
} else if (command.equals("Select none")) {
Rectangle box = selection.getBox();
selection.clear();
repaint(Display.this.layer, box, 0);
} else if (command.equals("Restore selection")) {
selection.restore();
} else if (command.equals("Select under ROI")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return;
selection.selectAll(roi, true);
} else if (command.equals("Merge")) {
ArrayList al_sel = selection.getSelected();
// put active at the beginning, to work as the base on which other's will get merged
al_sel.remove(Display.this.active);
al_sel.add(0, Display.this.active);
AreaList ali = AreaList.merge(al_sel);
if (null != ali) {
// remove all but the first from the selection
for (int i=1; i<al_sel.size(); i++) {
Object ob = al_sel.get(i);
if (ob.getClass() == AreaList.class) {
selection.remove((Displayable)ob);
}
}
selection.updateTransform(ali);
repaint(ali.getLayerSet(), ali, 0);
}
} else if (command.equals("Identify...")) {
// for pipes only for now
if (!(active instanceof Pipe)) return;
ini.trakem2.vector.Compare.findSimilar((Pipe)active);
} else if (command.equals("Identify with axes...")) {
if (!(active instanceof Pipe)) return;
if (Project.getProjects().size() < 2) {
Utils.showMessage("You need at least two projects open:\n-A reference project\n-The current project with the pipe to identify");
return;
}
ini.trakem2.vector.Compare.findSimilarWithAxes((Pipe)active);
} else if (command.equals("View orthoslices")) {
if (!(active instanceof Patch)) return;
Display3D.showOrthoslices(((Patch)active));
} else if (command.equals("View volume")) {
if (!(active instanceof Patch)) return;
Display3D.showVolume(((Patch)active));
} else if (command.equals("Show in 3D")) {
for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) {
ZDisplayable zd = (ZDisplayable)it.next();
Display3D.show(zd.getProject().findProjectThing(zd));
}
// handle profile lists ...
HashSet hs = new HashSet();
for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) {
Displayable d = (Displayable)it.next();
ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent();
if (!hs.contains(profile_list)) {
Display3D.show(profile_list);
hs.add(profile_list);
}
}
} else if (command.equals("Snap")) {
if (!(active instanceof Patch)) return;
StitchingTEM.snap(getActive(), Display.this);
} else if (command.equals("Montage")) {
if (!(active instanceof Patch)) {
Utils.showMessage("Please select only images.");
return;
}
for (Object ob : selection.getSelected()) {
if (!(ob instanceof Patch)) {
Utils.showMessage("Please select only images.\nCurrently, a " + Project.getName(ob.getClass()) + " is also selected.");
return;
}
}
HashSet hs = new HashSet();
hs.addAll(selection.getSelected(Patch.class));
// make an undo step!
layer.getParent().addUndoStep(selection.getAffected());
Registration.registerTilesSIFT(hs, (Patch)active, null, false);
} else if (command.equals("Link images...")) {
GenericDialog gd = new GenericDialog("Options");
gd.addMessage("Linking images to images (within their own layer only):");
String[] options = {"all images to all images", "each image with any other overlapping image"};
gd.addChoice("Link: ", options, options[1]);
String[] options2 = {"selected images only", "all images in this layer", "all images in all layers"};
gd.addChoice("Apply to: ", options2, options2[0]);
gd.showDialog();
if (gd.wasCanceled()) return;
boolean overlapping_only = 1 == gd.getNextChoiceIndex();
switch (gd.getNextChoiceIndex()) {
case 0:
Patch.crosslink(selection.getSelected(Patch.class), overlapping_only);
break;
case 1:
Patch.crosslink(layer.getDisplayables(Patch.class), overlapping_only);
break;
case 2:
for (Layer la : layer.getParent().getLayers()) {
Patch.crosslink(la.getDisplayables(Patch.class), overlapping_only);
}
break;
}
} else if (command.equals("Homogenize contrast (selected images)")) {
ArrayList al = selection.getSelected(Patch.class);
if (al.size() < 2) return;
getProject().getLoader().homogenizeContrast(al);
} else if (command.equals("Homogenize contrast layer-wise...")) {
// ask for range of layers
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
java.util.List list = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
Layer[] la = new Layer[list.size()];
list.toArray(la);
project.getLoader().homogenizeContrast(la);
} else if (command.equals("Set Min and Max...")) {
final GenericDialog gd = new GenericDialog("Choices");
gd.addMessage("Either process all images of all layers\nwithin the selected range,\nor check the box for using selected images only.");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.addCheckbox("use_selected_images_only", false);
gd.addMessage("-------");
gd.addNumericField("min: ", 0, 2);
gd.addNumericField("max: ", 255, 2);
gd.addCheckbox("drift_mean", true);
gd.addMessage("Or let each image find its optimal:");
gd.addCheckbox("independent", false);
gd.showDialog();
if (gd.wasCanceled()) return;
boolean use_selected_images = gd.getNextBoolean();
double min = gd.getNextNumber();
double max = gd.getNextNumber();
if (Double.isNaN(min) || Double.isNaN(max) || min < 0 || max < min) {
Utils.showMessage("Improper min and max values.");
return;
}
boolean drift_hist_peak = gd.getNextBoolean();
boolean independent = gd.getNextBoolean();
Utils.log2("Di Using: " + min + ", " + max + ", " + drift_hist_peak + " use_selected_images: " + use_selected_images);
if (use_selected_images) {
ArrayList al_images = selection.getSelected(Patch.class);
if (al_images.size() < 1) {
Utils.log2("You need at least 2 images selected.");
return;
}
if (independent) {
project.getLoader().optimizeContrast(al_images);
} else {
project.getLoader().homogenizeContrast(al_images, min, max, drift_hist_peak);
}
} else {
java.util.List list = list = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
Layer[] la = new Layer[list.size()];
list.toArray(la);
if (independent) {
ArrayList al_images = new ArrayList();
for (int i=0; i<la.length; i++) {
al_images.addAll(la[i].getDisplayables(Patch.class));
}
project.getLoader().optimizeContrast(al_images);
} else {
project.getLoader().homogenizeContrast(la, min, max, drift_hist_peak);
}
}
} else if (command.equals("Create subproject")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return; // the menu item is not active unless there is a ROI
Layer first, last;
if (1 == layer.getParent().size()) {
first = last = layer;
} else {
GenericDialog gd = new GenericDialog("Choose layer range");
Utils.addLayerRangeChoices(layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
first = layer.getParent().getLayer(gd.getNextChoiceIndex());
last = layer.getParent().getLayer(gd.getNextChoiceIndex());
Utils.log2("first, last: " + first + ", " + last);
}
Project sub = getProject().createSubproject(roi.getBounds(), first, last);
final LayerSet subls = sub.getRootLayerSet();
final Display d = new Display(sub, subls.getLayer(0));
SwingUtilities.invokeLater(new Runnable() { public void run() {
d.canvas.showCentered(new Rectangle(0, 0, (int)subls.getLayerWidth(), (int)subls.getLayerHeight()));
}});
} else if (command.equals("Export arealists as labels")) {
GenericDialog gd = new GenericDialog("Export labels");
gd.addSlider("Scale: ", 1, 100, 100);
final String[] options = {"All area list", "Selected area lists"};
gd.addChoice("Export: ", options, options[0]);
Utils.addLayerRangeChoices(layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final float scale = (float)(gd.getNextNumber() / 100);
java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class);
if (null == al) {
Utils.log("No area lists found to export.");
return;
}
if (al.size() > 255) {
YesNoCancelDialog yn = new YesNoCancelDialog(frame, "WARNING", "Found more than 255 area lists to export:\nExport only the first 255?");
if (yn.cancelPressed()) return;
if (yn.yesPressed()) al = al.subList(0, 255); // only 255 total: the 0 is left for background
}
int first = gd.getNextChoiceIndex();
int last = gd.getNextChoiceIndex();
AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last);
} else if (command.equals("Project properties...")) {
project.adjustProperties();
} else if (command.equals("Release memory...")) {
new Bureaucrat(new Worker("Releasing memory") {
public void run() {
startedWorking();
try {
GenericDialog gd = new GenericDialog("Release Memory");
int max = (int)(IJ.maxMemory() / 1000000);
gd.addSlider("Megabytes: ", 0, max, max/2);
gd.showDialog();
if (!gd.wasCanceled()) {
int n_mb = (int)gd.getNextNumber();
project.getLoader().releaseToFit((long)n_mb*1000000);
}
} catch (Throwable e) {
IJError.print(e);
} finally {
finishedWorking();
}
}
}, project).goHaveBreakfast();
} else {
Utils.log2("Display: don't know what to do with command " + command);
}
}});
| public void actionPerformed(final ActionEvent ae) {
dispatcher.exec(new Runnable() { public void run() {
String command = ae.getActionCommand();
if (command.startsWith("Job")) {
if (Utils.checkYN("Really cancel job?")) {
project.getLoader().quitJob(command);
repairGUI();
}
return;
} else if (command.equals("Move to top")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.TOP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move up")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.UP, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move down")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.DOWN, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Move to bottom")) {
if (null == active) return;
canvas.setUpdateGraphics(true);
layer.getParent().move(LayerSet.BOTTOM, active);
Display.repaint(layer.getParent(), active, 5);
//Display.updatePanelIndex(layer, active);
} else if (command.equals("Duplicate, link and send to next layer")) {
if (null == active || !(active instanceof Profile)) return;
Layer next_layer = layer.getParent().next(layer);
if (layer.equals(next_layer)) return; // no next layer! The menu item will be disabled anyway
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 1, next_layer);
if (null == profile) return;
active.link(profile);
next_layer.add(profile);
Thread thread = new SetLayerThread(Display.this, next_layer);//setLayer(next_layer);
try { thread.join(); } catch (InterruptedException ie) {} // wait until finished!
selection.add(profile); //setActive(profile);
} else if (command.equals("Duplicate, link and send to previous layer")) {
if (null == active || !(active instanceof Profile)) return;
Layer previous_layer = layer.getParent().previous(layer);
if (layer.equals(previous_layer)) return; // no previous layer!
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 0, previous_layer);
if (null == profile) return;
active.link(profile);
previous_layer.add(profile);
Thread thread = new SetLayerThread(Display.this, previous_layer);//setLayer(previous_layer);
try { thread.join(); } catch (InterruptedException ie) {} // wait until finished!
selection.add(profile); //setActive(profile);
} else if (command.equals("Duplicate, link and send to...")) {
// fix non-scrolling popup menu
GenericDialog gd = new GenericDialog("Send to");
gd.addMessage("Duplicate, link and send to...");
String[] sl = new String[layer.getParent().size()];
int next = 0;
for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) {
sl[next++] = project.findLayerThing(it.next()).toString();
}
gd.addChoice("Layer: ", sl, sl[layer.getParent().indexOf(layer)]);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer la = layer.getParent().getLayer(gd.getNextChoiceIndex());
if (layer == la) {
Utils.showMessage("Can't duplicate, link and send to the same layer.");
return;
}
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 0, la);
if (null == profile) return;
active.link(profile);
la.add(profile);
Thread thread = new SetLayerThread(Display.this, la);//setLayer(la);
try { thread.join(); } catch (InterruptedException ie) {} // waint until finished!
selection.add(profile);
} else if (-1 != command.indexOf("z = ")) {
// this is an item from the "Duplicate, link and send to" menu of layer z's
Layer target_layer = layer.getParent().getLayer(Double.parseDouble(command.substring(command.lastIndexOf(' ') +1)));
Utils.log2("layer: __" +command.substring(command.lastIndexOf(' ') +1) + "__");
if (null == target_layer) return;
Profile profile = project.getProjectTree().duplicateChild((Profile)active, 0, target_layer);
if (null == profile) return;
active.link(profile);
target_layer.add(profile);
Thread thread = new SetLayerThread(Display.this, target_layer);//setLayer(target_layer);
try { thread.join(); } catch (InterruptedException ie) {} // waint until finished!
selection.add(profile); // setActive(profile); // this is repainting only the active, not everything, because it cancels the repaint sent by the setLayer ! BUT NO, it should add up to the max box.
} else if (-1 != command.indexOf("z=")) {
// WARNING the indexOf is very similar to the previous one
// Send the linked group to the selected layer
int iz = command.indexOf("z=")+2;
Utils.log2("iz=" + iz + " other: " + command.indexOf(' ', iz+2));
int end = command.indexOf(' ', iz);
if (-1 == end) end = command.length();
double lz = Double.parseDouble(command.substring(iz, end));
Layer target = layer.getParent().getLayer(lz);
HashSet hs = active.getLinkedGroup(new HashSet());
layer.getParent().move(hs, active.getLayer(), target);
} else if (command.equals("Unlink")) {
if (null == active || active instanceof Patch) return;
active.unlink();
updateSelection();//selection.update();
} else if (command.equals("Unlink from images")) {
if (null == active) return;
try {
for (Displayable displ: selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
} else if (command.equals("Unlink slices")) {
YesNoCancelDialog yn = new YesNoCancelDialog(frame, "Attention", "Really unlink all slices from each other?\nThere is no undo.");
if (!yn.yesPressed()) return;
final ArrayList<Patch> pa = ((Patch)active).getStackPatches();
for (int i=pa.size()-1; i>0; i--) {
pa.get(i).unlink(pa.get(i-1));
}
} else if (command.equals("Send to next layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
for (Displayable displ : selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveDown(layer, active); // will repaint whatever appropriate layers
selection.moveDown();
repaint(layer.getParent(), box);
} else if (command.equals("Send to previous layer")) {
Rectangle box = selection.getBox();
try {
// unlink Patch instances
for (Displayable displ : selection.getSelected()) {
displ.unlinkAll(Patch.class);
}
updateSelection();//selection.update();
} catch (Exception e) { IJError.print(e); }
//layer.getParent().moveUp(layer, active); // will repaint whatever appropriate layers
selection.moveUp();
repaint(layer.getParent(), box);
} else if (command.equals("Show centered")) {
if (active == null) return;
showCentered(active);
} else if (command.equals("Delete...")) {
/*
if (null != active) {
Displayable d = active;
selection.remove(d);
d.remove(true); // will repaint
}
*/
// remove all selected objects
selection.deleteAll();
} else if (command.equals("Color...")) {
IJ.doCommand("Color Picker...");
} else if (command.equals("Revert")) {
if (null == active || active.getClass() != Patch.class) return;
Patch p = (Patch)active;
if (!p.revert()) {
if (null == p.getOriginalPath()) Utils.log("No editions to save for patch " + p.getTitle() + " #" + p.getId());
else Utils.log("Could not revert Patch " + p.getTitle() + " #" + p.getId());
}
} else if (command.equals("Undo transforms")) {
if (canvas.isTransforming()) return;
if (!layer.getParent().canRedo()) {
// catch the current
layer.getParent().appendCurrent(selection.getTransformationsCopy());
}
layer.getParent().undoOneStep();
} else if (command.equals("Redo transforms")) {
if (canvas.isTransforming()) return;
layer.getParent().redoOneStep();
} else if (command.equals("Transform")) {
if (null == active) {
Utils.log2("Display \"Transform\": null active!");
return;
}
canvas.setTransforming(true);
} else if (command.equals("Apply transform")) {
if (null == active) return;
canvas.setTransforming(false);
} else if (command.equals("Cancel transform")) {
if (null == active) return;
canvas.cancelTransform();
} else if (command.equals("Specify transform...")) {
if (null == active) return;
selection.specify();
} else if (command.equals("Hide all but images")) {
ArrayList<Class> type = new ArrayList<Class>();
type.add(Patch.class);
selection.removeAll(layer.getParent().hideExcept(type, false));
Display.update(layer.getParent(), false);
} else if (command.equals("Unhide all")) {
layer.getParent().setAllVisible(false);
Display.update(layer.getParent(), false);
} else if (command.startsWith("Hide all ")) {
String type = command.substring(9, command.length() -1); // skip the ending plural 's'
type = type.substring(0, 1).toUpperCase() + type.substring(1);
selection.removeAll(layer.getParent().setVisible(type, false, true));
} else if (command.startsWith("Unhide all ")) {
String type = command.substring(11, command.length() -1); // skip the ending plural 's'
type = type.substring(0, 1).toUpperCase() + type.substring(1);
layer.getParent().setVisible(type, true, true);
} else if (command.equals("Hide deselected")) {
hideDeselected(0 != (ActionEvent.ALT_MASK & ae.getModifiers()));
} else if (command.equals("Hide selected")) {
selection.setVisible(false); // TODO should deselect them too? I don't think so.
} else if (command.equals("Resize canvas/LayerSet...")) {
resizeCanvas();
} else if (command.equals("Autoresize canvas/LayerSet")) {
layer.getParent().setMinimumDimensions();
} else if (command.equals("Import image")) {
importImage();
} else if (command.equals("Import next image")) {
importNextImage();
} else if (command.equals("Import stack...")) {
project.getLoader().importStack(layer, null, true);
} else if (command.equals("Import grid...")) {
project.getLoader().importGrid(layer);
} else if (command.equals("Import sequence as grid...")) {
project.getLoader().importSequenceAsGrid(layer);
} else if (command.equals("Import from text file...")) {
project.getLoader().importImages(layer);
} else if (command.equals("Make flat image...")) {
// if there's a ROI, just use that as cropping rectangle
Rectangle srcRect = null;
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null != roi) {
srcRect = roi.getBounds();
} else {
// otherwise, whatever is visible
//srcRect = canvas.getSrcRect();
// The above is confusing. That is what ROIs are for. So paint all:
srcRect = new Rectangle(0, 0, (int)Math.ceil(layer.getParent().getLayerWidth()), (int)Math.ceil(layer.getParent().getLayerHeight()));
}
double scale = 1.0;
final String[] types = new String[]{"8-bit grayscale", "RGB"};
int the_type = ImagePlus.GRAY8;
final GenericDialog gd = new GenericDialog("Choose", frame);
gd.addNumericField("Scale: ", 1.0, 2);
gd.addChoice("Type: ", types, types[0]);
if (layer.getParent().size() > 1) {
/*
String[] layers = new String[layer.getParent().size()];
int i = 0;
for (Iterator it = layer.getParent().getLayers().iterator(); it.hasNext(); ) {
layers[i] = layer.getProject().findLayerThing((Layer)it.next()).toString();
i++;
}
int i_layer = layer.getParent().indexOf(layer);
gd.addChoice("Start: ", layers, layers[i_layer]);
gd.addChoice("End: ", layers, layers[i_layer]);
*/
Utils.addLayerRangeChoices(Display.this.layer, gd); /// $#%! where are my lisp macros
gd.addCheckbox("Include non-empty layers only", true);
}
gd.addCheckbox("Best quality", false);
gd.addMessage("");
gd.addCheckbox("Save to file", false);
gd.addCheckbox("Save for web", false);
gd.showDialog();
if (gd.wasCanceled()) return;
scale = gd.getNextNumber();
the_type = (0 == gd.getNextChoiceIndex() ? ImagePlus.GRAY8 : ImagePlus.COLOR_RGB);
if (Double.isNaN(scale) || scale <= 0.0) {
Utils.showMessage("Invalid scale.");
return;
}
Layer[] layer_array = null;
boolean non_empty_only = false;
if (layer.getParent().size() > 1) {
non_empty_only = gd.getNextBoolean();
int i_start = gd.getNextChoiceIndex();
int i_end = gd.getNextChoiceIndex();
ArrayList al = new ArrayList();
ArrayList al_zd = layer.getParent().getZDisplayables();
ZDisplayable[] zd = new ZDisplayable[al_zd.size()];
al_zd.toArray(zd);
for (int i=i_start, j=0; i <= i_end; i++, j++) {
Layer la = layer.getParent().getLayer(i);
if (!la.isEmpty() || !non_empty_only) al.add(la); // checks both the Layer and the ZDisplayable objects in the parent LayerSet
}
if (0 == al.size()) {
Utils.showMessage("All layers are empty!");
return;
}
layer_array = new Layer[al.size()];
al.toArray(layer_array);
} else {
layer_array = new Layer[]{Display.this.layer};
}
final boolean quality = gd.getNextBoolean();
final boolean save_to_file = gd.getNextBoolean();
final boolean save_for_web = gd.getNextBoolean();
// in its own thread
if (save_for_web) project.getLoader().makePrescaledTiles(layer_array, Patch.class, srcRect, scale, c_alphas, the_type);
else project.getLoader().makeFlatImage(layer_array, srcRect, scale, c_alphas, the_type, save_to_file, quality);
} else if (command.equals("Lock")) {
selection.setLocked(true);
} else if (command.equals("Unlock")) {
selection.setLocked(false);
} else if (command.equals("Properties...")) {
active.adjustProperties();
updateSelection();
} else if (command.equals("Cancel alignment")) {
layer.getParent().cancelAlign();
} else if (command.equals("Align with landmarks")) {
layer.getParent().applyAlign(false);
} else if (command.equals("Align and register")) {
layer.getParent().applyAlign(true);
} else if (command.equals("Align using profiles")) {
if (!selection.contains(Profile.class)) {
Utils.showMessage("No profiles are selected.");
return;
}
// ask for range of layers
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
Layer la_start = layer.getParent().getLayer(gd.getNextChoiceIndex());
Layer la_end = layer.getParent().getLayer(gd.getNextChoiceIndex());
if (la_start == la_end) {
Utils.showMessage("Need at least two layers.");
return;
}
if (selection.isLocked()) {
Utils.showMessage("There are locked objects.");
return;
}
layer.getParent().startAlign(Display.this);
layer.getParent().applyAlign(la_start, la_end, selection);
} else if (command.equals("Align stack slices")) {
if (getActive() instanceof Patch) {
final Patch slice = (Patch)getActive();
if (slice.isStack()) {
// check linked group
final HashSet hs = slice.getLinkedGroup(new HashSet());
for (Iterator it = hs.iterator(); it.hasNext(); ) {
if (it.next().getClass() != Patch.class) {
Utils.showMessage("Images are linked to other objects, can't proceed to cross-correlate them."); // labels should be fine, need to check that
return;
}
}
slice.getLayer().getParent().createUndoStep(); // full
Registration.registerStackSlices((Patch)getActive()); // will repaint
} else {
Utils.log("Align stack slices: selected image is not part of a stack.");
}
}
} else if (command.equals("Align layers (layer-wise)")) {
Registration.registerLayers(layer, Registration.LAYER_SIFT);
} else if (command.equals("Align layers (tile-wise global minimization)")) {
Registration.registerLayers(layer, Registration.GLOBAL_MINIMIZATION);
} else if (command.equals("Properties ...")) { // NOTE the space before the dots, to distinguish from the "Properties..." command that works on Displayable objects.
GenericDialog gd = new GenericDialog("Properties", Display.this.frame);
//gd.addNumericField("layer_scroll_step: ", this.scroll_step, 0);
gd.addSlider("layer_scroll_step: ", 1, layer.getParent().size(), Display.this.scroll_step);
gd.addChoice("snapshots_mode", LayerSet.snapshot_modes, LayerSet.snapshot_modes[layer.getParent().getSnapshotsMode()]);
gd.addCheckbox("prefer_snapshots_quality", layer.getParent().snapshotsQuality());
Loader lo = getProject().getLoader();
boolean using_mipmaps = lo.isMipMapsEnabled();
gd.addCheckbox("enable_mipmaps", using_mipmaps);
String preprocessor = project.getLoader().getPreprocessor();
gd.addStringField("image_preprocessor: ", null == preprocessor ? "" : preprocessor);
gd.addCheckbox("enable_layer_pixels virtualization", layer.getParent().isPixelsVirtualizationEnabled());
double max = layer.getParent().getLayerWidth() < layer.getParent().getLayerHeight() ? layer.getParent().getLayerWidth() : layer.getParent().getLayerHeight();
gd.addSlider("max_dimension of virtualized layer pixels: ", 0, max, layer.getParent().getPixelsDimension());
// --------
gd.showDialog();
if (gd.wasCanceled()) return;
// --------
int sc = (int) gd.getNextNumber();
if (sc < 1) sc = 1;
Display.this.scroll_step = sc;
updateInDatabase("scroll_step");
//
layer.getParent().setSnapshotsMode(gd.getNextChoiceIndex());
layer.getParent().setSnapshotsQuality(gd.getNextBoolean());
//
boolean generate_mipmaps = gd.getNextBoolean();
if (using_mipmaps && generate_mipmaps) {
// nothing changed
} else {
if (using_mipmaps) { // and !generate_mipmaps
lo.flushMipMaps(true);
} else {
// not using mipmaps before, and true == generate_mipmaps
lo.generateMipMaps(layer.getParent().getDisplayables(Patch.class));
}
}
//
final String prepro = gd.getNextString();
if (!project.getLoader().setPreprocessor(prepro.trim())) {
Utils.showMessage("Could NOT set the preprocessor to " + prepro);
}
//
layer.getParent().setPixelsVirtualizationEnabled(gd.getNextBoolean());
layer.getParent().setPixelsDimension((int)gd.getNextNumber());
} else if (command.equals("Search...")) {
new Search();
} else if (command.equals("Select all")) {
selection.selectAll();
repaint(Display.this.layer, selection.getBox(), 0);
} else if (command.equals("Select none")) {
Rectangle box = selection.getBox();
selection.clear();
repaint(Display.this.layer, box, 0);
} else if (command.equals("Restore selection")) {
selection.restore();
} else if (command.equals("Select under ROI")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return;
selection.selectAll(roi, true);
} else if (command.equals("Merge")) {
ArrayList al_sel = selection.getSelected();
// put active at the beginning, to work as the base on which other's will get merged
al_sel.remove(Display.this.active);
al_sel.add(0, Display.this.active);
AreaList ali = AreaList.merge(al_sel);
if (null != ali) {
// remove all but the first from the selection
for (int i=1; i<al_sel.size(); i++) {
Object ob = al_sel.get(i);
if (ob.getClass() == AreaList.class) {
selection.remove((Displayable)ob);
}
}
selection.updateTransform(ali);
repaint(ali.getLayerSet(), ali, 0);
}
} else if (command.equals("Identify...")) {
// for pipes only for now
if (!(active instanceof Pipe)) return;
ini.trakem2.vector.Compare.findSimilar((Pipe)active);
} else if (command.equals("Identify with axes...")) {
if (!(active instanceof Pipe)) return;
if (Project.getProjects().size() < 2) {
Utils.showMessage("You need at least two projects open:\n-A reference project\n-The current project with the pipe to identify");
return;
}
ini.trakem2.vector.Compare.findSimilarWithAxes((Pipe)active);
} else if (command.equals("View orthoslices")) {
if (!(active instanceof Patch)) return;
Display3D.showOrthoslices(((Patch)active));
} else if (command.equals("View volume")) {
if (!(active instanceof Patch)) return;
Display3D.showVolume(((Patch)active));
} else if (command.equals("Show in 3D")) {
for (Iterator it = selection.getSelected(ZDisplayable.class).iterator(); it.hasNext(); ) {
ZDisplayable zd = (ZDisplayable)it.next();
Display3D.show(zd.getProject().findProjectThing(zd));
}
// handle profile lists ...
HashSet hs = new HashSet();
for (Iterator it = selection.getSelected(Profile.class).iterator(); it.hasNext(); ) {
Displayable d = (Displayable)it.next();
ProjectThing profile_list = (ProjectThing)d.getProject().findProjectThing(d).getParent();
if (!hs.contains(profile_list)) {
Display3D.show(profile_list);
hs.add(profile_list);
}
}
} else if (command.equals("Snap")) {
if (!(active instanceof Patch)) return;
StitchingTEM.snap(getActive(), Display.this);
} else if (command.equals("Montage")) {
if (!(active instanceof Patch)) {
Utils.showMessage("Please select only images.");
return;
}
for (Object ob : selection.getSelected()) {
if (!(ob instanceof Patch)) {
Utils.showMessage("Please select only images.\nCurrently, a " + Project.getName(ob.getClass()) + " is also selected.");
return;
}
}
HashSet hs = new HashSet();
hs.addAll(selection.getSelected(Patch.class));
// make an undo step!
layer.getParent().addUndoStep(selection.getAffected());
Registration.registerTilesSIFT(hs, (Patch)active, null, false);
} else if (command.equals("Link images...")) {
GenericDialog gd = new GenericDialog("Options");
gd.addMessage("Linking images to images (within their own layer only):");
String[] options = {"all images to all images", "each image with any other overlapping image"};
gd.addChoice("Link: ", options, options[1]);
String[] options2 = {"selected images only", "all images in this layer", "all images in all layers"};
gd.addChoice("Apply to: ", options2, options2[0]);
gd.showDialog();
if (gd.wasCanceled()) return;
boolean overlapping_only = 1 == gd.getNextChoiceIndex();
switch (gd.getNextChoiceIndex()) {
case 0:
Patch.crosslink(selection.getSelected(Patch.class), overlapping_only);
break;
case 1:
Patch.crosslink(layer.getDisplayables(Patch.class), overlapping_only);
break;
case 2:
for (Layer la : layer.getParent().getLayers()) {
Patch.crosslink(la.getDisplayables(Patch.class), overlapping_only);
}
break;
}
} else if (command.equals("Homogenize contrast (selected images)")) {
ArrayList al = selection.getSelected(Patch.class);
if (al.size() < 2) return;
getProject().getLoader().homogenizeContrast(al);
} else if (command.equals("Homogenize contrast layer-wise...")) {
// ask for range of layers
final GenericDialog gd = new GenericDialog("Choose range");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
java.util.List list = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
Layer[] la = new Layer[list.size()];
list.toArray(la);
project.getLoader().homogenizeContrast(la);
} else if (command.equals("Set Min and Max...")) {
final GenericDialog gd = new GenericDialog("Choices");
gd.addMessage("Either process all images of all layers\nwithin the selected range,\nor check the box for using selected images only.");
Utils.addLayerRangeChoices(Display.this.layer, gd);
gd.addCheckbox("use_selected_images_only", false);
gd.addMessage("-------");
gd.addNumericField("min: ", 0, 2);
gd.addNumericField("max: ", 255, 2);
gd.addCheckbox("drift_mean", true);
gd.addMessage("Or let each image find its optimal:");
gd.addCheckbox("independent", false);
gd.showDialog();
if (gd.wasCanceled()) return;
boolean use_selected_images = gd.getNextBoolean();
double min = gd.getNextNumber();
double max = gd.getNextNumber();
if (Double.isNaN(min) || Double.isNaN(max) || min < 0 || max < min) {
Utils.showMessage("Improper min and max values.");
return;
}
boolean drift_hist_peak = gd.getNextBoolean();
boolean independent = gd.getNextBoolean();
Utils.log2("Di Using: " + min + ", " + max + ", " + drift_hist_peak + " use_selected_images: " + use_selected_images);
if (use_selected_images) {
ArrayList al_images = selection.getSelected(Patch.class);
if (al_images.size() < 1) {
Utils.log2("You need at least 2 images selected.");
return;
}
if (independent) {
project.getLoader().optimizeContrast(al_images);
} else {
project.getLoader().homogenizeContrast(al_images, min, max, drift_hist_peak);
}
} else {
java.util.List list = list = layer.getParent().getLayers().subList(gd.getNextChoiceIndex(), gd.getNextChoiceIndex() +1); // exclusive end
Layer[] la = new Layer[list.size()];
list.toArray(la);
if (independent) {
ArrayList al_images = new ArrayList();
for (int i=0; i<la.length; i++) {
al_images.addAll(la[i].getDisplayables(Patch.class));
}
project.getLoader().optimizeContrast(al_images);
} else {
project.getLoader().homogenizeContrast(la, min, max, drift_hist_peak);
}
}
} else if (command.equals("Create subproject")) {
Roi roi = canvas.getFakeImagePlus().getRoi();
if (null == roi) return; // the menu item is not active unless there is a ROI
Layer first, last;
if (1 == layer.getParent().size()) {
first = last = layer;
} else {
GenericDialog gd = new GenericDialog("Choose layer range");
Utils.addLayerRangeChoices(layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
first = layer.getParent().getLayer(gd.getNextChoiceIndex());
last = layer.getParent().getLayer(gd.getNextChoiceIndex());
Utils.log2("first, last: " + first + ", " + last);
}
Project sub = getProject().createSubproject(roi.getBounds(), first, last);
final LayerSet subls = sub.getRootLayerSet();
final Display d = new Display(sub, subls.getLayer(0));
SwingUtilities.invokeLater(new Runnable() { public void run() {
d.canvas.showCentered(new Rectangle(0, 0, (int)subls.getLayerWidth(), (int)subls.getLayerHeight()));
}});
} else if (command.equals("Export arealists as labels")) {
GenericDialog gd = new GenericDialog("Export labels");
gd.addSlider("Scale: ", 1, 100, 100);
final String[] options = {"All area list", "Selected area lists"};
gd.addChoice("Export: ", options, options[0]);
Utils.addLayerRangeChoices(layer, gd);
gd.showDialog();
if (gd.wasCanceled()) return;
final float scale = (float)(gd.getNextNumber() / 100);
java.util.List al = 0 == gd.getNextChoiceIndex() ? layer.getParent().getZDisplayables(AreaList.class) : selection.getSelected(AreaList.class);
if (null == al) {
Utils.log("No area lists found to export.");
return;
}
if (al.size() > 255) {
YesNoCancelDialog yn = new YesNoCancelDialog(frame, "WARNING", "Found more than 255 area lists to export:\nExport only the first 255?");
if (yn.cancelPressed()) return;
if (yn.yesPressed()) al = al.subList(0, 255); // only 255 total: the 0 is left for background
}
int first = gd.getNextChoiceIndex();
int last = gd.getNextChoiceIndex();
AreaList.exportAsLabels(al, canvas.getFakeImagePlus().getRoi(), scale, first, last);
} else if (command.equals("Project properties...")) {
project.adjustProperties();
} else if (command.equals("Release memory...")) {
new Bureaucrat(new Worker("Releasing memory") {
public void run() {
startedWorking();
try {
GenericDialog gd = new GenericDialog("Release Memory");
int max = (int)(IJ.maxMemory() / 1000000);
gd.addSlider("Megabytes: ", 0, max, max/2);
gd.showDialog();
if (!gd.wasCanceled()) {
int n_mb = (int)gd.getNextNumber();
project.getLoader().releaseToFit((long)n_mb*1000000);
}
} catch (Throwable e) {
IJError.print(e);
} finally {
finishedWorking();
}
}
}, project).goHaveBreakfast();
} else {
Utils.log2("Display: don't know what to do with command " + command);
}
}});
|
diff --git a/src/biz/bokhorst/xprivacy/PrivacyManager.java b/src/biz/bokhorst/xprivacy/PrivacyManager.java
index 21282137..7b665fde 100644
--- a/src/biz/bokhorst/xprivacy/PrivacyManager.java
+++ b/src/biz/bokhorst/xprivacy/PrivacyManager.java
@@ -1,1422 +1,1424 @@
package biz.bokhorst.xprivacy;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.location.Location;
import android.os.Binder;
import android.os.Build;
import android.os.Process;
import android.os.SystemClock;
import android.util.Log;
public class PrivacyManager {
// This should correspond with restrict_<name> in strings.xml
public static final String cAccounts = "accounts";
public static final String cBrowser = "browser";
public static final String cCalendar = "calendar";
public static final String cCalling = "calling";
public static final String cClipboard = "clipboard";
public static final String cContacts = "contacts";
public static final String cDictionary = "dictionary";
public static final String cEMail = "email";
public static final String cIdentification = "identification";
public static final String cInternet = "internet";
public static final String cLocation = "location";
public static final String cMedia = "media";
public static final String cMessages = "messages";
public static final String cNetwork = "network";
public static final String cNfc = "nfc";
public static final String cNotifications = "notifications";
public static final String cOverlay = "overlay";
public static final String cPhone = "phone";
public static final String cSensors = "sensors";
public static final String cShell = "shell";
public static final String cStorage = "storage";
public static final String cSystem = "system";
public static final String cView = "view";
// This should correspond with the above definitions
private static final String cRestrictionNames[] = new String[] { cAccounts, cBrowser, cCalendar, cCalling,
cClipboard, cContacts, cDictionary, cEMail, cIdentification, cInternet, cLocation, cMedia, cMessages,
cNetwork, cNfc, cNotifications, cOverlay, cPhone, cSensors, cShell, cStorage, cSystem, cView };
// Setting names
public final static String cSettingSerial = "Serial";
public final static String cSettingLatitude = "Latitude";
public final static String cSettingLongitude = "Longitude";
public final static String cSettingMac = "Mac";
public final static String cSettingIP = "IP";
public final static String cSettingImei = "IMEI";
public final static String cSettingPhone = "Phone";
public final static String cSettingId = "ID";
public final static String cSettingGsfId = "GSF_ID";
public final static String cSettingAdId = "AdId";
public final static String cSettingMcc = "MCC";
public final static String cSettingMnc = "MNC";
public final static String cSettingCountry = "Country";
public final static String cSettingOperator = "Operator";
public final static String cSettingIccId = "ICC_ID";
public final static String cSettingSubscriber = "Subscriber";
public final static String cSettingSSID = "SSID";
public final static String cSettingUa = "UA";
public final static String cSettingFUsed = "FUsed";
public final static String cSettingFInternet = "FInternet";
public final static String cSettingFRestriction = "FRestriction";
public final static String cSettingFRestrictionNot = "FRestrictionNot";
public final static String cSettingFPermission = "FPermission";
public final static String cSettingFUser = "FUser";
public final static String cSettingFSystem = "FSystem";
public final static String cSettingTheme = "Theme";
public final static String cSettingSalt = "Salt";
public final static String cSettingVersion = "Version";
public final static String cSettingFirstRun = "FirstRun";
public final static String cSettingTutorialMain = "TutorialMain";
public final static String cSettingTutorialDetails = "TutorialDetails";
public final static String cSettingNotify = "Notify";
public final static String cSettingLog = "Log";
public final static String cSettingDangerous = "Dangerous";
public final static String cSettingAndroidUsage = "AndroidUsage";
public final static String cSettingExperimental = "Experimental";
public final static String cSettingRandom = "Random@boot";
public final static String cSettingState = "State";
public final static String cSettingConfidence = "Confidence";
public final static String cSettingTemplate = "Template";
// Special value names
public final static String cValueRandom = "#Random#";
public final static String cValueRandomLegacy = "\nRandom\n";
// Constants
public final static int cXposedAppProcessMinVersion = 46;
public final static int cAndroidUid = Process.SYSTEM_UID;
public final static boolean cTestVersion = true;
private final static String cDeface = "DEFACE";
public final static int cRestrictionCacheTimeoutMs = 15 * 1000;
public final static int cSettingCacheTimeoutMs = 30 * 1000;
public final static int cUseProviderAfterMs = 3 * 60 * 1000;
// Static data
private static Map<String, List<MethodDescription>> mMethod = new LinkedHashMap<String, List<MethodDescription>>();
private static Map<String, List<MethodDescription>> mPermission = new LinkedHashMap<String, List<MethodDescription>>();
private static Map<String, CRestriction> mRestrictionCache = new HashMap<String, CRestriction>();
private static Map<String, CSetting> mSettingsCache = new HashMap<String, CSetting>();
private static Map<UsageData, UsageData> mUsageQueue = new LinkedHashMap<UsageData, UsageData>();
private static ExecutorService mExecutor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
static {
// Scan meta data
try {
File in = new File(Util.getUserDataDirectory(Process.myUid()) + File.separator + "meta.xml");
Util.log(null, Log.INFO, "Reading meta=" + in.getAbsolutePath());
FileInputStream fis = null;
try {
fis = new FileInputStream(in);
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
MetaHandler metaHandler = new MetaHandler();
xmlReader.setContentHandler(metaHandler);
xmlReader.parse(new InputSource(fis));
} finally {
if (fis != null)
fis.close();
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
}
private static class MetaHandler extends DefaultHandler {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("Meta"))
;
else if (qName.equals("Hook")) {
// Get meta data
String restrictionName = attributes.getValue("restriction");
String methodName = attributes.getValue("method");
String dangerous = attributes.getValue("dangerous");
String restart = attributes.getValue("restart");
String permissions = attributes.getValue("permissions");
int sdk = (attributes.getValue("sdk") == null ? 0 : Integer.parseInt(attributes.getValue("sdk")));
String from = attributes.getValue("from");
// Add meta data
if (Build.VERSION.SDK_INT >= sdk) {
boolean danger = (dangerous == null ? false : Boolean.parseBoolean(dangerous));
boolean restartRequired = (restart == null ? false : Boolean.parseBoolean(restart));
String[] permission = (permissions == null ? null : permissions.split(","));
MethodDescription md = new MethodDescription(restrictionName, methodName, danger, restartRequired,
permission, sdk, from == null ? null : new Version(from));
if (!mMethod.containsKey(restrictionName))
mMethod.put(restrictionName, new ArrayList<MethodDescription>());
if (!mMethod.get(restrictionName).contains(methodName))
mMethod.get(restrictionName).add(md);
if (permission != null)
for (String perm : permission)
if (!perm.equals("")) {
String aPermission = (perm.contains(".") ? perm : "android.permission." + perm);
if (!mPermission.containsKey(aPermission))
mPermission.put(aPermission, new ArrayList<MethodDescription>());
if (!mPermission.get(aPermission).contains(md))
mPermission.get(aPermission).add(md);
}
}
} else
Util.log(null, Log.WARN, "Unknown element=" + qName);
}
}
// Data
public static void registerMethod(String restrictionName, String methodName, int sdk) {
if (restrictionName != null && methodName != null && Build.VERSION.SDK_INT >= sdk) {
if (!mMethod.containsKey(restrictionName)
|| !mMethod.get(restrictionName).contains(new MethodDescription(restrictionName, methodName)))
Util.log(null, Log.WARN, "Missing method " + methodName);
}
}
public static List<String> getRestrictions() {
return new ArrayList<String>(Arrays.asList(cRestrictionNames));
}
// Map of restrictions sorted by localized name
public static TreeMap<String, String> getRestrictions(Context context) {
Collator collator = Collator.getInstance(Locale.getDefault());
TreeMap<String, String> tmRestriction = new TreeMap<String, String>(collator);
String packageName = PrivacyManager.class.getPackage().getName();
for (String restrictionName : getRestrictions()) {
int stringId = context.getResources().getIdentifier("restrict_" + restrictionName, "string", packageName);
tmRestriction.put(stringId == 0 ? restrictionName : context.getString(stringId), restrictionName);
}
return tmRestriction;
}
public static MethodDescription getMethod(String restrictionName, String methodName) {
if (mMethod.containsKey(restrictionName)) {
MethodDescription md = new MethodDescription(restrictionName, methodName);
int pos = mMethod.get(restrictionName).indexOf(md);
return (pos < 0 ? null : mMethod.get(restrictionName).get(pos));
} else
return null;
}
public static List<MethodDescription> getMethods(String restrictionName) {
List<MethodDescription> listMethod = new ArrayList<MethodDescription>();
List<MethodDescription> listMethodOrig = mMethod.get(restrictionName);
if (listMethodOrig != null)
listMethod.addAll(listMethodOrig);
// null can happen when upgrading
Collections.sort(listMethod);
return listMethod;
}
public static List<String> getPermissions(String restrictionName) {
List<String> listPermission = new ArrayList<String>();
for (MethodDescription md : getMethods(restrictionName))
if (md.getPermissions() != null)
for (String permission : md.getPermissions())
if (!listPermission.contains(permission))
listPermission.add(permission);
return listPermission;
}
// Restrictions
@SuppressLint("DefaultLocale")
public static boolean getRestricted(final XHook hook, Context context, int uid, String restrictionName,
String methodName, boolean usage, boolean useCache) {
try {
long start = System.currentTimeMillis();
// Check uid
if (uid <= 0) {
Util.log(hook, Log.WARN, "uid <= 0");
Util.logStack(hook);
return false;
}
// Check restriction
if (restrictionName == null || restrictionName.equals("")) {
Util.log(hook, Log.WARN, "restriction empty method=" + methodName);
Util.logStack(hook);
return false;
}
if (usage)
if (methodName == null || methodName.equals("")) {
Util.log(hook, Log.WARN, "method empty");
Util.logStack(hook);
} else if (getMethods(restrictionName).indexOf(new MethodDescription(restrictionName, methodName)) < 0)
Util.log(hook, Log.WARN, "unknown method=" + methodName);
// Check cache
String keyCache = String.format("%d.%s.%s", uid, restrictionName, methodName);
if (useCache)
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(keyCache)) {
CRestriction entry = mRestrictionCache.get(keyCache);
if (entry.isExpired())
mRestrictionCache.remove(keyCache);
else {
long ms = System.currentTimeMillis() - start;
logRestriction(hook, context, uid, "get", restrictionName, methodName,
entry.isRestricted(), true, ms);
return entry.isRestricted();
}
}
}
// Check if privacy provider usable
if (!isProviderUsable(context))
context = null;
// Check if restricted
boolean fallback = true;
boolean restricted = false;
if (context != null)
try {
// Get content resolver
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null) {
Util.log(hook, Log.WARN, "contentResolver is null");
Util.logStack(hook);
} else {
// Query restriction
Cursor cursor = contentResolver.query(PrivacyProvider.URI_RESTRICTION, null, restrictionName,
new String[] { Integer.toString(uid), Boolean.toString(usage), methodName }, null);
if (cursor == null) {
// Can happen if memory low
Util.log(hook, Log.WARN, "cursor is null");
Util.logStack(null);
} else
try {
// Get restriction
if (cursor.moveToNext()) {
restricted = Boolean.parseBoolean(cursor.getString(cursor
.getColumnIndex(PrivacyProvider.COL_RESTRICTED)));
fallback = false;
} else {
Util.log(hook, Log.WARN, "cursor is empty");
Util.logStack(null);
}
} finally {
cursor.close();
}
// Send usage data async
sendUsageData(hook, context);
}
} catch (SecurityException ex) {
Util.bug(hook, ex);
} catch (Throwable ex) {
Util.bug(hook, ex);
}
// Use fallback
if (fallback) {
// Fallback
restricted = PrivacyProvider.getRestrictedFallback(hook, uid, restrictionName, methodName);
// Queue usage data
if (usage) {
UsageData usageData = new UsageData(uid, restrictionName, methodName, restricted);
synchronized (mUsageQueue) {
if (mUsageQueue.containsKey(usageData))
mUsageQueue.remove(usageData);
mUsageQueue.put(usageData, usageData);
Util.log(hook, Log.INFO, "Queue usage data=" + usageData + " size=" + mUsageQueue.size());
}
}
}
// Add to cache
synchronized (mRestrictionCache) {
if (mRestrictionCache.containsKey(keyCache))
mRestrictionCache.remove(keyCache);
mRestrictionCache.put(keyCache, new CRestriction(restricted));
}
// Result
long ms = System.currentTimeMillis() - start;
logRestriction(hook, context, uid, "get", restrictionName, methodName, restricted, false, ms);
return restricted;
} catch (Throwable ex) {
// Failsafe
Util.bug(hook, ex);
return false;
}
}
public static boolean getRestricted(XHook hook, int uid, String permission) {
boolean allRestricted = false;
if (mPermission.containsKey(permission)) {
allRestricted = true;
for (MethodDescription md : mPermission.get(permission)) {
boolean restricted = PrivacyProvider.getRestrictedFallback(hook, uid, md.getRestrictionName(),
md.getName());
allRestricted = allRestricted && restricted;
}
}
return allRestricted;
}
// TODO: Waiting for SDK 20 ...
public static final int FIRST_ISOLATED_UID = 99000;
public static final int LAST_ISOLATED_UID = 99999;
public static final int FIRST_SHARED_APPLICATION_GID = 50000;
public static final int LAST_SHARED_APPLICATION_GID = 59999;
public static boolean isApplication(int uid) {
uid = Util.getAppId(uid);
return (uid >= Process.FIRST_APPLICATION_UID && uid <= Process.LAST_APPLICATION_UID);
}
public static boolean isShared(int uid) {
uid = Util.getAppId(uid);
return (uid >= FIRST_SHARED_APPLICATION_GID && uid <= LAST_SHARED_APPLICATION_GID);
}
public static boolean isIsolated(int uid) {
uid = Util.getAppId(uid);
return (uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID);
}
private static boolean isProviderUsable(Context context) {
if (context == null)
return false;
String self = PrivacyManager.class.getPackage().getName();
if (self.equals(context.getPackageName()))
return true;
if (SystemClock.elapsedRealtime() < cUseProviderAfterMs / ("hammerhead".equals(Build.PRODUCT) ? 6 : 1))
return false;
if (isIsolated(Process.myUid()))
return false;
if (Util.getAppId(Process.myUid()) == cAndroidUid)
if (!PrivacyManager.getSettingBool(null, null, 0, PrivacyManager.cSettingAndroidUsage, true, false))
return false;
return true;
}
public static void sendUsageData(final XHook hook, Context context) {
if (!isProviderUsable(context))
return;
int qSize = 0;
synchronized (mUsageQueue) {
qSize = mUsageQueue.size();
}
if (qSize > 0) {
final Context fContext = context;
mExecutor.execute(new Runnable() {
public void run() {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
UsageData data = null;
do {
int size = 0;
synchronized (mUsageQueue) {
if (mUsageQueue.size() > 0) {
data = mUsageQueue.keySet().iterator().next();
mUsageQueue.remove(data);
size = mUsageQueue.size();
} else
data = null;
}
if (data != null) {
try {
Util.log(hook, Log.INFO, "Sending usage data=" + data + " size=" + size + " uid="
+ Binder.getCallingUid());
ContentValues values = new ContentValues();
values.put(PrivacyProvider.COL_UID, data.getUid());
values.put(PrivacyProvider.COL_RESTRICTION, data.getRestrictionName());
values.put(PrivacyProvider.COL_METHOD, data.getMethodName());
values.put(PrivacyProvider.COL_RESTRICTED, data.getRestricted());
values.put(PrivacyProvider.COL_USED, data.getTimeStamp());
if (fContext.getContentResolver().update(PrivacyProvider.URI_USAGE, values, null, null) <= 0)
Util.log(hook, Log.INFO, "Error updating usage data=" + data);
Thread.sleep(500);
} catch (Throwable ex) {
Util.bug(hook, ex);
}
}
} while (data != null);
}
});
} else
Util.log(hook, Log.INFO, "No usage data queued uid=" + Binder.getCallingUid());
}
public static boolean setRestricted(XHook hook, Context context, int uid, String restrictionName,
String methodName, boolean restricted, boolean changeState) {
// Check context
if (context == null) {
Util.log(hook, Log.WARN, "context is null");
return false;
}
// Check uid
if (uid == 0) {
Util.log(hook, Log.WARN, "uid=0");
return false;
}
// Get content resolver
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null) {
Util.log(hook, Log.WARN, "contentResolver is null");
return false;
}
// Set restrictions
ContentValues values = new ContentValues();
values.put(PrivacyProvider.COL_UID, uid);
values.put(PrivacyProvider.COL_METHOD, methodName);
values.put(PrivacyProvider.COL_RESTRICTED, Boolean.toString(restricted));
if (contentResolver.update(PrivacyProvider.URI_RESTRICTION, values, restrictionName, null) <= 0)
Util.log(hook, Log.INFO, "Error updating restriction=" + restrictionName);
// Result
logRestriction(hook, context, uid, "set", restrictionName, methodName, restricted, false, 0);
// Mark as restricted
if (restricted && changeState)
PrivacyManager.setSetting(null, context, uid, PrivacyManager.cSettingState,
Integer.toString(ActivityMain.STATE_RESTRICTED));
// Make exceptions for dangerous methods
boolean dangerous = PrivacyManager.getSettingBool(null, context, 0, PrivacyManager.cSettingDangerous, false,
false);
if (methodName == null)
if (restricted && !dangerous) {
for (MethodDescription md : getMethods(restrictionName))
if (md.isDangerous())
PrivacyManager.setRestricted(null, context, uid, restrictionName, md.getName(), dangerous,
changeState);
}
// Flush caches
if (methodName == null)
XApplication.manage(context, uid, XApplication.cActionFlushCache);
// Check restart
if (methodName == null) {
for (MethodDescription md : getMethods(restrictionName))
if (md.isRestartRequired() && !(restricted && !dangerous && md.isDangerous()))
return true;
return false;
} else
return getMethod(restrictionName, methodName).isRestartRequired();
}
public static List<Boolean> getRestricted(Context context, int uid, String restrictionName) {
List<Boolean> listRestricted = new ArrayList<Boolean>();
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver != null) {
Cursor cursor = contentResolver.query(PrivacyProvider.URI_RESTRICTION, null, restrictionName, new String[] {
Integer.toString(uid), Boolean.toString(false), restrictionName == null ? null : "*" }, null);
if (cursor != null)
try {
while (cursor.moveToNext()) {
listRestricted.add(Boolean.parseBoolean(cursor.getString(cursor
.getColumnIndex(PrivacyProvider.COL_RESTRICTED))));
}
} finally {
cursor.close();
}
}
return listRestricted;
}
public static void flush(Context context, int uid) {
synchronized (mRestrictionCache) {
mRestrictionCache.clear();
}
synchronized (mSettingsCache) {
mSettingsCache.clear();
}
PrivacyProvider.flush();
}
public static class RestrictionDesc {
public int uid;
public boolean restricted;
public String restrictionName;
public String methodName;
}
public static List<RestrictionDesc> getRestricted(Context context, Runnable progress) {
List<RestrictionDesc> result = new ArrayList<RestrictionDesc>();
progress.run(); // 1% for getting the cursor
Cursor rCursor = context.getContentResolver().query(PrivacyProvider.URI_RESTRICTION, null, null,
new String[] { Integer.toString(0), Boolean.toString(false) }, null);
if (rCursor != null)
try {
final int max = rCursor.getCount();
final int step = (max + 95) / 96;
// 96% left for loading the restrictions
int current = 0;
while (rCursor.moveToNext()) {
current++;
if (current % step == 0 || current == max)
progress.run();
RestrictionDesc restriction = new RestrictionDesc();
restriction.uid = rCursor.getInt(rCursor.getColumnIndex(PrivacyProvider.COL_UID));
restriction.restricted = Boolean.parseBoolean(rCursor.getString(rCursor
.getColumnIndex(PrivacyProvider.COL_RESTRICTED)));
restriction.restrictionName = rCursor.getString(rCursor
.getColumnIndex(PrivacyProvider.COL_RESTRICTION));
restriction.methodName = rCursor.getString(rCursor.getColumnIndex(PrivacyProvider.COL_METHOD));
result.add(restriction);
}
} finally {
rCursor.close();
}
return result;
}
public static boolean deleteRestrictions(Context context, int uid, boolean changeState) {
// Check if restart required
boolean restart = false;
for (String restrictionName : getRestrictions()) {
for (MethodDescription md : getMethods(restrictionName))
if (getRestricted(null, context, uid, restrictionName, md.getName(), false, false))
if (md.isRestartRequired()) {
restart = true;
break;
}
if (restart)
break;
}
// Delete restrictions
context.getContentResolver().delete(PrivacyProvider.URI_RESTRICTION, null,
new String[] { Integer.toString(uid) });
Util.log(null, Log.INFO, "Deleted restrictions uid=" + uid);
// Mark as new/changed
if (changeState)
PrivacyManager.setSetting(null, context, uid, PrivacyManager.cSettingState,
Integer.toString(ActivityMain.STATE_ATTENTION));
return restart;
}
// Usage
public static long getUsed(Context context, int uid, String restrictionName, String methodName) {
long lastUsage = 0;
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(PrivacyProvider.URI_USAGE, null, restrictionName, new String[] {
Integer.toString(uid), methodName }, null);
if (cursor != null)
try {
while (cursor.moveToNext()) {
long usage = cursor.getLong(cursor.getColumnIndex(PrivacyProvider.COL_USED));
if (usage > lastUsage)
lastUsage = usage;
}
} finally {
cursor.close();
}
return lastUsage;
}
public static List<UsageData> getUsed(Context context, int uid) {
List<UsageData> listUsage = new ArrayList<UsageData>();
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(PrivacyProvider.URI_USAGE, null, null, new String[] { Integer.toString(uid), null },
null);
if (cursor != null)
try {
while (cursor.moveToNext()) {
int rUid = cursor.getInt(cursor.getColumnIndex(PrivacyProvider.COL_UID));
String restrictionName = cursor.getString(cursor.getColumnIndex(PrivacyProvider.COL_RESTRICTION));
String methodName = cursor.getString(cursor.getColumnIndex(PrivacyProvider.COL_METHOD));
boolean restricted = Boolean.parseBoolean(cursor.getString(cursor
.getColumnIndex(PrivacyProvider.COL_RESTRICTED)));
long used = cursor.getLong(cursor.getColumnIndex(PrivacyProvider.COL_USED));
UsageData usageData = new UsageData(rUid, restrictionName, methodName, restricted, used);
listUsage.add(usageData);
}
} finally {
cursor.close();
}
Collections.sort(listUsage);
return listUsage;
}
public static void deleteUsage(Context context, int uid) {
context.getContentResolver().delete(PrivacyProvider.URI_USAGE, null, new String[] { Integer.toString(uid) });
Util.log(null, Log.INFO, "Deleted usage data uid=" + uid);
}
// Settings
public static boolean getSettingBool(XHook hook, Context context, int uid, String settingName,
boolean defaultValue, boolean useCache) {
return Boolean.parseBoolean(getSetting(hook, context, uid, settingName, Boolean.toString(defaultValue),
useCache));
}
public static String getSetting(XHook hook, Context context, int uid, String settingName, String defaultValue,
boolean useCache) {
if (uid == 0)
return getSetting(hook, context, settingName, defaultValue, useCache);
else {
String setting = getSetting(hook, context, String.format("%s.%d", settingName, uid), null, useCache);
if (setting == null)
return getSetting(hook, context, settingName, defaultValue, useCache);
else
return setting;
}
}
public static String getAppSetting(XHook hook, Context context, int uid, String settingName, String defaultValue,
boolean useCache) {
return getSetting(hook, context, String.format("%s.%d", settingName, uid), null, useCache);
}
private static String getSetting(XHook hook, Context context, String name, String defaultValue, boolean useCache) {
long start = System.currentTimeMillis();
// Check cache
if (useCache)
synchronized (mSettingsCache) {
if (mSettingsCache.containsKey(name)) {
CSetting entry = mSettingsCache.get(name);
if (entry.isExpired())
mSettingsCache.remove(name);
else {
String value = mSettingsCache.get(name).getSettingsValue();
if (entry.willExpire())
Util.log(hook, Log.INFO, String.format("get setting %s=%s (cached)", name, value));
return value;
}
}
}
// Check if privacy provider usable
if (!isProviderUsable(context))
context = null;
// Get setting
boolean fallback = true;
String value = null;
if (context != null) {
try {
ContentResolver contentResolver = context.getContentResolver();
if (contentResolver == null) {
Util.log(hook, Log.WARN, "contentResolver is null");
Util.logStack(hook);
} else {
Cursor cursor = contentResolver.query(PrivacyProvider.URI_SETTING, null, name, null, null);
if (cursor == null) {
// Can happen if memory low
Util.log(hook, Log.WARN, "cursor is null");
Util.logStack(null);
} else
try {
if (cursor.moveToNext()) {
value = cursor.getString(cursor.getColumnIndex(PrivacyProvider.COL_VALUE));
fallback = false;
} else {
Util.log(hook, Log.WARN, "cursor is empty");
}
} finally {
cursor.close();
}
}
} catch (Throwable ex) {
Util.bug(hook, ex);
Util.logStack(hook);
}
}
// Use fallback
if (fallback)
value = PrivacyProvider.getSettingFallback(name, defaultValue, true);
// Default value
if (value == null)
value = defaultValue;
else if (value.equals("") && defaultValue != null)
value = defaultValue;
// Add to cache
synchronized (mSettingsCache) {
if (mSettingsCache.containsKey(name))
mSettingsCache.remove(name);
mSettingsCache.put(name, new CSetting(name, value));
}
long ms = System.currentTimeMillis() - start;
Util.log(
hook,
Log.INFO,
String.format("get setting %s=%s%s%s", name, value, (fallback ? " (file)" : ""), (ms > 1 ? " " + ms
+ " ms" : "")));
return value;
}
@SuppressLint("DefaultLocale")
public static void setSetting(XHook hook, Context context, int uid, String settingName, String value) {
ContentResolver contentResolver = context.getContentResolver();
ContentValues values = new ContentValues();
values.put(PrivacyProvider.COL_VALUE, value);
String sName = (uid == 0 ? settingName : String.format("%s.%d", settingName, uid));
if (contentResolver.update(PrivacyProvider.URI_SETTING, values, sName, null) <= 0)
Util.log(hook, Log.INFO, "Error updating setting=" + sName);
Util.log(hook, Log.INFO, String.format("set setting %s=%s", sName, value));
// Flush caches
XApplication.manage(context, uid, XApplication.cActionFlushCache);
}
public static Map<String, String> getSettings(Context context, Runnable progress) {
Map<String, String> result = new HashMap<String, String>();
progress.run(); // 1% for getting the cursor
Cursor sCursor = context.getContentResolver().query(PrivacyProvider.URI_SETTING, null, null, null, null);
if (sCursor != null)
try {
final int max = sCursor.getCount();
int current = 0;
while (sCursor.moveToNext()) {
current++;
if (current == max / 2 || current == max)
progress.run(); // 2% for fetching settings
// Get setting
String setting = sCursor.getString(sCursor.getColumnIndex(PrivacyProvider.COL_SETTING));
String value = sCursor.getString(sCursor.getColumnIndex(PrivacyProvider.COL_VALUE));
result.put(setting, value);
}
} finally {
sCursor.close();
}
return result;
}
public static void deleteSettings(Context context, int uid) {
context.getContentResolver().delete(PrivacyProvider.URI_SETTING, null, new String[] { Integer.toString(uid) });
Util.log(null, Log.INFO, "Deleted settings uid=" + uid);
}
// Defacing
public static Object getDefacedProp(int uid, String name) {
// Serial number
if (name.equals("SERIAL") || name.equals("%serialno")) {
String value = getSetting(null, null, uid, cSettingSerial, cDeface, true);
return (cValueRandom.equals(value) ? getRandomProp("SERIAL") : value);
}
// Host name
if (name.equals("%hostname"))
return cDeface;
// MAC addresses
if (name.equals("MAC") || name.equals("%macaddr")) {
String mac = getSetting(null, null, uid, cSettingMac, "DE:FA:CE:DE:FA:CE", true);
if (cValueRandom.equals(mac))
return getRandomProp("MAC");
StringBuilder sb = new StringBuilder(mac.replace(":", ""));
while (sb.length() != 12)
sb.insert(0, '0');
while (sb.length() > 12)
sb.deleteCharAt(sb.length() - 1);
for (int i = 10; i > 0; i -= 2)
sb.insert(i, ':');
return sb.toString();
}
// cid
if (name.equals("%cid"))
return cDeface;
// IMEI
if (name.equals("getDeviceId") || name.equals("%imei")) {
String value = getSetting(null, null, uid, cSettingImei, "000000000000000", true);
return (cValueRandom.equals(value) ? getRandomProp("IMEI") : value);
}
// Phone
if (name.equals("PhoneNumber") || name.equals("getLine1AlphaTag") || name.equals("getLine1Number")
|| name.equals("getMsisdn") || name.equals("getVoiceMailAlphaTag") || name.equals("getVoiceMailNumber")) {
String value = getSetting(null, null, uid, cSettingPhone, cDeface, true);
return (cValueRandom.equals(value) ? getRandomProp("PHONE") : value);
}
// Android ID
if (name.equals("ANDROID_ID")) {
String value = getSetting(null, null, uid, cSettingId, cDeface, true);
return (cValueRandom.equals(value) ? getRandomProp("ANDROID_ID") : value);
}
// Telephony manager
if (name.equals("getGroupIdLevel1"))
return null;
if (name.equals("getIsimDomain"))
return null;
if (name.equals("getIsimImpi"))
return null;
if (name.equals("getIsimImpu"))
return null;
- if (name.equals("getNetworkCountryIso")) {
+ if (name.equals("getNetworkCountryIso") || name.equals("gsm.operator.iso-country")) {
// ISO country code
String value = getSetting(null, null, uid, cSettingCountry, "XX", true);
return (cValueRandom.equals(value) ? getRandomProp("ISO3166") : value);
}
- if (name.equals("getNetworkOperator")) // MCC+MNC: test network
+ if (name.equals("getNetworkOperator") || name.equals("gsm.operator.numeric"))
+ // MCC+MNC: test network
return getSetting(null, null, uid, cSettingMcc, "001", true)
+ getSetting(null, null, uid, cSettingMnc, "01", true);
- if (name.equals("getNetworkOperatorName"))
+ if (name.equals("getNetworkOperatorName") || name.equals("gsm.operator.alpha"))
return getSetting(null, null, uid, cSettingOperator, cDeface, true);
- if (name.equals("getSimCountryIso")) {
+ if (name.equals("getSimCountryIso") || name.equals("gsm.sim.operator.iso-country")) {
// ISO country code
String value = getSetting(null, null, uid, cSettingCountry, "XX", true);
return (cValueRandom.equals(value) ? getRandomProp("ISO3166") : value);
}
- if (name.equals("getSimOperator")) // MCC+MNC: test network
+ if (name.equals("getSimOperator") || name.equals("gsm.sim.operator.numeric"))
+ // MCC+MNC: test network
return getSetting(null, null, uid, cSettingMcc, "001", true)
+ getSetting(null, null, uid, cSettingMnc, "01", true);
- if (name.equals("getSimOperatorName"))
+ if (name.equals("getSimOperatorName") || name.equals("gsm.operator.alpha"))
return getSetting(null, null, uid, cSettingOperator, cDeface, true);
if (name.equals("getSimSerialNumber") || name.equals("getIccSerialNumber"))
return getSetting(null, null, uid, cSettingIccId, null, true);
if (name.equals("getSubscriberId")) { // IMSI for a GSM phone
String value = getSetting(null, null, uid, cSettingSubscriber, null, true);
return (cValueRandom.equals(value) ? getRandomProp("SubscriberId") : value);
}
if (name.equals("SSID")) {
// Default hidden network
String value = getSetting(null, null, uid, cSettingSSID, "", true);
return (cValueRandom.equals(value) ? getRandomProp("SSID") : value);
}
// Google services framework ID
if (name.equals("GSF_ID")) {
long gsfid = 0xDEFACE;
try {
String value = getSetting(null, null, uid, cSettingGsfId, "DEFACE", true);
if (cValueRandom.equals(value))
value = getRandomProp(name);
gsfid = Long.parseLong(value, 16);
} catch (Throwable ex) {
Util.bug(null, ex);
}
return gsfid;
}
// Advertisement ID
if (name.equals("AdvertisingId")) {
String adid = getSetting(null, null, uid, cSettingAdId, "DEFACE00-0000-0000-0000-000000000000", true);
if (cValueRandom.equals(adid))
adid = getRandomProp(name);
return adid;
}
if (name.equals("InetAddress")) {
// Set address
String ip = getSetting(null, null, uid, cSettingIP, null, true);
if (ip != null)
try {
return InetAddress.getByName(ip);
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Any address (0.0.0.0)
try {
Field unspecified = Inet4Address.class.getDeclaredField("ANY");
unspecified.setAccessible(true);
return (InetAddress) unspecified.get(Inet4Address.class);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
if (name.equals("IPInt")) {
// Set address
String ip = getSetting(null, null, uid, cSettingIP, null, true);
if (ip != null)
try {
InetAddress inet = InetAddress.getByName(ip);
if (inet.getClass().equals(Inet4Address.class)) {
byte[] b = inet.getAddress();
return b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Any address (0.0.0.0)
return 0;
}
if (name.equals("Bytes3"))
return new byte[] { (byte) 0xDE, (byte) 0xFA, (byte) 0xCE };
if (name.equals("UA"))
return getSetting(null, null, uid, cSettingUa,
"Mozilla/5.0 (Linux; U; Android; en-us) AppleWebKit/999+ (KHTML, like Gecko) Safari/999.9", true);
// InputDevice
if (name.equals("DeviceDescriptor"))
return cDeface;
// Fallback
Util.log(null, Log.WARN, "Fallback value name=" + name);
return cDeface;
}
public static Location getDefacedLocation(int uid, Location location) {
String sLat = getSetting(null, null, uid, cSettingLatitude, null, true);
String sLon = getSetting(null, null, uid, cSettingLongitude, null, true);
if (cValueRandom.equals(sLat))
sLat = getRandomProp("LAT");
if (cValueRandom.equals(sLon))
sLon = getRandomProp("LON");
// 1 degree ~ 111111 m
// 1 m ~ 0,000009 degrees
// Christmas Island ~ -10.5 / 105.667
if (sLat == null || "".equals(sLat))
location.setLatitude(-10.5);
else
location.setLatitude(Float.parseFloat(sLat) + (Math.random() * 2.0 - 1.0) * location.getAccuracy() * 9e-6);
if (sLon == null || "".equals(sLon))
location.setLongitude(105.667);
else
location.setLongitude(Float.parseFloat(sLon) + (Math.random() * 2.0 - 1.0) * location.getAccuracy() * 9e-6);
return location;
}
@SuppressLint("DefaultLocale")
public static String getRandomProp(String name) {
Random r = new Random();
if (name.equals("SERIAL")) {
long v = r.nextLong();
return Long.toHexString(v).toUpperCase();
}
if (name.equals("MAC")) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 6; i++) {
if (i != 0)
sb.append(':');
int v = r.nextInt(256);
if (i == 0)
v = v & 0xFC; // unicast, globally unique
sb.append(Integer.toHexString(0x100 | v).substring(1));
}
return sb.toString().toUpperCase();
}
// IMEI
if (name.equals("IMEI")) {
// http://en.wikipedia.org/wiki/Reporting_Body_Identifier
String[] rbi = new String[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "30", "33",
"35", "44", "45", "49", "50", "51", "52", "53", "54", "86", "91", "98", "99" };
String imei = rbi[r.nextInt(rbi.length)];
while (imei.length() < 14)
imei += Character.forDigit(r.nextInt(10), 10);
imei += getLuhnDigit(imei);
return imei;
}
if (name.equals("PHONE")) {
String phone = "0";
for (int i = 1; i < 10; i++)
phone += Character.forDigit(r.nextInt(10), 10);
return phone;
}
if (name.equals("ANDROID_ID")) {
long v = r.nextLong();
return Long.toHexString(v).toUpperCase();
}
if (name.equals("ISO3166")) {
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String country = Character.toString(letters.charAt(r.nextInt(letters.length())))
+ Character.toString(letters.charAt(r.nextInt(letters.length())));
return country;
}
if (name.equals("GSF_ID")) {
long v = r.nextLong();
return Long.toHexString(v).toUpperCase();
}
if (name.equals("AdvertisingId"))
return UUID.randomUUID().toString().toUpperCase();
if (name.equals("LAT")) {
double d = r.nextDouble() * 180 - 90;
d = Math.rint(d * 1e7) / 1e7;
return Double.toString(d);
}
if (name.equals("LON")) {
double d = r.nextDouble() * 360 - 180;
d = Math.rint(d * 1e7) / 1e7;
return Double.toString(d);
}
if (name.equals("SubscriberId")) {
String subscriber = "001";
while (subscriber.length() < 15)
subscriber += Character.forDigit(r.nextInt(10), 10);
return subscriber;
}
if (name.equals("SSID")) {
String ssid = "";
while (ssid.length() < 6)
ssid += (char) (r.nextInt(26) + 'A');
ssid += Character.forDigit(r.nextInt(10), 10);
ssid += Character.forDigit(r.nextInt(10), 10);
return ssid;
}
return "";
}
private static char getLuhnDigit(String x) {
// http://en.wikipedia.org/wiki/Luhn_algorithm
int sum = 0;
for (int i = 0; i < x.length(); i++) {
int n = Character.digit(x.charAt(x.length() - 1 - i), 10);
if (i % 2 == 0) {
n *= 2;
if (n > 9)
n -= 9; // n = (n % 10) + 1;
}
sum += n;
}
return Character.forDigit((sum * 9) % 10, 10);
}
// Helper methods
// @formatter:off
private static void logRestriction(
XHook hook, Context context,
int uid, String prefix, String restrictionName, String methodName,
boolean restricted, boolean cached, long ms) {
Util.log(hook, Log.INFO, String.format("%s %d/%s %s=%srestricted%s%s",
prefix, uid, methodName, restrictionName,
(restricted ? "" : "!"),
(cached ? " (cached)" : (context == null ? " (file)" : "")),
(ms > 1 ? " " + ms + " ms" : "")));
}
// @formatter:on
public static boolean hasPermission(Context context, List<String> listPackageName, String restrictionName) {
return hasPermission(context, listPackageName, PrivacyManager.getPermissions(restrictionName));
}
public static boolean hasPermission(Context context, List<String> listPackageName, MethodDescription md) {
List<String> listPermission = (md.getPermissions() == null ? null : Arrays.asList(md.getPermissions()));
return hasPermission(context, listPackageName, listPermission);
}
@SuppressLint("DefaultLocale")
private static boolean hasPermission(Context context, List<String> listPackageName, List<String> listPermission) {
try {
if (listPermission == null || listPermission.size() == 0 || listPermission.contains(""))
return true;
PackageManager pm = context.getPackageManager();
for (String packageName : listPackageName) {
PackageInfo pInfo = pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
if (pInfo != null && pInfo.requestedPermissions != null)
for (String rPermission : pInfo.requestedPermissions)
for (String permission : listPermission)
if (permission.equals("")) {
// No permission required
return true;
} else if (rPermission.toLowerCase().contains(permission.toLowerCase())) {
String aPermission = "android.permission." + permission;
if (!aPermission.equals(rPermission))
Util.log(null, Log.WARN, "Check permission=" + permission + "/" + rPermission);
return true;
} else if (permission.contains("."))
if (pm.checkPermission(permission, packageName) == PackageManager.PERMISSION_GRANTED)
return true;
}
} catch (Throwable ex) {
Util.bug(null, ex);
return false;
}
return false;
}
// Helper classes
private static class CRestriction {
private long mTimestamp;
private boolean mRestricted;
public CRestriction(boolean restricted) {
mTimestamp = new Date().getTime();
mRestricted = restricted;
}
public boolean isExpired() {
return (mTimestamp + cRestrictionCacheTimeoutMs < new Date().getTime());
}
public boolean isRestricted() {
return mRestricted;
}
}
private static class CSetting {
private long mTimestamp;
private String mName;
private String mValue;
public CSetting(String name, String value) {
mTimestamp = new Date().getTime();
mName = name;
mValue = value;
}
public boolean willExpire() {
if (mName.equals(PrivacyManager.cSettingVersion))
return false;
if (mName.equals(PrivacyManager.cSettingAndroidUsage))
return false;
if (mName.equals(PrivacyManager.cSettingExperimental))
return false;
return true;
}
public boolean isExpired() {
return (willExpire() ? (mTimestamp + cSettingCacheTimeoutMs < new Date().getTime()) : false);
}
public String getSettingsValue() {
return mValue;
}
}
public static class MethodDescription implements Comparable<MethodDescription> {
private String mRestrictionName;
private String mMethodName;
private boolean mDangerous;
private boolean mRestart;
private String[] mPermissions;
private int mSdk;
private Version mFrom;
public MethodDescription(String restrictionName, String methodName) {
mRestrictionName = restrictionName;
mMethodName = methodName;
}
public MethodDescription(String restrictionName, String methodName, boolean dangerous, boolean restart,
String[] permissions, int sdk, Version from) {
mRestrictionName = restrictionName;
mMethodName = methodName;
mDangerous = dangerous;
mRestart = restart;
mPermissions = permissions;
mSdk = sdk;
mFrom = from;
}
public String getRestrictionName() {
return mRestrictionName;
}
public String getName() {
return mMethodName;
}
public boolean isDangerous() {
return mDangerous;
}
public boolean isRestartRequired() {
return mRestart;
}
@SuppressLint("FieldGetter")
public boolean hasNoUsageData() {
return isRestartRequired();
}
public String[] getPermissions() {
return mPermissions;
}
public int getSdk() {
return mSdk;
}
public Version getFrom() {
return mFrom;
}
@Override
public int hashCode() {
return (mRestrictionName.hashCode() ^ mMethodName.hashCode());
}
@Override
public boolean equals(Object obj) {
MethodDescription other = (MethodDescription) obj;
return (mRestrictionName.equals(other.mRestrictionName) && mMethodName.equals(other.mMethodName));
}
@Override
public int compareTo(MethodDescription another) {
int x = mRestrictionName.compareTo(another.mRestrictionName);
return (x == 0 ? mMethodName.compareTo(another.mMethodName) : x);
}
@Override
public String toString() {
return String.format("%s/%s", mRestrictionName, mMethodName);
}
}
public static class UsageData implements Comparable<UsageData> {
private Integer mUid;
private String mRestriction;
private String mMethodName;
private boolean mRestricted;
private long mTimeStamp;
private int mHash;
public UsageData(int uid, String restrictionName, String methodName, boolean restricted) {
initialize(uid, restrictionName, methodName, restricted, new Date().getTime());
}
public UsageData(int uid, String restrictionName, String methodName, boolean restricted, long used) {
initialize(uid, restrictionName, methodName, restricted, used);
}
private void initialize(int uid, String restrictionName, String methodName, boolean restricted, long used) {
mUid = uid;
mRestriction = restrictionName;
mMethodName = methodName;
mRestricted = restricted;
mTimeStamp = used;
mHash = mUid.hashCode();
if (mRestriction != null)
mHash = mHash ^ mRestriction.hashCode();
if (mMethodName != null)
mHash = mHash ^ mMethodName.hashCode();
}
public int getUid() {
return mUid;
}
public String getRestrictionName() {
return mRestriction;
}
public String getMethodName() {
return mMethodName;
}
public boolean getRestricted() {
return mRestricted;
}
public long getTimeStamp() {
return mTimeStamp;
}
@Override
public int hashCode() {
return mHash;
}
@Override
public boolean equals(Object obj) {
UsageData other = (UsageData) obj;
// @formatter:off
return
(mUid.equals(other.mUid) &&
(mRestriction == null ? other.mRestriction == null : mRestriction.equals(other.mRestriction)) &&
(mMethodName == null ? other.mMethodName == null : mMethodName.equals(other.mMethodName)));
// @formatter:on
}
@Override
@SuppressLint("DefaultLocale")
public String toString() {
return String.format("%d/%s/%s=%b", mUid, mRestriction, mMethodName, mRestricted);
}
@Override
public int compareTo(UsageData another) {
if (mTimeStamp < another.mTimeStamp)
return 1;
else if (mTimeStamp > another.mTimeStamp)
return -1;
else
return 0;
}
}
}
| false | true | public static Object getDefacedProp(int uid, String name) {
// Serial number
if (name.equals("SERIAL") || name.equals("%serialno")) {
String value = getSetting(null, null, uid, cSettingSerial, cDeface, true);
return (cValueRandom.equals(value) ? getRandomProp("SERIAL") : value);
}
// Host name
if (name.equals("%hostname"))
return cDeface;
// MAC addresses
if (name.equals("MAC") || name.equals("%macaddr")) {
String mac = getSetting(null, null, uid, cSettingMac, "DE:FA:CE:DE:FA:CE", true);
if (cValueRandom.equals(mac))
return getRandomProp("MAC");
StringBuilder sb = new StringBuilder(mac.replace(":", ""));
while (sb.length() != 12)
sb.insert(0, '0');
while (sb.length() > 12)
sb.deleteCharAt(sb.length() - 1);
for (int i = 10; i > 0; i -= 2)
sb.insert(i, ':');
return sb.toString();
}
// cid
if (name.equals("%cid"))
return cDeface;
// IMEI
if (name.equals("getDeviceId") || name.equals("%imei")) {
String value = getSetting(null, null, uid, cSettingImei, "000000000000000", true);
return (cValueRandom.equals(value) ? getRandomProp("IMEI") : value);
}
// Phone
if (name.equals("PhoneNumber") || name.equals("getLine1AlphaTag") || name.equals("getLine1Number")
|| name.equals("getMsisdn") || name.equals("getVoiceMailAlphaTag") || name.equals("getVoiceMailNumber")) {
String value = getSetting(null, null, uid, cSettingPhone, cDeface, true);
return (cValueRandom.equals(value) ? getRandomProp("PHONE") : value);
}
// Android ID
if (name.equals("ANDROID_ID")) {
String value = getSetting(null, null, uid, cSettingId, cDeface, true);
return (cValueRandom.equals(value) ? getRandomProp("ANDROID_ID") : value);
}
// Telephony manager
if (name.equals("getGroupIdLevel1"))
return null;
if (name.equals("getIsimDomain"))
return null;
if (name.equals("getIsimImpi"))
return null;
if (name.equals("getIsimImpu"))
return null;
if (name.equals("getNetworkCountryIso")) {
// ISO country code
String value = getSetting(null, null, uid, cSettingCountry, "XX", true);
return (cValueRandom.equals(value) ? getRandomProp("ISO3166") : value);
}
if (name.equals("getNetworkOperator")) // MCC+MNC: test network
return getSetting(null, null, uid, cSettingMcc, "001", true)
+ getSetting(null, null, uid, cSettingMnc, "01", true);
if (name.equals("getNetworkOperatorName"))
return getSetting(null, null, uid, cSettingOperator, cDeface, true);
if (name.equals("getSimCountryIso")) {
// ISO country code
String value = getSetting(null, null, uid, cSettingCountry, "XX", true);
return (cValueRandom.equals(value) ? getRandomProp("ISO3166") : value);
}
if (name.equals("getSimOperator")) // MCC+MNC: test network
return getSetting(null, null, uid, cSettingMcc, "001", true)
+ getSetting(null, null, uid, cSettingMnc, "01", true);
if (name.equals("getSimOperatorName"))
return getSetting(null, null, uid, cSettingOperator, cDeface, true);
if (name.equals("getSimSerialNumber") || name.equals("getIccSerialNumber"))
return getSetting(null, null, uid, cSettingIccId, null, true);
if (name.equals("getSubscriberId")) { // IMSI for a GSM phone
String value = getSetting(null, null, uid, cSettingSubscriber, null, true);
return (cValueRandom.equals(value) ? getRandomProp("SubscriberId") : value);
}
if (name.equals("SSID")) {
// Default hidden network
String value = getSetting(null, null, uid, cSettingSSID, "", true);
return (cValueRandom.equals(value) ? getRandomProp("SSID") : value);
}
// Google services framework ID
if (name.equals("GSF_ID")) {
long gsfid = 0xDEFACE;
try {
String value = getSetting(null, null, uid, cSettingGsfId, "DEFACE", true);
if (cValueRandom.equals(value))
value = getRandomProp(name);
gsfid = Long.parseLong(value, 16);
} catch (Throwable ex) {
Util.bug(null, ex);
}
return gsfid;
}
// Advertisement ID
if (name.equals("AdvertisingId")) {
String adid = getSetting(null, null, uid, cSettingAdId, "DEFACE00-0000-0000-0000-000000000000", true);
if (cValueRandom.equals(adid))
adid = getRandomProp(name);
return adid;
}
if (name.equals("InetAddress")) {
// Set address
String ip = getSetting(null, null, uid, cSettingIP, null, true);
if (ip != null)
try {
return InetAddress.getByName(ip);
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Any address (0.0.0.0)
try {
Field unspecified = Inet4Address.class.getDeclaredField("ANY");
unspecified.setAccessible(true);
return (InetAddress) unspecified.get(Inet4Address.class);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
if (name.equals("IPInt")) {
// Set address
String ip = getSetting(null, null, uid, cSettingIP, null, true);
if (ip != null)
try {
InetAddress inet = InetAddress.getByName(ip);
if (inet.getClass().equals(Inet4Address.class)) {
byte[] b = inet.getAddress();
return b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Any address (0.0.0.0)
return 0;
}
if (name.equals("Bytes3"))
return new byte[] { (byte) 0xDE, (byte) 0xFA, (byte) 0xCE };
if (name.equals("UA"))
return getSetting(null, null, uid, cSettingUa,
"Mozilla/5.0 (Linux; U; Android; en-us) AppleWebKit/999+ (KHTML, like Gecko) Safari/999.9", true);
// InputDevice
if (name.equals("DeviceDescriptor"))
return cDeface;
// Fallback
Util.log(null, Log.WARN, "Fallback value name=" + name);
return cDeface;
}
| public static Object getDefacedProp(int uid, String name) {
// Serial number
if (name.equals("SERIAL") || name.equals("%serialno")) {
String value = getSetting(null, null, uid, cSettingSerial, cDeface, true);
return (cValueRandom.equals(value) ? getRandomProp("SERIAL") : value);
}
// Host name
if (name.equals("%hostname"))
return cDeface;
// MAC addresses
if (name.equals("MAC") || name.equals("%macaddr")) {
String mac = getSetting(null, null, uid, cSettingMac, "DE:FA:CE:DE:FA:CE", true);
if (cValueRandom.equals(mac))
return getRandomProp("MAC");
StringBuilder sb = new StringBuilder(mac.replace(":", ""));
while (sb.length() != 12)
sb.insert(0, '0');
while (sb.length() > 12)
sb.deleteCharAt(sb.length() - 1);
for (int i = 10; i > 0; i -= 2)
sb.insert(i, ':');
return sb.toString();
}
// cid
if (name.equals("%cid"))
return cDeface;
// IMEI
if (name.equals("getDeviceId") || name.equals("%imei")) {
String value = getSetting(null, null, uid, cSettingImei, "000000000000000", true);
return (cValueRandom.equals(value) ? getRandomProp("IMEI") : value);
}
// Phone
if (name.equals("PhoneNumber") || name.equals("getLine1AlphaTag") || name.equals("getLine1Number")
|| name.equals("getMsisdn") || name.equals("getVoiceMailAlphaTag") || name.equals("getVoiceMailNumber")) {
String value = getSetting(null, null, uid, cSettingPhone, cDeface, true);
return (cValueRandom.equals(value) ? getRandomProp("PHONE") : value);
}
// Android ID
if (name.equals("ANDROID_ID")) {
String value = getSetting(null, null, uid, cSettingId, cDeface, true);
return (cValueRandom.equals(value) ? getRandomProp("ANDROID_ID") : value);
}
// Telephony manager
if (name.equals("getGroupIdLevel1"))
return null;
if (name.equals("getIsimDomain"))
return null;
if (name.equals("getIsimImpi"))
return null;
if (name.equals("getIsimImpu"))
return null;
if (name.equals("getNetworkCountryIso") || name.equals("gsm.operator.iso-country")) {
// ISO country code
String value = getSetting(null, null, uid, cSettingCountry, "XX", true);
return (cValueRandom.equals(value) ? getRandomProp("ISO3166") : value);
}
if (name.equals("getNetworkOperator") || name.equals("gsm.operator.numeric"))
// MCC+MNC: test network
return getSetting(null, null, uid, cSettingMcc, "001", true)
+ getSetting(null, null, uid, cSettingMnc, "01", true);
if (name.equals("getNetworkOperatorName") || name.equals("gsm.operator.alpha"))
return getSetting(null, null, uid, cSettingOperator, cDeface, true);
if (name.equals("getSimCountryIso") || name.equals("gsm.sim.operator.iso-country")) {
// ISO country code
String value = getSetting(null, null, uid, cSettingCountry, "XX", true);
return (cValueRandom.equals(value) ? getRandomProp("ISO3166") : value);
}
if (name.equals("getSimOperator") || name.equals("gsm.sim.operator.numeric"))
// MCC+MNC: test network
return getSetting(null, null, uid, cSettingMcc, "001", true)
+ getSetting(null, null, uid, cSettingMnc, "01", true);
if (name.equals("getSimOperatorName") || name.equals("gsm.operator.alpha"))
return getSetting(null, null, uid, cSettingOperator, cDeface, true);
if (name.equals("getSimSerialNumber") || name.equals("getIccSerialNumber"))
return getSetting(null, null, uid, cSettingIccId, null, true);
if (name.equals("getSubscriberId")) { // IMSI for a GSM phone
String value = getSetting(null, null, uid, cSettingSubscriber, null, true);
return (cValueRandom.equals(value) ? getRandomProp("SubscriberId") : value);
}
if (name.equals("SSID")) {
// Default hidden network
String value = getSetting(null, null, uid, cSettingSSID, "", true);
return (cValueRandom.equals(value) ? getRandomProp("SSID") : value);
}
// Google services framework ID
if (name.equals("GSF_ID")) {
long gsfid = 0xDEFACE;
try {
String value = getSetting(null, null, uid, cSettingGsfId, "DEFACE", true);
if (cValueRandom.equals(value))
value = getRandomProp(name);
gsfid = Long.parseLong(value, 16);
} catch (Throwable ex) {
Util.bug(null, ex);
}
return gsfid;
}
// Advertisement ID
if (name.equals("AdvertisingId")) {
String adid = getSetting(null, null, uid, cSettingAdId, "DEFACE00-0000-0000-0000-000000000000", true);
if (cValueRandom.equals(adid))
adid = getRandomProp(name);
return adid;
}
if (name.equals("InetAddress")) {
// Set address
String ip = getSetting(null, null, uid, cSettingIP, null, true);
if (ip != null)
try {
return InetAddress.getByName(ip);
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Any address (0.0.0.0)
try {
Field unspecified = Inet4Address.class.getDeclaredField("ANY");
unspecified.setAccessible(true);
return (InetAddress) unspecified.get(Inet4Address.class);
} catch (Throwable ex) {
Util.bug(null, ex);
return null;
}
}
if (name.equals("IPInt")) {
// Set address
String ip = getSetting(null, null, uid, cSettingIP, null, true);
if (ip != null)
try {
InetAddress inet = InetAddress.getByName(ip);
if (inet.getClass().equals(Inet4Address.class)) {
byte[] b = inet.getAddress();
return b[0] + (b[1] << 8) + (b[2] << 16) + (b[3] << 24);
}
} catch (Throwable ex) {
Util.bug(null, ex);
}
// Any address (0.0.0.0)
return 0;
}
if (name.equals("Bytes3"))
return new byte[] { (byte) 0xDE, (byte) 0xFA, (byte) 0xCE };
if (name.equals("UA"))
return getSetting(null, null, uid, cSettingUa,
"Mozilla/5.0 (Linux; U; Android; en-us) AppleWebKit/999+ (KHTML, like Gecko) Safari/999.9", true);
// InputDevice
if (name.equals("DeviceDescriptor"))
return cDeface;
// Fallback
Util.log(null, Log.WARN, "Fallback value name=" + name);
return cDeface;
}
|
diff --git a/src/org/fdroid/fdroid/UpdateService.java b/src/org/fdroid/fdroid/UpdateService.java
index 9d39619..2775e35 100644
--- a/src/org/fdroid/fdroid/UpdateService.java
+++ b/src/org/fdroid/fdroid/UpdateService.java
@@ -1,297 +1,301 @@
/*
* Copyright (C) 2010-12 Ciaran Gultnieks, [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, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.fdroid.fdroid;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Vector;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
public class UpdateService extends IntentService {
public UpdateService() {
super("UpdateService");
}
// Schedule (or cancel schedule for) this service, according to the
// current preferences. Should be called a) at boot, or b) if the preference
// is changed.
// TODO: What if we get upgraded?
public static void schedule(Context ctx) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(ctx);
String sint = prefs.getString("updateInterval", "0");
int interval = Integer.parseInt(sint);
Intent intent = new Intent(ctx, UpdateService.class);
PendingIntent pending = PendingIntent.getService(ctx, 0, intent, 0);
AlarmManager alarm = (AlarmManager) ctx
.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
if (interval > 0) {
alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 5000,
AlarmManager.INTERVAL_HOUR, pending);
}
}
protected void onHandleIntent(Intent intent) {
// We might be doing a scheduled run, or we might have been launched by
// the app in response to a user's request. If we get this receiver,
// it's
// the latter...
ResultReceiver receiver = intent.getParcelableExtra("receiver");
long startTime = System.currentTimeMillis();
String errmsg = "";
try {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
// See if it's time to actually do anything yet...
if (receiver == null) {
- long lastUpdate = prefs.getLong("lastUpdateCheck",
- System.currentTimeMillis());
+ long lastUpdate = prefs.getLong("lastUpdateCheck", 0);
String sint = prefs.getString("updateInterval", "0");
int interval = Integer.parseInt(sint);
- if (interval == 0)
+ if (interval == 0) {
+ Log.d("FDroid", "Skipping update - disabled");
return;
- if (lastUpdate + (interval * 60 * 60) > System
- .currentTimeMillis())
+ }
+ long elapsed = System.currentTimeMillis() - lastUpdate;
+ if (elapsed < interval * 60 * 60) {
+ Log.d("FDroid", "Skipping update - done " + elapsed
+ + "ms ago, interval is " + interval + " hours");
return;
+ }
}
boolean notify = prefs.getBoolean("updateNotify", false);
// Grab some preliminary information, then we can release the
// database while we do all the downloading, etc...
int prevUpdates = 0;
int newUpdates = 0;
Vector<DB.Repo> repos;
try {
DB db = DB.getDB();
repos = db.getRepos();
} finally {
DB.releaseDB();
}
// Process each repo...
Vector<DB.App> apps = new Vector<DB.App>();
Vector<String> keeprepos = new Vector<String>();
boolean success = true;
for (DB.Repo repo : repos) {
if (repo.inuse) {
StringBuilder newetag = new StringBuilder();
String err = RepoXMLHandler.doUpdate(getBaseContext(),
repo, apps, newetag, keeprepos);
if (err == null) {
repo.lastetag = newetag.toString();
} else {
success = false;
err = "Update failed for " + repo.address + " - " + err;
Log.d("FDroid", err);
if (errmsg.length() == 0)
errmsg = err;
else
errmsg += "\n" + err;
}
}
}
if (success) {
Vector<DB.App> acceptedapps = new Vector<DB.App>();
Vector<DB.App> prevapps = ((FDroidApp) getApplication())
.getApps();
DB db = DB.getDB();
try {
// Need to flag things we're keeping despite having received
// no data about during the update. (i.e. stuff from a repo
// that we know is unchanged due to the etag)
for (String keep : keeprepos) {
for (DB.App app : prevapps) {
boolean keepapp = false;
for (DB.Apk apk : app.apks) {
if (apk.server.equals(keep)) {
keepapp = true;
break;
}
}
if (keepapp) {
DB.App app_k = null;
for (DB.App app2 : apps) {
if (app2.id.equals(app.id)) {
app_k = app2;
break;
}
}
if (app_k == null) {
apps.add(app);
app_k = app;
}
app_k.updated = true;
if (!app_k.detail_Populated) {
db.populateDetails(app_k, keep);
}
for (DB.Apk apk : app.apks)
if (apk.server.equals(keep))
apk.updated = true;
}
}
}
prevUpdates = db.beginUpdate(prevapps);
for (DB.App app : apps) {
if (db.updateApplication(app))
acceptedapps.add(app);
}
db.endUpdate();
if (notify)
newUpdates = db.getNumUpdates();
for (DB.Repo repo : repos)
db.writeLastEtag(repo);
} catch (Exception ex) {
db.cancelUpdate();
Log.e("FDroid", "Exception during update processing:\n"
+ Log.getStackTraceString(ex));
errmsg = "Exception during processing - " + ex.getMessage();
success = false;
} finally {
DB.releaseDB();
}
if (success) {
for (DB.App app : acceptedapps)
getIcon(app);
((FDroidApp) getApplication()).invalidateApps();
}
}
if (success && notify) {
Log.d("FDroid", "Updates before:" + prevUpdates + ", after: "
+ newUpdates);
if (newUpdates > prevUpdates) {
NotificationManager n = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(
R.drawable.icon, "F-Droid Updates Available",
System.currentTimeMillis());
Context context = getApplicationContext();
CharSequence contentTitle = "F-Droid";
CharSequence contentText = "Updates are available.";
Intent notificationIntent = new Intent(UpdateService.this,
FDroid.class);
notificationIntent.putExtra(FDroid.EXTRA_TAB_UPDATE, true);
PendingIntent contentIntent = PendingIntent.getActivity(
UpdateService.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle,
contentText, contentIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
n.notify(1, notification);
}
}
if (receiver != null) {
Bundle resultData = new Bundle();
if (!success) {
if (errmsg.length() == 0)
errmsg = "Unknown error";
resultData.putString("errmsg", errmsg);
receiver.send(1, resultData);
} else {
receiver.send(0, resultData);
}
}
} catch (Exception e) {
Log.e("FDroid",
"Exception during update processing:\n"
+ Log.getStackTraceString(e));
if (receiver != null) {
Bundle resultData = new Bundle();
if (errmsg.length() == 0)
errmsg = "Unknown error";
resultData.putString("errmsg", errmsg);
receiver.send(1, resultData);
}
} finally {
Log.d("FDroid", "Update took "
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " seconds.");
}
}
private void getIcon(DB.App app) {
try {
File f = new File(DB.getIconsPath(), app.icon);
if (f.exists())
return;
if (app.apks.size() == 0)
return;
String server = app.apks.get(0).server;
URL u = new URL(server + "/icons/" + app.icon);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
if (uc.getResponseCode() == 200) {
BufferedInputStream getit = new BufferedInputStream(
uc.getInputStream());
FileOutputStream saveit = new FileOutputStream(f);
BufferedOutputStream bout = new BufferedOutputStream(saveit,
1024);
byte data[] = new byte[1024];
int readed = getit.read(data, 0, 1024);
while (readed != -1) {
bout.write(data, 0, readed);
readed = getit.read(data, 0, 1024);
}
bout.close();
getit.close();
saveit.close();
}
} catch (Exception e) {
}
}
}
| false | true | protected void onHandleIntent(Intent intent) {
// We might be doing a scheduled run, or we might have been launched by
// the app in response to a user's request. If we get this receiver,
// it's
// the latter...
ResultReceiver receiver = intent.getParcelableExtra("receiver");
long startTime = System.currentTimeMillis();
String errmsg = "";
try {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
// See if it's time to actually do anything yet...
if (receiver == null) {
long lastUpdate = prefs.getLong("lastUpdateCheck",
System.currentTimeMillis());
String sint = prefs.getString("updateInterval", "0");
int interval = Integer.parseInt(sint);
if (interval == 0)
return;
if (lastUpdate + (interval * 60 * 60) > System
.currentTimeMillis())
return;
}
boolean notify = prefs.getBoolean("updateNotify", false);
// Grab some preliminary information, then we can release the
// database while we do all the downloading, etc...
int prevUpdates = 0;
int newUpdates = 0;
Vector<DB.Repo> repos;
try {
DB db = DB.getDB();
repos = db.getRepos();
} finally {
DB.releaseDB();
}
// Process each repo...
Vector<DB.App> apps = new Vector<DB.App>();
Vector<String> keeprepos = new Vector<String>();
boolean success = true;
for (DB.Repo repo : repos) {
if (repo.inuse) {
StringBuilder newetag = new StringBuilder();
String err = RepoXMLHandler.doUpdate(getBaseContext(),
repo, apps, newetag, keeprepos);
if (err == null) {
repo.lastetag = newetag.toString();
} else {
success = false;
err = "Update failed for " + repo.address + " - " + err;
Log.d("FDroid", err);
if (errmsg.length() == 0)
errmsg = err;
else
errmsg += "\n" + err;
}
}
}
if (success) {
Vector<DB.App> acceptedapps = new Vector<DB.App>();
Vector<DB.App> prevapps = ((FDroidApp) getApplication())
.getApps();
DB db = DB.getDB();
try {
// Need to flag things we're keeping despite having received
// no data about during the update. (i.e. stuff from a repo
// that we know is unchanged due to the etag)
for (String keep : keeprepos) {
for (DB.App app : prevapps) {
boolean keepapp = false;
for (DB.Apk apk : app.apks) {
if (apk.server.equals(keep)) {
keepapp = true;
break;
}
}
if (keepapp) {
DB.App app_k = null;
for (DB.App app2 : apps) {
if (app2.id.equals(app.id)) {
app_k = app2;
break;
}
}
if (app_k == null) {
apps.add(app);
app_k = app;
}
app_k.updated = true;
if (!app_k.detail_Populated) {
db.populateDetails(app_k, keep);
}
for (DB.Apk apk : app.apks)
if (apk.server.equals(keep))
apk.updated = true;
}
}
}
prevUpdates = db.beginUpdate(prevapps);
for (DB.App app : apps) {
if (db.updateApplication(app))
acceptedapps.add(app);
}
db.endUpdate();
if (notify)
newUpdates = db.getNumUpdates();
for (DB.Repo repo : repos)
db.writeLastEtag(repo);
} catch (Exception ex) {
db.cancelUpdate();
Log.e("FDroid", "Exception during update processing:\n"
+ Log.getStackTraceString(ex));
errmsg = "Exception during processing - " + ex.getMessage();
success = false;
} finally {
DB.releaseDB();
}
if (success) {
for (DB.App app : acceptedapps)
getIcon(app);
((FDroidApp) getApplication()).invalidateApps();
}
}
if (success && notify) {
Log.d("FDroid", "Updates before:" + prevUpdates + ", after: "
+ newUpdates);
if (newUpdates > prevUpdates) {
NotificationManager n = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(
R.drawable.icon, "F-Droid Updates Available",
System.currentTimeMillis());
Context context = getApplicationContext();
CharSequence contentTitle = "F-Droid";
CharSequence contentText = "Updates are available.";
Intent notificationIntent = new Intent(UpdateService.this,
FDroid.class);
notificationIntent.putExtra(FDroid.EXTRA_TAB_UPDATE, true);
PendingIntent contentIntent = PendingIntent.getActivity(
UpdateService.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle,
contentText, contentIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
n.notify(1, notification);
}
}
if (receiver != null) {
Bundle resultData = new Bundle();
if (!success) {
if (errmsg.length() == 0)
errmsg = "Unknown error";
resultData.putString("errmsg", errmsg);
receiver.send(1, resultData);
} else {
receiver.send(0, resultData);
}
}
} catch (Exception e) {
Log.e("FDroid",
"Exception during update processing:\n"
+ Log.getStackTraceString(e));
if (receiver != null) {
Bundle resultData = new Bundle();
if (errmsg.length() == 0)
errmsg = "Unknown error";
resultData.putString("errmsg", errmsg);
receiver.send(1, resultData);
}
} finally {
Log.d("FDroid", "Update took "
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " seconds.");
}
}
| protected void onHandleIntent(Intent intent) {
// We might be doing a scheduled run, or we might have been launched by
// the app in response to a user's request. If we get this receiver,
// it's
// the latter...
ResultReceiver receiver = intent.getParcelableExtra("receiver");
long startTime = System.currentTimeMillis();
String errmsg = "";
try {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(getBaseContext());
// See if it's time to actually do anything yet...
if (receiver == null) {
long lastUpdate = prefs.getLong("lastUpdateCheck", 0);
String sint = prefs.getString("updateInterval", "0");
int interval = Integer.parseInt(sint);
if (interval == 0) {
Log.d("FDroid", "Skipping update - disabled");
return;
}
long elapsed = System.currentTimeMillis() - lastUpdate;
if (elapsed < interval * 60 * 60) {
Log.d("FDroid", "Skipping update - done " + elapsed
+ "ms ago, interval is " + interval + " hours");
return;
}
}
boolean notify = prefs.getBoolean("updateNotify", false);
// Grab some preliminary information, then we can release the
// database while we do all the downloading, etc...
int prevUpdates = 0;
int newUpdates = 0;
Vector<DB.Repo> repos;
try {
DB db = DB.getDB();
repos = db.getRepos();
} finally {
DB.releaseDB();
}
// Process each repo...
Vector<DB.App> apps = new Vector<DB.App>();
Vector<String> keeprepos = new Vector<String>();
boolean success = true;
for (DB.Repo repo : repos) {
if (repo.inuse) {
StringBuilder newetag = new StringBuilder();
String err = RepoXMLHandler.doUpdate(getBaseContext(),
repo, apps, newetag, keeprepos);
if (err == null) {
repo.lastetag = newetag.toString();
} else {
success = false;
err = "Update failed for " + repo.address + " - " + err;
Log.d("FDroid", err);
if (errmsg.length() == 0)
errmsg = err;
else
errmsg += "\n" + err;
}
}
}
if (success) {
Vector<DB.App> acceptedapps = new Vector<DB.App>();
Vector<DB.App> prevapps = ((FDroidApp) getApplication())
.getApps();
DB db = DB.getDB();
try {
// Need to flag things we're keeping despite having received
// no data about during the update. (i.e. stuff from a repo
// that we know is unchanged due to the etag)
for (String keep : keeprepos) {
for (DB.App app : prevapps) {
boolean keepapp = false;
for (DB.Apk apk : app.apks) {
if (apk.server.equals(keep)) {
keepapp = true;
break;
}
}
if (keepapp) {
DB.App app_k = null;
for (DB.App app2 : apps) {
if (app2.id.equals(app.id)) {
app_k = app2;
break;
}
}
if (app_k == null) {
apps.add(app);
app_k = app;
}
app_k.updated = true;
if (!app_k.detail_Populated) {
db.populateDetails(app_k, keep);
}
for (DB.Apk apk : app.apks)
if (apk.server.equals(keep))
apk.updated = true;
}
}
}
prevUpdates = db.beginUpdate(prevapps);
for (DB.App app : apps) {
if (db.updateApplication(app))
acceptedapps.add(app);
}
db.endUpdate();
if (notify)
newUpdates = db.getNumUpdates();
for (DB.Repo repo : repos)
db.writeLastEtag(repo);
} catch (Exception ex) {
db.cancelUpdate();
Log.e("FDroid", "Exception during update processing:\n"
+ Log.getStackTraceString(ex));
errmsg = "Exception during processing - " + ex.getMessage();
success = false;
} finally {
DB.releaseDB();
}
if (success) {
for (DB.App app : acceptedapps)
getIcon(app);
((FDroidApp) getApplication()).invalidateApps();
}
}
if (success && notify) {
Log.d("FDroid", "Updates before:" + prevUpdates + ", after: "
+ newUpdates);
if (newUpdates > prevUpdates) {
NotificationManager n = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(
R.drawable.icon, "F-Droid Updates Available",
System.currentTimeMillis());
Context context = getApplicationContext();
CharSequence contentTitle = "F-Droid";
CharSequence contentText = "Updates are available.";
Intent notificationIntent = new Intent(UpdateService.this,
FDroid.class);
notificationIntent.putExtra(FDroid.EXTRA_TAB_UPDATE, true);
PendingIntent contentIntent = PendingIntent.getActivity(
UpdateService.this, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle,
contentText, contentIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
n.notify(1, notification);
}
}
if (receiver != null) {
Bundle resultData = new Bundle();
if (!success) {
if (errmsg.length() == 0)
errmsg = "Unknown error";
resultData.putString("errmsg", errmsg);
receiver.send(1, resultData);
} else {
receiver.send(0, resultData);
}
}
} catch (Exception e) {
Log.e("FDroid",
"Exception during update processing:\n"
+ Log.getStackTraceString(e));
if (receiver != null) {
Bundle resultData = new Bundle();
if (errmsg.length() == 0)
errmsg = "Unknown error";
resultData.putString("errmsg", errmsg);
receiver.send(1, resultData);
}
} finally {
Log.d("FDroid", "Update took "
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " seconds.");
}
}
|
diff --git a/src/instructions/UIG_Arithmetic.java b/src/instructions/UIG_Arithmetic.java
index d1e9100..60be9cf 100644
--- a/src/instructions/UIG_Arithmetic.java
+++ b/src/instructions/UIG_Arithmetic.java
@@ -1,131 +1,131 @@
package instructions;
import instructions.UIG_IO.OperandType;
import assemblernator.IOFormat;
import assemblernator.Instruction;
import assemblernator.ErrorReporting.ErrorHandler;
import assemblernator.OperandChecker;
/**
* @author Eric
* @date Apr 14, 2012; 5:22:20 PM
*/
public abstract class UIG_Arithmetic extends Instruction {
String dest = "";
String src = "";
/**
* @author Eric
* @date Apr 14, 2012; 5:52:36 PM
*/
@Override
public final boolean check(ErrorHandler hErr) {
boolean isValid = true;
//any size under two is invalid
if(this.operands.size() < 2){
isValid = false;
//checks all combinations for two operands if a combo is not found operands are invalid
}else if (this.operands.size() == 2){
//checks combos associated with DM
if(this.hasOperand("DM")){
dest="DM";
if(this.hasOperand("FR")){
src="FR";
}
- if( this.hasOperand("FM")){
+ else if( this.hasOperand("FM")){
src="FM";
}
- if( this.hasOperand("FL")){
+ else if( this.hasOperand("FL")){
src="FL";
}
else{
isValid = false;
}
//checks combos associated with DR
}else if (this.hasOperand("DR")){
dest="DR";
if(this.hasOperand("FR")){
src="FR";
}
else if(this.hasOperand("FM")){
src="FM";
}
else if(this.hasOperand("FL")){
src="FL";
}
else if (this.hasOperand("FX")){
src="FX";
}else{
isValid = false;
}
//checks combos associated with DX
}else if (this.hasOperand("DX")){
dest="DX";
if(this.hasOperand("FL")){
src="FL";
}
else if (this.hasOperand("FX") ){
src="FX";
}else{
isValid = false;
}
}else{
isValid = false;
}
//checks all combinations for three operands instructions
}else if (this.operands.size() == 3){
//checks combos associated FR
if(this.hasOperand("FR")){
src="FR";
if(this.hasOperand("DM") && this.hasOperand("DX")){
dest="DMDX";
}
else{
isValid=false;
}
//checks combos associated DR
}else if(this.hasOperand("DR")){
dest="DR";
if(this.hasOperand("FX") && this.hasOperand("FM")){
src="FXFM";
}
else{
isValid=false;
}
}else{
isValid =false;
}
//more than three operands is invalid
}else{
isValid = false;
}
return isValid;
}
@Override
public final int[] assemble() {
String code = IOFormat.formatBinInteger(this.getOpcode(), 6);
if(dest == "DR"){
if(src=="FM" || src=="FL" || src=="FXFM"){
//format 0
}else{
//format 1
}
}else if(dest == "DX"){
// and so on
}
return null;
}
}
| false | true | public final boolean check(ErrorHandler hErr) {
boolean isValid = true;
//any size under two is invalid
if(this.operands.size() < 2){
isValid = false;
//checks all combinations for two operands if a combo is not found operands are invalid
}else if (this.operands.size() == 2){
//checks combos associated with DM
if(this.hasOperand("DM")){
dest="DM";
if(this.hasOperand("FR")){
src="FR";
}
if( this.hasOperand("FM")){
src="FM";
}
if( this.hasOperand("FL")){
src="FL";
}
else{
isValid = false;
}
//checks combos associated with DR
}else if (this.hasOperand("DR")){
dest="DR";
if(this.hasOperand("FR")){
src="FR";
}
else if(this.hasOperand("FM")){
src="FM";
}
else if(this.hasOperand("FL")){
src="FL";
}
else if (this.hasOperand("FX")){
src="FX";
}else{
isValid = false;
}
//checks combos associated with DX
}else if (this.hasOperand("DX")){
dest="DX";
if(this.hasOperand("FL")){
src="FL";
}
else if (this.hasOperand("FX") ){
src="FX";
}else{
isValid = false;
}
}else{
isValid = false;
}
//checks all combinations for three operands instructions
}else if (this.operands.size() == 3){
//checks combos associated FR
if(this.hasOperand("FR")){
src="FR";
if(this.hasOperand("DM") && this.hasOperand("DX")){
dest="DMDX";
}
else{
isValid=false;
}
//checks combos associated DR
}else if(this.hasOperand("DR")){
dest="DR";
if(this.hasOperand("FX") && this.hasOperand("FM")){
src="FXFM";
}
else{
isValid=false;
}
}else{
isValid =false;
}
//more than three operands is invalid
}else{
isValid = false;
}
return isValid;
}
| public final boolean check(ErrorHandler hErr) {
boolean isValid = true;
//any size under two is invalid
if(this.operands.size() < 2){
isValid = false;
//checks all combinations for two operands if a combo is not found operands are invalid
}else if (this.operands.size() == 2){
//checks combos associated with DM
if(this.hasOperand("DM")){
dest="DM";
if(this.hasOperand("FR")){
src="FR";
}
else if( this.hasOperand("FM")){
src="FM";
}
else if( this.hasOperand("FL")){
src="FL";
}
else{
isValid = false;
}
//checks combos associated with DR
}else if (this.hasOperand("DR")){
dest="DR";
if(this.hasOperand("FR")){
src="FR";
}
else if(this.hasOperand("FM")){
src="FM";
}
else if(this.hasOperand("FL")){
src="FL";
}
else if (this.hasOperand("FX")){
src="FX";
}else{
isValid = false;
}
//checks combos associated with DX
}else if (this.hasOperand("DX")){
dest="DX";
if(this.hasOperand("FL")){
src="FL";
}
else if (this.hasOperand("FX") ){
src="FX";
}else{
isValid = false;
}
}else{
isValid = false;
}
//checks all combinations for three operands instructions
}else if (this.operands.size() == 3){
//checks combos associated FR
if(this.hasOperand("FR")){
src="FR";
if(this.hasOperand("DM") && this.hasOperand("DX")){
dest="DMDX";
}
else{
isValid=false;
}
//checks combos associated DR
}else if(this.hasOperand("DR")){
dest="DR";
if(this.hasOperand("FX") && this.hasOperand("FM")){
src="FXFM";
}
else{
isValid=false;
}
}else{
isValid =false;
}
//more than three operands is invalid
}else{
isValid = false;
}
return isValid;
}
|
diff --git a/src/com/android/gallery3d/filtershow/PanelController.java b/src/com/android/gallery3d/filtershow/PanelController.java
index a852632dc..3a24d00aa 100644
--- a/src/com/android/gallery3d/filtershow/PanelController.java
+++ b/src/com/android/gallery3d/filtershow/PanelController.java
@@ -1,582 +1,583 @@
/*
* Copyright (C) 2012 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.gallery3d.filtershow;
import android.content.Context;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewPropertyAnimator;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.gallery3d.R;
import com.android.gallery3d.filtershow.editors.Editor;
import com.android.gallery3d.filtershow.filters.ImageFilter;
import com.android.gallery3d.filtershow.filters.ImageFilterTinyPlanet;
import com.android.gallery3d.filtershow.imageshow.ImageCrop;
import com.android.gallery3d.filtershow.imageshow.ImageShow;
import com.android.gallery3d.filtershow.imageshow.MasterImage;
import com.android.gallery3d.filtershow.presets.ImagePreset;
import com.android.gallery3d.filtershow.ui.FilterIconButton;
import com.android.gallery3d.filtershow.ui.FramedTextButton;
import java.util.HashMap;
import java.util.Vector;
public class PanelController implements OnClickListener {
private static int PANEL = 0;
private static int COMPONENT = 1;
private static int VERTICAL_MOVE = 0;
private static int HORIZONTAL_MOVE = 1;
private static final int ANIM_DURATION = 200;
private static final String LOGTAG = "PanelController";
private boolean mDisableFilterButtons = false;
private boolean mFixedAspect = false;
public void setFixedAspect(boolean t) {
mFixedAspect = t;
}
class Panel {
private final View mView;
private final View mContainer;
private int mPosition = 0;
private final Vector<View> mSubviews = new Vector<View>();
public Panel(View view, View container, int position) {
mView = view;
mContainer = container;
mPosition = position;
}
public void addView(View view) {
mSubviews.add(view);
}
public int getPosition() {
return mPosition;
}
public ViewPropertyAnimator unselect(int newPos, int move) {
ViewPropertyAnimator anim = mContainer.animate();
mView.setSelected(false);
mContainer.setX(0);
mContainer.setY(0);
int delta = 0;
int w = mRowPanel.getWidth();
int h = mRowPanel.getHeight();
if (move == HORIZONTAL_MOVE) {
if (newPos > mPosition) {
delta = -w;
} else {
delta = w;
}
anim.x(delta);
} else if (move == VERTICAL_MOVE) {
anim.y(h);
}
anim.setDuration(ANIM_DURATION).withLayer().withEndAction(new Runnable() {
@Override
public void run() {
mContainer.setVisibility(View.GONE);
}
});
return anim;
}
public ViewPropertyAnimator select(int oldPos, int move) {
mView.setSelected(true);
mContainer.setVisibility(View.VISIBLE);
mContainer.setX(0);
mContainer.setY(0);
ViewPropertyAnimator anim = mContainer.animate();
int w = mRowPanel.getWidth();
int h = mRowPanel.getHeight();
if (move == HORIZONTAL_MOVE) {
if (oldPos < mPosition) {
mContainer.setX(w);
} else {
mContainer.setX(-w);
}
anim.x(0);
} else if (move == VERTICAL_MOVE) {
mContainer.setY(h);
anim.y(0);
}
anim.setDuration(ANIM_DURATION).withLayer();
return anim;
}
}
class UtilityPanel {
private final Context mContext;
private final View mView;
private final LinearLayout mAccessoryViewList;
private Vector<View> mAccessoryViews = new Vector<View>();
private final TextView mTextView;
private boolean mSelected = false;
private String mEffectName = null;
private int mParameterValue = 0;
private boolean mShowParameterValue = false;
boolean firstTimeCropDisplayed = true;
public UtilityPanel(Context context, View view, View accessoryViewList,
View textView) {
mContext = context;
mView = view;
mAccessoryViewList = (LinearLayout) accessoryViewList;
mTextView = (TextView) textView;
}
public boolean selected() {
return mSelected;
}
public void hideAccessoryViews() {
int childCount = mAccessoryViewList.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = mAccessoryViewList.getChildAt(i);
child.setVisibility(View.GONE);
}
}
public void onNewValue(int value) {
mParameterValue = value;
updateText();
}
public void setEffectName(String effectName) {
mEffectName = effectName;
setShowParameter(true);
}
public void setShowParameter(boolean s) {
mShowParameterValue = s;
updateText();
}
public void updateText() {
String apply = mContext.getString(R.string.apply_effect);
if (mShowParameterValue) {
mTextView.setText(Html.fromHtml(apply + " " + mEffectName + " "
+ mParameterValue));
} else {
mTextView.setText(Html.fromHtml(apply + " " + mEffectName));
}
}
public ViewPropertyAnimator unselect() {
ViewPropertyAnimator anim = mView.animate();
mView.setX(0);
mView.setY(0);
int h = mRowPanel.getHeight();
anim.y(-h);
anim.setDuration(ANIM_DURATION).withLayer().withEndAction(new Runnable() {
@Override
public void run() {
mView.setVisibility(View.GONE);
}
});
mSelected = false;
return anim;
}
public ViewPropertyAnimator select() {
mView.setVisibility(View.VISIBLE);
int h = mRowPanel.getHeight();
mView.setX(0);
mView.setY(-h);
updateText();
ViewPropertyAnimator anim = mView.animate();
anim.y(0);
anim.setDuration(ANIM_DURATION).withLayer();
mSelected = true;
return anim;
}
}
class ViewType {
private final int mType;
private final View mView;
public ViewType(View view, int type) {
mView = view;
mType = type;
}
public int type() {
return mType;
}
}
private final HashMap<View, Panel> mPanels = new HashMap<View, Panel>();
private final HashMap<View, ViewType> mViews = new HashMap<View, ViewType>();
private final HashMap<String, ImageFilter> mFilters = new HashMap<String, ImageFilter>();
private final Vector<View> mImageViews = new Vector<View>();
private View mCurrentPanel = null;
private View mRowPanel = null;
private UtilityPanel mUtilityPanel = null;
private MasterImage mMasterImage = MasterImage.getImage();
private ImageShow mCurrentImage = null;
private Editor mCurrentEditor = null;
private FilterShowActivity mActivity = null;
private EditorPlaceHolder mEditorPlaceHolder = null;
public void setActivity(FilterShowActivity activity) {
mActivity = activity;
}
public void addView(View view) {
view.setOnClickListener(this);
mViews.put(view, new ViewType(view, COMPONENT));
}
public void addPanel(View view, View container, int position) {
mPanels.put(view, new Panel(view, container, position));
view.setOnClickListener(this);
mViews.put(view, new ViewType(view, PANEL));
}
public void addComponent(View aPanel, View component) {
Panel panel = mPanels.get(aPanel);
if (panel == null) {
return;
}
panel.addView(component);
component.setOnClickListener(this);
mViews.put(component, new ViewType(component, COMPONENT));
}
public void addFilter(ImageFilter filter) {
mFilters.put(filter.getName(), filter);
}
public void addImageView(View view) {
mImageViews.add(view);
ImageShow imageShow = (ImageShow) view;
imageShow.setPanelController(this);
}
public void resetParameters() {
showPanel(mCurrentPanel);
if (mCurrentImage != null) {
mCurrentImage.resetParameter();
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
}
}
if (mDisableFilterButtons) {
mActivity.enableFilterButtons();
mDisableFilterButtons = false;
}
}
public boolean onBackPressed() {
if (mUtilityPanel == null || !mUtilityPanel.selected()) {
return true;
}
HistoryAdapter adapter = mMasterImage.getHistory();
int position = adapter.undo();
mMasterImage.onHistoryItemClick(position);
showPanel(mCurrentPanel);
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
}
if (mDisableFilterButtons) {
mActivity.enableFilterButtons();
mActivity.resetHistory();
mDisableFilterButtons = false;
}
return false;
}
public void onNewValue(int value) {
mUtilityPanel.onNewValue(value);
}
public void showParameter(boolean s) {
mUtilityPanel.setShowParameter(s);
}
public void setCurrentPanel(View panel) {
showPanel(panel);
}
public void setRowPanel(View rowPanel) {
mRowPanel = rowPanel;
}
public void setUtilityPanel(Context context, View utilityPanel,
View accessoryViewList, View textView) {
mUtilityPanel = new UtilityPanel(context, utilityPanel,
accessoryViewList, textView);
}
@Override
public void onClick(View view) {
ViewType type = mViews.get(view);
if (type.type() == PANEL) {
showPanel(view);
} else if (type.type() == COMPONENT) {
showComponent(view);
}
}
public ImageShow showImageView(int id) {
ImageShow image = null;
mActivity.hideImageViews();
for (View view : mImageViews) {
if (view.getId() == id) {
view.setVisibility(View.VISIBLE);
image = (ImageShow) view;
} else {
view.setVisibility(View.GONE);
}
}
return image;
}
public void showDefaultImageView() {
showImageView(R.id.imageShow).setShowControls(false);
mMasterImage.setCurrentFilter(null);
mMasterImage.setCurrentFilterRepresentation(null);
}
public void showPanel(View view) {
view.setVisibility(View.VISIBLE);
boolean removedUtilityPanel = false;
Panel current = mPanels.get(mCurrentPanel);
if (mUtilityPanel != null && mUtilityPanel.selected()) {
ViewPropertyAnimator anim1 = mUtilityPanel.unselect();
removedUtilityPanel = true;
anim1.start();
if (mCurrentPanel == view) {
ViewPropertyAnimator anim2 = current.select(-1, VERTICAL_MOVE);
anim2.start();
showDefaultImageView();
}
}
if (mCurrentPanel == view) {
return;
}
Panel panel = mPanels.get(view);
if (!removedUtilityPanel) {
int currentPos = -1;
if (current != null) {
currentPos = current.getPosition();
}
ViewPropertyAnimator anim1 = panel.select(currentPos, HORIZONTAL_MOVE);
anim1.start();
if (current != null) {
ViewPropertyAnimator anim2 = current.unselect(panel.getPosition(), HORIZONTAL_MOVE);
anim2.start();
}
} else {
ViewPropertyAnimator anim = panel.select(-1, VERTICAL_MOVE);
anim.start();
}
showDefaultImageView();
mCurrentPanel = view;
}
public ImagePreset getImagePreset() {
return mMasterImage.getPreset();
}
/**
public ImageFilter setImagePreset(ImageFilter filter, String name) {
ImagePreset copy = new ImagePreset(getImagePreset());
copy.add(filter);
copy.setHistoryName(name);
copy.setIsFx(false);
mMasterImage.setPreset(copy, true);
return filter;
}
*/
// TODO: remove this.
public void ensureFilter(String name) {
/*
ImagePreset preset = getImagePreset();
ImageFilter filter = preset.getFilter(name);
if (filter != null) {
// If we already have a filter, we might still want
// to push it onto the history stack.
ImagePreset copy = new ImagePreset(getImagePreset());
copy.setHistoryName(name);
mMasterImage.setPreset(copy, true);
filter = copy.getFilter(name);
}
if (filter == null) {
ImageFilter filterInstance = mFilters.get(name);
if (filterInstance != null) {
try {
ImageFilter newFilter = filterInstance.clone();
newFilter.reset();
filter = setImagePreset(newFilter, name);
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
if (filter != null) {
mMasterImage.setCurrentFilter(filter);
}
*/
}
public void showComponent(View view) {
boolean doPanelTransition = true;
if (view instanceof FilterIconButton) {
ImageFilter f = ((FilterIconButton) view).getImageFilter();
doPanelTransition = f.showUtilityPanel();
}
if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) {
Panel current = mPanels.get(mCurrentPanel);
ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE);
anim1.start();
if (mUtilityPanel != null) {
ViewPropertyAnimator anim2 = mUtilityPanel.select();
anim2.start();
}
}
if (mCurrentImage != null) {
mCurrentImage.unselect();
}
mUtilityPanel.hideAccessoryViews();
if (view instanceof FilterIconButton) {
mCurrentEditor = null;
FilterIconButton component = (FilterIconButton) view;
ImageFilter filter = component.getImageFilter();
if (filter.getEditingViewId() != 0) {
if (mEditorPlaceHolder.contains(filter.getEditingViewId())) {
mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId());
mCurrentImage = mCurrentEditor.getImageShow();
mCurrentEditor.setPanelController(this);
} else {
mCurrentImage = showImageView(filter.getEditingViewId());
}
mCurrentImage.setShowControls(filter.showEditingControls());
String ename = mCurrentImage.getContext().getString(filter.getTextId());
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(filter.showParameterValue());
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
return;
}
switch (view.getId()) {
case R.id.tinyplanetButton: {
mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.tinyplanet);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
if (!mDisableFilterButtons) {
mActivity.disableFilterButtons();
mDisableFilterButtons = true;
}
break;
}
case R.id.straightenButton: {
mCurrentImage = showImageView(R.id.imageStraighten);
String ename = mCurrentImage.getContext().getString(R.string.straighten);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.cropButton: {
mCurrentImage = showImageView(R.id.imageCrop);
String ename = mCurrentImage.getContext().getString(R.string.crop);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) {
((ImageCrop) mCurrentImage).clear();
mUtilityPanel.firstTimeCropDisplayed = false;
}
((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect);
break;
}
case R.id.rotateButton: {
mCurrentImage = showImageView(R.id.imageRotate);
String ename = mCurrentImage.getContext().getString(R.string.rotate);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.flipButton: {
mCurrentImage = showImageView(R.id.imageFlip);
String ename = mCurrentImage.getContext().getString(R.string.mirror);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
break;
}
case R.id.redEyeButton: {
mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.redeye);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
break;
}
case R.id.applyEffect: {
if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) {
mActivity.saveImage();
} else {
if (mCurrentImage instanceof ImageCrop) {
((ImageCrop) mCurrentImage).saveAndSetPreset();
}
showPanel(mCurrentPanel);
}
+ MasterImage.getImage().invalidateFiltersOnly();
break;
}
}
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
public void setEditorPlaceHolder(EditorPlaceHolder editorPlaceHolder) {
mEditorPlaceHolder = editorPlaceHolder;
}
}
| true | true | public void showComponent(View view) {
boolean doPanelTransition = true;
if (view instanceof FilterIconButton) {
ImageFilter f = ((FilterIconButton) view).getImageFilter();
doPanelTransition = f.showUtilityPanel();
}
if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) {
Panel current = mPanels.get(mCurrentPanel);
ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE);
anim1.start();
if (mUtilityPanel != null) {
ViewPropertyAnimator anim2 = mUtilityPanel.select();
anim2.start();
}
}
if (mCurrentImage != null) {
mCurrentImage.unselect();
}
mUtilityPanel.hideAccessoryViews();
if (view instanceof FilterIconButton) {
mCurrentEditor = null;
FilterIconButton component = (FilterIconButton) view;
ImageFilter filter = component.getImageFilter();
if (filter.getEditingViewId() != 0) {
if (mEditorPlaceHolder.contains(filter.getEditingViewId())) {
mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId());
mCurrentImage = mCurrentEditor.getImageShow();
mCurrentEditor.setPanelController(this);
} else {
mCurrentImage = showImageView(filter.getEditingViewId());
}
mCurrentImage.setShowControls(filter.showEditingControls());
String ename = mCurrentImage.getContext().getString(filter.getTextId());
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(filter.showParameterValue());
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
return;
}
switch (view.getId()) {
case R.id.tinyplanetButton: {
mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.tinyplanet);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
if (!mDisableFilterButtons) {
mActivity.disableFilterButtons();
mDisableFilterButtons = true;
}
break;
}
case R.id.straightenButton: {
mCurrentImage = showImageView(R.id.imageStraighten);
String ename = mCurrentImage.getContext().getString(R.string.straighten);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.cropButton: {
mCurrentImage = showImageView(R.id.imageCrop);
String ename = mCurrentImage.getContext().getString(R.string.crop);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) {
((ImageCrop) mCurrentImage).clear();
mUtilityPanel.firstTimeCropDisplayed = false;
}
((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect);
break;
}
case R.id.rotateButton: {
mCurrentImage = showImageView(R.id.imageRotate);
String ename = mCurrentImage.getContext().getString(R.string.rotate);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.flipButton: {
mCurrentImage = showImageView(R.id.imageFlip);
String ename = mCurrentImage.getContext().getString(R.string.mirror);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
break;
}
case R.id.redEyeButton: {
mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.redeye);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
break;
}
case R.id.applyEffect: {
if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) {
mActivity.saveImage();
} else {
if (mCurrentImage instanceof ImageCrop) {
((ImageCrop) mCurrentImage).saveAndSetPreset();
}
showPanel(mCurrentPanel);
}
break;
}
}
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
| public void showComponent(View view) {
boolean doPanelTransition = true;
if (view instanceof FilterIconButton) {
ImageFilter f = ((FilterIconButton) view).getImageFilter();
doPanelTransition = f.showUtilityPanel();
}
if (mUtilityPanel != null && !mUtilityPanel.selected() && doPanelTransition ) {
Panel current = mPanels.get(mCurrentPanel);
ViewPropertyAnimator anim1 = current.unselect(-1, VERTICAL_MOVE);
anim1.start();
if (mUtilityPanel != null) {
ViewPropertyAnimator anim2 = mUtilityPanel.select();
anim2.start();
}
}
if (mCurrentImage != null) {
mCurrentImage.unselect();
}
mUtilityPanel.hideAccessoryViews();
if (view instanceof FilterIconButton) {
mCurrentEditor = null;
FilterIconButton component = (FilterIconButton) view;
ImageFilter filter = component.getImageFilter();
if (filter.getEditingViewId() != 0) {
if (mEditorPlaceHolder.contains(filter.getEditingViewId())) {
mCurrentEditor = mEditorPlaceHolder.showEditor(filter.getEditingViewId());
mCurrentImage = mCurrentEditor.getImageShow();
mCurrentEditor.setPanelController(this);
} else {
mCurrentImage = showImageView(filter.getEditingViewId());
}
mCurrentImage.setShowControls(filter.showEditingControls());
String ename = mCurrentImage.getContext().getString(filter.getTextId());
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(filter.showParameterValue());
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
return;
}
switch (view.getId()) {
case R.id.tinyplanetButton: {
mCurrentImage = showImageView(R.id.imageTinyPlanet).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.tinyplanet);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
if (!mDisableFilterButtons) {
mActivity.disableFilterButtons();
mDisableFilterButtons = true;
}
break;
}
case R.id.straightenButton: {
mCurrentImage = showImageView(R.id.imageStraighten);
String ename = mCurrentImage.getContext().getString(R.string.straighten);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.cropButton: {
mCurrentImage = showImageView(R.id.imageCrop);
String ename = mCurrentImage.getContext().getString(R.string.crop);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
if (mCurrentImage instanceof ImageCrop && mUtilityPanel.firstTimeCropDisplayed) {
((ImageCrop) mCurrentImage).clear();
mUtilityPanel.firstTimeCropDisplayed = false;
}
((ImageCrop) mCurrentImage).setFixedAspect(mFixedAspect);
break;
}
case R.id.rotateButton: {
mCurrentImage = showImageView(R.id.imageRotate);
String ename = mCurrentImage.getContext().getString(R.string.rotate);
mUtilityPanel.setEffectName(ename);
break;
}
case R.id.flipButton: {
mCurrentImage = showImageView(R.id.imageFlip);
String ename = mCurrentImage.getContext().getString(R.string.mirror);
mUtilityPanel.setEffectName(ename);
mUtilityPanel.setShowParameter(false);
break;
}
case R.id.redEyeButton: {
mCurrentImage = showImageView(R.id.imageRedEyes).setShowControls(true);
String ename = mCurrentImage.getContext().getString(R.string.redeye);
mUtilityPanel.setEffectName(ename);
ensureFilter(ename);
break;
}
case R.id.applyEffect: {
if (mMasterImage.getCurrentFilter() instanceof ImageFilterTinyPlanet) {
mActivity.saveImage();
} else {
if (mCurrentImage instanceof ImageCrop) {
((ImageCrop) mCurrentImage).saveAndSetPreset();
}
showPanel(mCurrentPanel);
}
MasterImage.getImage().invalidateFiltersOnly();
break;
}
}
mCurrentImage.select();
if (mCurrentEditor != null) {
mCurrentEditor.reflectCurrentFilter();
if (mCurrentEditor.useUtilityPanel()) {
mCurrentEditor.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
} else if (mCurrentImage.useUtilityPanel()) {
mCurrentImage.openUtilityPanel(mUtilityPanel.mAccessoryViewList);
}
}
|
diff --git a/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/MyResource.java b/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/MyResource.java
index 67d7281d..7b59f654 100644
--- a/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/MyResource.java
+++ b/jaxrs/client-negotiation/src/main/java/org/javaee7/jaxrs/client/negotiation/MyResource.java
@@ -1,61 +1,61 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.javaee7.jaxrs.client.negotiation;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
/**
* @author Arun Gupta
*/
@Path("persons")
public class MyResource {
@GET
@Produces({"application/xml", "application/json"})
public Person[] getList() {
Person[] list = new Person[3];
list[0] = new Person("Penny", 1);
- list[1] = new Person("Howard", 2);
+ list[1] = new Person("Leonard", 2);
list[2] = new Person("Sheldon", 3);
return list;
}
}
| true | true | public Person[] getList() {
Person[] list = new Person[3];
list[0] = new Person("Penny", 1);
list[1] = new Person("Howard", 2);
list[2] = new Person("Sheldon", 3);
return list;
}
| public Person[] getList() {
Person[] list = new Person[3];
list[0] = new Person("Penny", 1);
list[1] = new Person("Leonard", 2);
list[2] = new Person("Sheldon", 3);
return list;
}
|
diff --git a/org.eclipse.riena.core/src/org/eclipse/riena/core/extension/InterfaceBeanHandler.java b/org.eclipse.riena.core/src/org/eclipse/riena/core/extension/InterfaceBeanHandler.java
index 2956cee8b..4c1a7334a 100644
--- a/org.eclipse.riena.core/src/org/eclipse/riena/core/extension/InterfaceBeanHandler.java
+++ b/org.eclipse.riena.core/src/org/eclipse/riena/core/extension/InterfaceBeanHandler.java
@@ -1,317 +1,317 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 compeople AG 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:
* compeople AG - initial API and implementation
*******************************************************************************/
package org.eclipse.riena.core.extension;
import static org.eclipse.riena.core.extension.InterfaceBeanHandler.MethodKind.OTHER;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.ContributorFactoryOSGi;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.variables.IStringVariableManager;
import org.eclipse.core.variables.VariablesPlugin;
import org.eclipse.equinox.log.Logger;
import org.eclipse.riena.internal.core.Activator;
import org.osgi.framework.Bundle;
import org.osgi.service.log.LogService;
/**
* InvocationHandler for proxies that map to configuration elements.
*/
final class InterfaceBeanHandler implements InvocationHandler {
private final Class<?> interfaceType;
private final IConfigurationElement configurationElement;
private final boolean symbolReplace;
private final Map<Method, Result> resolved;
private final static Logger LOGGER = Activator.getDefault().getLogger(InterfaceBeanHandler.class);
InterfaceBeanHandler(final Class<?> interfaceType, final boolean symbolReplace,
final IConfigurationElement configurationElement) {
this.interfaceType = interfaceType;
this.configurationElement = configurationElement;
this.symbolReplace = symbolReplace;
this.resolved = new HashMap<Method, Result>();
if (!interfaceType.isAnnotationPresent(ExtensionInterface.class)) {
LOGGER.log(LogService.LOG_WARNING, "The interface '" + interfaceType.getName() //$NON-NLS-1$
+ "' is NOT annotated with @" + ExtensionInterface.class.getSimpleName() + " but it should!"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
/*
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object,
* java.lang.reflect.Method, java.lang.Object[])
*/
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
final MethodKind methodKind = MethodKind.of(method);
synchronized (resolved) {
Result result = resolved.get(method);
if (result == null) {
result = invoke(method, args, methodKind);
if (result.cash) {
resolved.put(method, result);
}
}
return result.object;
}
}
private Result invoke(final Method method, final Object[] args, final MethodKind methodKind) throws Throwable {
if (method.getParameterTypes().length == 0) {
if (method.getName().equals("toString")) { //$NON-NLS-1$
return Result.cache(proxiedToString());
} else if (method.getName().equals("hashCode")) { //$NON-NLS-1$
return Result.cache(proxiedHashCode());
}
}
if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == Object.class
&& method.getName().equals("equals")) { //$NON-NLS-1$
return Result.noCache(proxiedEquals(args[0]));
}
final Class<?> returnType = method.getReturnType();
final String name = getAttributeName(method, methodKind);
if (returnType == String.class) {
- return Result.cache(modify(method.isAnnotationPresent(MapContent.class) ? configurationElement.getValue()
+ return Result.noCache(modify(method.isAnnotationPresent(MapContent.class) ? configurationElement.getValue()
: configurationElement.getAttribute(name)));
}
if (returnType.isPrimitive()) {
- return Result.cache(coerce(returnType, modify(configurationElement.getAttribute(name))));
+ return Result.noCache(coerce(returnType, modify(configurationElement.getAttribute(name))));
}
if (returnType == Bundle.class) {
return Result.cache(ContributorFactoryOSGi.resolve(configurationElement.getContributor()));
}
if (returnType == Class.class) {
String value = configurationElement.getAttribute(name);
if (value == null) {
return Result.CACHED_NULL;
}
Bundle bundle = ContributorFactoryOSGi.resolve(configurationElement.getContributor());
if (bundle == null) {
return Result.CACHED_NULL;
}
// does it contain initialization data?
int colon = value.indexOf(':');
if (colon != -1) {
value = value.substring(0, colon);
}
return Result.cache(bundle.loadClass(value));
}
if (returnType.isInterface() && returnType.isAnnotationPresent(ExtensionInterface.class)) {
final IConfigurationElement[] cfgElements = configurationElement.getChildren(name);
if (cfgElements.length == 0) {
return Result.CACHED_NULL;
}
if (cfgElements.length == 1) {
return Result.cache(Proxy.newProxyInstance(returnType.getClassLoader(), new Class[] { returnType },
new InterfaceBeanHandler(returnType, symbolReplace, cfgElements[0])));
}
throw new IllegalStateException(
"Got more than one configuration element but the interface expected exactly one, .i.e no array type has been specified for: " //$NON-NLS-1$
+ method);
}
if (returnType.isArray() && returnType.getComponentType().isInterface()) {
final IConfigurationElement[] cfgElements = configurationElement.getChildren(name);
final Object[] result = (Object[]) Array.newInstance(returnType.getComponentType(), cfgElements.length);
for (int i = 0; i < cfgElements.length; i++) {
result[i] = Proxy.newProxyInstance(returnType.getComponentType().getClassLoader(),
new Class[] { returnType.getComponentType() }, new InterfaceBeanHandler(returnType
.getComponentType(), symbolReplace, cfgElements[i]));
}
return Result.cache(result);
}
if (method.getReturnType() == Void.class || (args != null && args.length > 0)) {
throw new UnsupportedOperationException("Can not handle method '" + method + "' in '" //$NON-NLS-1$ //$NON-NLS-2$
+ interfaceType.getName() + "'."); //$NON-NLS-1$
}
// Now try to create a fresh instance,i.e.
// createExecutableExtension() ()
if (configurationElement.getAttribute(name) == null) {
return Result.CACHED_NULL;
}
if (method.isAnnotationPresent(CreateLazy.class)) {
return Result.noCache(LazyExecutableExtension.newInstance(configurationElement, name));
}
return Result.noCache(configurationElement.createExecutableExtension(name));
}
/*
*
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean proxiedEquals(final Object obj) {
try {
InvocationHandler handler = Proxy.getInvocationHandler(obj);
if (handler instanceof InterfaceBeanHandler) {
return configurationElement.equals(((InterfaceBeanHandler) handler).configurationElement);
}
} catch (IllegalArgumentException e) {
// fall thru
}
return false;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
public int proxiedHashCode() {
return configurationElement.hashCode();
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String proxiedToString() {
final StringBuilder bob = new StringBuilder("Dynamic proxy for "); //$NON-NLS-1$
bob.append(interfaceType.getName()).append(':');
final String[] names = configurationElement.getAttributeNames();
for (String name : names) {
bob.append(name).append('=').append(configurationElement.getAttribute(name)).append(',');
}
bob.setLength(bob.length() - 1);
return bob.toString();
}
private String getAttributeName(final Method method, final MethodKind methodKind) {
final Annotation annotation = method.getAnnotation(MapName.class);
if (annotation != null) {
return ((MapName) annotation).value();
}
// No annotations
if (methodKind == OTHER) {
return null;
}
final String name = method.getName().substring(methodKind.prefix.length());
return name.substring(0, 1).toLowerCase() + name.substring(1);
}
private Object coerce(final Class<?> toType, final String value) {
if (toType == Long.TYPE) {
return Long.valueOf(value);
}
if (toType == Integer.TYPE) {
return Integer.valueOf(value);
}
if (toType == Boolean.TYPE) {
return Boolean.valueOf(value);
}
if (toType == Float.TYPE) {
return Float.valueOf(value);
}
if (toType == Double.TYPE) {
return Double.valueOf(value);
}
if (toType == Short.TYPE) {
return Short.valueOf(value);
}
if (toType == Character.TYPE) {
return Character.valueOf(value.charAt(0));
}
if (toType == Byte.TYPE) {
return Byte.valueOf(value);
}
return value;
}
private String modify(final String value) {
if (!symbolReplace || value == null) {
return value;
}
IStringVariableManager variableManager = VariablesPlugin.getDefault().getStringVariableManager();
if (variableManager == null) {
return value;
}
try {
return variableManager.performStringSubstitution(value);
} catch (CoreException e) {
LOGGER.log(LogService.LOG_ERROR, "Could not perfrom string substitution for '" + value + "' .", e); //$NON-NLS-1$ //$NON-NLS-2$
return value;
}
}
private final static class Result {
private final Object object;
private final boolean cash;
private static final Result CACHED_NULL = Result.cache(null);
private static Result noCache(final Object object) {
return new Result(object, false);
}
private static Result cache(final Object object) {
return new Result(object, true);
}
private Result(final Object object, final boolean cash) {
this.object = object;
this.cash = cash;
}
}
enum MethodKind {
GET("get"), IS("is"), CREATE("create"), OTHER; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
private final String prefix;
private MethodKind(final String kind) {
this.prefix = kind;
}
private MethodKind() {
this.prefix = null;
}
/**
* @param method
* @return
*/
private static MethodKind of(final Method method) {
final String name = method.getName();
if (name.startsWith(GET.prefix)) {
return GET;
} else if (name.startsWith(IS.prefix)) {
return IS;
} else if (name.startsWith(CREATE.prefix)) {
return CREATE;
}
return OTHER;
}
/*
* (non-Javadoc)
*
* @see java.lang.Enum#toString()
*/
@Override
public String toString() {
return prefix;
}
}
}
| false | true | private Result invoke(final Method method, final Object[] args, final MethodKind methodKind) throws Throwable {
if (method.getParameterTypes().length == 0) {
if (method.getName().equals("toString")) { //$NON-NLS-1$
return Result.cache(proxiedToString());
} else if (method.getName().equals("hashCode")) { //$NON-NLS-1$
return Result.cache(proxiedHashCode());
}
}
if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == Object.class
&& method.getName().equals("equals")) { //$NON-NLS-1$
return Result.noCache(proxiedEquals(args[0]));
}
final Class<?> returnType = method.getReturnType();
final String name = getAttributeName(method, methodKind);
if (returnType == String.class) {
return Result.cache(modify(method.isAnnotationPresent(MapContent.class) ? configurationElement.getValue()
: configurationElement.getAttribute(name)));
}
if (returnType.isPrimitive()) {
return Result.cache(coerce(returnType, modify(configurationElement.getAttribute(name))));
}
if (returnType == Bundle.class) {
return Result.cache(ContributorFactoryOSGi.resolve(configurationElement.getContributor()));
}
if (returnType == Class.class) {
String value = configurationElement.getAttribute(name);
if (value == null) {
return Result.CACHED_NULL;
}
Bundle bundle = ContributorFactoryOSGi.resolve(configurationElement.getContributor());
if (bundle == null) {
return Result.CACHED_NULL;
}
// does it contain initialization data?
int colon = value.indexOf(':');
if (colon != -1) {
value = value.substring(0, colon);
}
return Result.cache(bundle.loadClass(value));
}
if (returnType.isInterface() && returnType.isAnnotationPresent(ExtensionInterface.class)) {
final IConfigurationElement[] cfgElements = configurationElement.getChildren(name);
if (cfgElements.length == 0) {
return Result.CACHED_NULL;
}
if (cfgElements.length == 1) {
return Result.cache(Proxy.newProxyInstance(returnType.getClassLoader(), new Class[] { returnType },
new InterfaceBeanHandler(returnType, symbolReplace, cfgElements[0])));
}
throw new IllegalStateException(
"Got more than one configuration element but the interface expected exactly one, .i.e no array type has been specified for: " //$NON-NLS-1$
+ method);
}
if (returnType.isArray() && returnType.getComponentType().isInterface()) {
final IConfigurationElement[] cfgElements = configurationElement.getChildren(name);
final Object[] result = (Object[]) Array.newInstance(returnType.getComponentType(), cfgElements.length);
for (int i = 0; i < cfgElements.length; i++) {
result[i] = Proxy.newProxyInstance(returnType.getComponentType().getClassLoader(),
new Class[] { returnType.getComponentType() }, new InterfaceBeanHandler(returnType
.getComponentType(), symbolReplace, cfgElements[i]));
}
return Result.cache(result);
}
if (method.getReturnType() == Void.class || (args != null && args.length > 0)) {
throw new UnsupportedOperationException("Can not handle method '" + method + "' in '" //$NON-NLS-1$ //$NON-NLS-2$
+ interfaceType.getName() + "'."); //$NON-NLS-1$
}
// Now try to create a fresh instance,i.e.
// createExecutableExtension() ()
if (configurationElement.getAttribute(name) == null) {
return Result.CACHED_NULL;
}
if (method.isAnnotationPresent(CreateLazy.class)) {
return Result.noCache(LazyExecutableExtension.newInstance(configurationElement, name));
}
return Result.noCache(configurationElement.createExecutableExtension(name));
}
| private Result invoke(final Method method, final Object[] args, final MethodKind methodKind) throws Throwable {
if (method.getParameterTypes().length == 0) {
if (method.getName().equals("toString")) { //$NON-NLS-1$
return Result.cache(proxiedToString());
} else if (method.getName().equals("hashCode")) { //$NON-NLS-1$
return Result.cache(proxiedHashCode());
}
}
if (method.getParameterTypes().length == 1 && method.getParameterTypes()[0] == Object.class
&& method.getName().equals("equals")) { //$NON-NLS-1$
return Result.noCache(proxiedEquals(args[0]));
}
final Class<?> returnType = method.getReturnType();
final String name = getAttributeName(method, methodKind);
if (returnType == String.class) {
return Result.noCache(modify(method.isAnnotationPresent(MapContent.class) ? configurationElement.getValue()
: configurationElement.getAttribute(name)));
}
if (returnType.isPrimitive()) {
return Result.noCache(coerce(returnType, modify(configurationElement.getAttribute(name))));
}
if (returnType == Bundle.class) {
return Result.cache(ContributorFactoryOSGi.resolve(configurationElement.getContributor()));
}
if (returnType == Class.class) {
String value = configurationElement.getAttribute(name);
if (value == null) {
return Result.CACHED_NULL;
}
Bundle bundle = ContributorFactoryOSGi.resolve(configurationElement.getContributor());
if (bundle == null) {
return Result.CACHED_NULL;
}
// does it contain initialization data?
int colon = value.indexOf(':');
if (colon != -1) {
value = value.substring(0, colon);
}
return Result.cache(bundle.loadClass(value));
}
if (returnType.isInterface() && returnType.isAnnotationPresent(ExtensionInterface.class)) {
final IConfigurationElement[] cfgElements = configurationElement.getChildren(name);
if (cfgElements.length == 0) {
return Result.CACHED_NULL;
}
if (cfgElements.length == 1) {
return Result.cache(Proxy.newProxyInstance(returnType.getClassLoader(), new Class[] { returnType },
new InterfaceBeanHandler(returnType, symbolReplace, cfgElements[0])));
}
throw new IllegalStateException(
"Got more than one configuration element but the interface expected exactly one, .i.e no array type has been specified for: " //$NON-NLS-1$
+ method);
}
if (returnType.isArray() && returnType.getComponentType().isInterface()) {
final IConfigurationElement[] cfgElements = configurationElement.getChildren(name);
final Object[] result = (Object[]) Array.newInstance(returnType.getComponentType(), cfgElements.length);
for (int i = 0; i < cfgElements.length; i++) {
result[i] = Proxy.newProxyInstance(returnType.getComponentType().getClassLoader(),
new Class[] { returnType.getComponentType() }, new InterfaceBeanHandler(returnType
.getComponentType(), symbolReplace, cfgElements[i]));
}
return Result.cache(result);
}
if (method.getReturnType() == Void.class || (args != null && args.length > 0)) {
throw new UnsupportedOperationException("Can not handle method '" + method + "' in '" //$NON-NLS-1$ //$NON-NLS-2$
+ interfaceType.getName() + "'."); //$NON-NLS-1$
}
// Now try to create a fresh instance,i.e.
// createExecutableExtension() ()
if (configurationElement.getAttribute(name) == null) {
return Result.CACHED_NULL;
}
if (method.isAnnotationPresent(CreateLazy.class)) {
return Result.noCache(LazyExecutableExtension.newInstance(configurationElement, name));
}
return Result.noCache(configurationElement.createExecutableExtension(name));
}
|
diff --git a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ControlEvaluationsProducer.java b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ControlEvaluationsProducer.java
index 7c46f085..048decdc 100644
--- a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ControlEvaluationsProducer.java
+++ b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ControlEvaluationsProducer.java
@@ -1,486 +1,487 @@
/******************************************************************************
* ControlEvaluationsProducer.java - created by [email protected] on Mar 19, 2007
*
* Copyright (c) 2007 Virginia Polytechnic Institute and State University
* Licensed under the Educational Community License version 1.0
*
* A copy of the Educational Community License has been included in this
* distribution and is available at: http://www.opensource.org/licenses/ecl1.php
*
* Contributors:
* Aaron Zeckoski ([email protected]) - primary
*
*****************************************************************************/
package org.sakaiproject.evaluation.tool.producers;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.sakaiproject.evaluation.logic.EvalEvaluationsLogic;
import org.sakaiproject.evaluation.logic.EvalExternalLogic;
import org.sakaiproject.evaluation.logic.EvalResponsesLogic;
import org.sakaiproject.evaluation.logic.EvalSettings;
import org.sakaiproject.evaluation.logic.EvalTemplatesLogic;
import org.sakaiproject.evaluation.logic.entity.EvalCategoryEntityProvider;
import org.sakaiproject.evaluation.logic.utils.EvalUtils;
import org.sakaiproject.evaluation.model.EvalAssignGroup;
import org.sakaiproject.evaluation.model.EvalEvaluation;
import org.sakaiproject.evaluation.model.constant.EvalConstants;
import org.sakaiproject.evaluation.tool.viewparams.PreviewEvalParameters;
import org.sakaiproject.evaluation.tool.viewparams.ReportParameters;
import org.sakaiproject.evaluation.tool.viewparams.TemplateViewParameters;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.components.UILink;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.decorators.DecoratorList;
import uk.org.ponder.rsf.components.decorators.UITooltipDecorator;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParameters;
/**
* This lists evaluations for users so they can add, modify, remove them
*
* @author Aaron Zeckoski ([email protected])
*/
public class ControlEvaluationsProducer implements ViewComponentProducer, NavigationCaseReporter {
/* (non-Javadoc)
* @see uk.org.ponder.rsf.view.ViewComponentProducer#getViewID()
*/
public static String VIEW_ID = "control_evaluations";
public String getViewID() {
return VIEW_ID;
}
private Locale locale;
public void setLocale(Locale locale) {
this.locale = locale;
}
private EvalExternalLogic externalLogic;
public void setExternalLogic(EvalExternalLogic externalLogic) {
this.externalLogic = externalLogic;
}
private EvalEvaluationsLogic evaluationsLogic;
public void setEvaluationsLogic(EvalEvaluationsLogic evaluationsLogic) {
this.evaluationsLogic = evaluationsLogic;
}
private EvalTemplatesLogic templatesLogic;
public void setTemplatesLogic(EvalTemplatesLogic templatesLogic) {
this.templatesLogic = templatesLogic;
}
private EvalResponsesLogic responsesLogic;
public void setResponsesLogic(EvalResponsesLogic responsesLogic) {
this.responsesLogic = responsesLogic;
}
private EvalSettings settings;
public void setSettings(EvalSettings settings) {
this.settings = settings;
}
/* (non-Javadoc)
* @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, uk.org.ponder.rsf.viewstate.ViewParameters, uk.org.ponder.rsf.view.ComponentChecker)
*/
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
// local variables used in the render logic
String currentUserId = externalLogic.getCurrentUserId();
boolean userAdmin = externalLogic.isUserAdmin(currentUserId);
boolean createTemplate = templatesLogic.canCreateTemplate(currentUserId);
boolean beginEvaluation = evaluationsLogic.canBeginEvaluation(currentUserId);
// use a date which is related to the current users locale
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
// page title
UIMessage.make(tofill, "page-title", "controlevaluations.page.title");
/*
* top links here
*/
UIInternalLink.make(tofill, "summary-link",
UIMessage.make("summary.page.title"),
new SimpleViewParameters(SummaryProducer.VIEW_ID));
if (userAdmin) {
UIInternalLink.make(tofill, "administrate-link",
UIMessage.make("administrate.page.title"),
new SimpleViewParameters(AdministrateProducer.VIEW_ID));
}
if (createTemplate) {
UIInternalLink.make(tofill, "control-templates-link",
UIMessage.make("controltemplates.page.title"),
new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID));
UIInternalLink.make(tofill, "control-items-link",
UIMessage.make("controlitems.page.title"),
new SimpleViewParameters(ControlItemsProducer.VIEW_ID));
}
if (!beginEvaluation) {
throw new SecurityException("User attempted to access " +
ControlEvaluationsProducer.VIEW_ID + " when they are not allowed");
}
// get all the visible evaluations for the current user
List inqueueEvals = new ArrayList();
List activeEvals = new ArrayList();
List closedEvals = new ArrayList();
List evals = evaluationsLogic.getVisibleEvaluationsForUser(externalLogic.getCurrentUserId(), false, false);
for (int j = 0; j < evals.size(); j++) {
// get queued, active, closed evaluations by date
// check the state of the eval to determine display data
EvalEvaluation eval = (EvalEvaluation) evals.get(j);
String evalStatus = evaluationsLogic.getEvaluationState(eval.getId());
if ( EvalConstants.EVALUATION_STATE_INQUEUE.equals(evalStatus) ) {
inqueueEvals.add(eval);
} else if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus) ||
EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus) ) {
closedEvals.add(eval);
} else if (EvalConstants.EVALUATION_STATE_ACTIVE.equals(evalStatus) ||
EvalConstants.EVALUATION_STATE_DUE.equals(evalStatus) ) {
activeEvals.add(eval);
}
}
// create inqueue evaluations header and link
UIMessage.make(tofill, "evals-inqueue-header", "controlevaluations.inqueue.header");
UIMessage.make(tofill, "evals-inqueue-description", "controlevaluations.inqueue.description");
UIForm startEvalForm = UIForm.make(tofill, "begin-evaluation-form");
UICommand.make(startEvalForm, "begin-evaluation-link", UIMessage.make("starteval.page.title"), "#{evaluationBean.startEvaluation}");
if (inqueueEvals.size() > 0) {
UIBranchContainer evalListing = UIBranchContainer.make(tofill, "inqueue-eval-listing:");
UIForm evalForm = UIForm.make(evalListing, "inqueue-eval-form");
UIMessage.make(evalForm, "eval-title-header", "controlevaluations.eval.title.header");
UIMessage.make(evalForm, "eval-assigned-header", "controlevaluations.eval.assigned.header");
UIMessage.make(evalForm, "eval-startdate-header", "controlevaluations.eval.startdate.header");
UIMessage.make(evalForm, "eval-duedate-header", "controlevaluations.eval.duedate.header");
UIMessage.make(evalForm, "eval-settings-header", "controlevaluations.eval.settings.header");
for (int i = 0; i < inqueueEvals.size(); i++) {
EvalEvaluation evaluation = (EvalEvaluation) inqueueEvals.get(i);
UIBranchContainer evaluationRow = UIBranchContainer.make(evalForm, "inqueue-eval-row:", evaluation.getId().toString());
UIMessage.make(evalForm, "eval-preview-title", "controlevaluations.eval.preview.title");
UIMessage.make(evalForm, "eval-link-title", "controlevaluations.eval.link.title");
UIInternalLink.make(evaluationRow, "inqueue-eval-link", evaluation.getTitle(),
new PreviewEvalParameters( PreviewEvalProducer.VIEW_ID, evaluation.getId(), evaluation.getTemplate().getId() ) );
UILink.make(evaluationRow, "eval-direct-link", UIMessage.make("controlevaluations.eval.direct.link"),
externalLogic.getEntityURL(evaluation));
if (evaluation.getEvalCategory() != null) {
UILink catLink = UILink.make(evaluationRow, "eval-category-direct-link", shortenText(evaluation.getEvalCategory(), 20),
externalLogic.getEntityURL(EvalCategoryEntityProvider.ENTITY_PREFIX, evaluation.getEvalCategory()) );
catLink.decorators = new DecoratorList(
new UITooltipDecorator( UIMessage.make("general.category.link.tip", new Object[]{evaluation.getEvalCategory()}) ) );
}
// vary the display depending on the number of groups assigned
int groupsCount = evaluationsLogic.countEvaluationGroups(evaluation.getId());
if (groupsCount == 1) {
UICommand evalAssigned = UICommand.make(evaluationRow,
"inqueue-eval-assigned-link",
getTitleForFirstEvalGroup(evaluation.getId()),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
} else {
UICommand evalAssigned = UICommand.make(evaluationRow,
"inqueue-eval-assigned-link",
UIMessage.make("controlevaluations.eval.groups.link", new Object[] { new Integer(groupsCount) }),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
}
UIOutput.make(evaluationRow, "inqueue-eval-startdate", df.format(evaluation.getStartDate()));
UIOutput.make(evaluationRow, "inqueue-eval-duedate", df.format(evaluation.getDueDate()));
UICommand evalEdit = UICommand.make(evaluationRow,
"inqueue-eval-edit-link",
UIMessage.make("controlevaluations.eval.edit.link"),
"#{evaluationBean.editEvalSettingAction}");
evalEdit.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", evaluation.getId()));
// do the locked check first since it is more efficient
if ( ! evaluation.getLocked().booleanValue() &&
evaluationsLogic.canRemoveEvaluation(currentUserId, evaluation.getId()) ) {
// evaluation removable
UIInternalLink.make(evaluationRow, "inqueue-eval-delete-link",
UIMessage.make("controlevaluations.eval.delete.link"),
new TemplateViewParameters( RemoveEvalProducer.VIEW_ID, evaluation.getId() ) );
}
}
} else {
UIMessage.make(tofill, "no-inqueue-evals", "controlevaluations.inqueue.none");
}
// create active evaluations header and link
UIMessage.make(tofill, "evals-active-header", "controlevaluations.active.header");
UIMessage.make(tofill, "evals-active-description", "controlevaluations.active.description");
if (activeEvals.size() > 0) {
UIBranchContainer evalListing = UIBranchContainer.make(tofill, "active-eval-listing:");
UIForm evalForm = UIForm.make(evalListing, "active-eval-form");
UIMessage.make(evalForm, "eval-title-header", "controlevaluations.eval.title.header");
UIMessage.make(evalForm, "eval-assigned-header", "controlevaluations.eval.assigned.header");
UIMessage.make(evalForm, "eval-responses-header", "controlevaluations.eval.responses.header");
UIMessage.make(evalForm, "eval-startdate-header", "controlevaluations.eval.startdate.header");
UIMessage.make(evalForm, "eval-duedate-header", "controlevaluations.eval.duedate.header");
UIMessage.make(evalForm, "eval-settings-header", "controlevaluations.eval.settings.header");
for (int i = 0; i < activeEvals.size(); i++) {
EvalEvaluation evaluation = (EvalEvaluation) activeEvals.get(i);
UIBranchContainer evaluationRow = UIBranchContainer.make(evalForm, "active-eval-row:", evaluation.getId().toString());
UIMessage.make(evalForm, "eval-preview-title", "controlevaluations.eval.preview.title");
UIMessage.make(evalForm, "eval-link-title", "controlevaluations.eval.link.title");
UIInternalLink.make(evaluationRow, "active-eval-link", evaluation.getTitle(),
new PreviewEvalParameters( PreviewEvalProducer.VIEW_ID, evaluation.getId(), evaluation.getTemplate().getId() ) );
UILink.make(evaluationRow, "eval-direct-link", UIMessage.make("controlevaluations.eval.direct.link"),
externalLogic.getEntityURL(evaluation));
if (evaluation.getEvalCategory() != null) {
UILink catLink = UILink.make(evaluationRow, "eval-category-direct-link", shortenText(evaluation.getEvalCategory(), 20),
externalLogic.getEntityURL(EvalCategoryEntityProvider.ENTITY_PREFIX, evaluation.getEvalCategory()) );
catLink.decorators = new DecoratorList(
new UITooltipDecorator( UIMessage.make("general.category.link.tip", new Object[]{evaluation.getEvalCategory()}) ) );
}
// vary the display depending on the number of groups assigned
int groupsCount = evaluationsLogic.countEvaluationGroups(evaluation.getId());
if (groupsCount == 1) {
UICommand evalAssigned = UICommand.make(evaluationRow,
"active-eval-assigned-link",
getTitleForFirstEvalGroup(evaluation.getId()),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
} else {
UICommand evalAssigned = UICommand.make(evaluationRow,
"active-eval-assigned-link",
UIMessage.make("controlevaluations.eval.groups.link", new Object[] { new Integer(groupsCount) }),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
}
// calculate the response rate
int countResponses = responsesLogic.countResponses(evaluation.getId(), null);
int countEnrollments = getTotalEnrollmentsForEval(evaluation.getId());
if (countEnrollments > 0) {
UIOutput.make(evaluationRow, "active-eval-response-rate", countResponses + "/" + countEnrollments );
} else {
UIOutput.make(evaluationRow, "active-eval-response-rate", countResponses + "" );
}
UIOutput.make(evaluationRow, "active-eval-startdate", df.format(evaluation.getStartDate()));
UIOutput.make(evaluationRow, "active-eval-duedate", df.format(evaluation.getDueDate()));
UICommand evalEdit = UICommand.make(evaluationRow,
"active-eval-edit-link",
UIMessage.make("controlevaluations.eval.edit.link"),
"#{evaluationBean.editEvalSettingAction}");
evalEdit.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", evaluation.getId()));
if ( ! evaluation.getLocked().booleanValue() &&
evaluationsLogic.canRemoveEvaluation(currentUserId, evaluation.getId()) ) {
// evaluation removable
UIInternalLink.make(evaluationRow, "active-eval-delete-link",
UIMessage.make("controlevaluations.eval.delete.link"),
new TemplateViewParameters( RemoveEvalProducer.VIEW_ID, evaluation.getId() ) );
}
}
} else {
UIMessage.make(tofill, "no-active-evals", "controlevaluations.active.none");
}
// create closed evaluations header and link
UIMessage.make(tofill, "evals-closed-header", "controlevaluations.closed.header");
UIMessage.make(tofill, "evals-closed-description", "controlevaluations.closed.description");
if (closedEvals.size() > 0) {
UIBranchContainer evalListing = UIBranchContainer.make(tofill, "closed-eval-listing:");
UIForm evalForm = UIForm.make(evalListing, "closed-eval-form");
UIMessage.make(evalForm, "eval-title-header", "controlevaluations.eval.title.header");
+ UIMessage.make(evalForm, "eval-report-header", "controlevaluations.eval.report.header");
UIMessage.make(evalForm, "eval-assigned-header", "controlevaluations.eval.assigned.header");
UIMessage.make(evalForm, "eval-response-rate-header", "controlevaluations.eval.responserate.header");
- UIMessage.make(evalForm, "eval-startdate-header", "controlevaluations.eval.startdate.header");
- UIMessage.make(evalForm, "eval-report-header", "controlevaluations.eval.report.header");
+ UIMessage.make(evalForm, "eval-duedate-header", "controlevaluations.eval.startdate.header");
for (int i = 0; i < closedEvals.size(); i++) {
EvalEvaluation evaluation = (EvalEvaluation) closedEvals.get(i);
UIBranchContainer evaluationRow = UIBranchContainer.make(evalForm, "closed-eval-row:", evaluation.getId().toString());
UIMessage.make(evalForm, "eval-preview-title", "controlevaluations.eval.preview.title");
UIMessage.make(evalForm, "eval-link-title", "controlevaluations.eval.link.title");
UIInternalLink.make(evaluationRow, "closed-eval-link", evaluation.getTitle(),
new PreviewEvalParameters( PreviewEvalProducer.VIEW_ID, evaluation.getId(), evaluation.getTemplate().getId() ) );
if (evaluation.getEvalCategory() != null) {
UIOutput category = UIOutput.make(evaluationRow, "eval-category", shortenText(evaluation.getEvalCategory(), 20) );
category.decorators = new DecoratorList(
new UITooltipDecorator( evaluation.getEvalCategory() ) );
}
// vary the display depending on the number of groups assigned
int groupsCount = evaluationsLogic.countEvaluationGroups(evaluation.getId());
if (groupsCount == 1) {
UICommand evalAssigned = UICommand.make(evaluationRow,
"closed-eval-assigned-link",
getTitleForFirstEvalGroup(evaluation.getId()),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
} else {
UICommand evalAssigned = UICommand.make(evaluationRow,
"closed-eval-assigned-link",
UIMessage.make("controlevaluations.eval.groups.link", new Object[] { new Integer(groupsCount) }),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
}
// calculate the response rate
int countResponses = responsesLogic.countResponses(evaluation.getId(), null);
- int countEnrollments = getTotalEnrollmentsForEval(evaluation.getId());
- long percentage = 0;
- if (countEnrollments > 0) {
- percentage = Math.round( (1.0 * countResponses )/countEnrollments )*100;
- UIOutput.make(evaluationRow, "closed-eval-response-rate", countResponses + "/"+ countEnrollments +" - "+percentage +"%");
- } else {
- // don't bother showing percentage or "out of" when there are no enrollments
- UIOutput.make(evaluationRow, "closed-eval-response-rate", countResponses + "");
- }
+ int countEnrollments = getTotalEnrollmentsForEval(evaluation.getId());
+ long percentage = 0;
+ if (countEnrollments > 0) {
+ percentage = Math.round( (((float)countResponses) / (float)countEnrollments) * 100.0 );
+ UIOutput.make(evaluationRow, "closed-eval-response-rate", countResponses + "/"
+ + countEnrollments + " - " + percentage + "%");
+ } else {
+ // don't bother showing percentage or "out of" when there are no enrollments
+ UIOutput.make(evaluationRow, "closed-eval-response-rate", countResponses + "");
+ }
UIOutput.make(evaluationRow, "closed-eval-duedate", df.format(evaluation.getDueDate()));
UICommand evalEdit = UICommand.make(evaluationRow,
"closed-eval-edit-link",
UIMessage.make("controlevaluations.eval.edit.link"),
"#{evaluationBean.editEvalSettingAction}");
evalEdit.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", evaluation.getId()));
if (EvalConstants.EVALUATION_STATE_VIEWABLE.equals(EvalUtils.getEvaluationState(evaluation)) ) {
int respReqToViewResults = ((Integer) settings.get(EvalSettings.RESPONSES_REQUIRED_TO_VIEW_RESULTS)).intValue();
// make sure there is at least one response before showing the link
if ( (respReqToViewResults <= countResponses || countResponses >= countEnrollments) &&
countResponses > 0 ) {
UIInternalLink.make(evaluationRow, "closed-eval-report-link",
UIMessage.make("controlevaluations.eval.report.link"),
new ReportParameters(ReportChooseGroupsProducer.VIEW_ID, evaluation.getId() ));
} else {
UIMessage.make(evaluationRow, "closed-eval-message",
"controlevaluations.eval.report.awaiting.responses");
}
} else {
UIMessage.make(evaluationRow, "closed-eval-message",
"controlevaluations.eval.report.viewable.on",
new String[] { df.format(evaluation.getViewDate()) });
}
if ( ! evaluation.getLocked().booleanValue() &&
evaluationsLogic.canRemoveEvaluation(currentUserId, evaluation.getId()) ) {
// evaluation removable
UIInternalLink.make(evaluationRow, "closed-eval-delete-link",
UIMessage.make("controlevaluations.eval.delete.link"),
new TemplateViewParameters( RemoveEvalProducer.VIEW_ID, evaluation.getId() ) );
}
}
} else {
UIMessage.make(tofill, "no-closed-evals", "controlevaluations.closed.none");
}
}
/* (non-Javadoc)
* @see uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter#reportNavigationCases()
*/
public List reportNavigationCases() {
List i = new ArrayList();
i.add(new NavigationCase(EvaluationSettingsProducer.VIEW_ID, new SimpleViewParameters(
EvaluationSettingsProducer.VIEW_ID)));
i.add(new NavigationCase(EvaluationStartProducer.VIEW_ID, new SimpleViewParameters(
EvaluationStartProducer.VIEW_ID)));
i.add(new NavigationCase(EvaluationAssignConfirmProducer.VIEW_ID, new SimpleViewParameters(
EvaluationAssignConfirmProducer.VIEW_ID)));
return i;
}
/**
* Gets the title for the first returned evalGroupId for this evaluation,
* should only be used when there is only one evalGroupId assigned to an eval
*
* @param evaluationId
* @return title of first evalGroupId returned
*/
private String getTitleForFirstEvalGroup(Long evaluationId) {
Map evalAssignGroups = evaluationsLogic.getEvaluationAssignGroups(new Long[] {evaluationId}, true);
List groups = (List) evalAssignGroups.get(evaluationId);
EvalAssignGroup eac = (EvalAssignGroup) groups.get(0);
return externalLogic.getDisplayTitle( eac.getEvalGroupId() );
}
/**
* Gets the total count of enrollments for an evaluation
*
* @param evaluationId
* @return total number of users with take eval perms in this evaluation
*/
private int getTotalEnrollmentsForEval(Long evaluationId) {
int totalEnrollments = 0;
Map evalAssignGroups = evaluationsLogic.getEvaluationAssignGroups(new Long[] {evaluationId}, true);
List groups = (List) evalAssignGroups.get(evaluationId);
for (int i=0; i<groups.size(); i++) {
EvalAssignGroup eac = (EvalAssignGroup) groups.get(i);
String context = eac.getEvalGroupId();
Set userIds = externalLogic.getUserIdsForEvalGroup(context, EvalConstants.PERM_TAKE_EVALUATION);
totalEnrollments = totalEnrollments + userIds.size();
}
return totalEnrollments;
}
/**
* Shorten a string to be no longer than the length supplied (uses ...)
* @param text
* @param length
* @return shorted text with ... or original string
*/
private String shortenText(String text, int length) {
if (text.length() > length) {
text = text.substring(0, length-3) + "...";
}
return text;
}
}
| false | true | public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
// local variables used in the render logic
String currentUserId = externalLogic.getCurrentUserId();
boolean userAdmin = externalLogic.isUserAdmin(currentUserId);
boolean createTemplate = templatesLogic.canCreateTemplate(currentUserId);
boolean beginEvaluation = evaluationsLogic.canBeginEvaluation(currentUserId);
// use a date which is related to the current users locale
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
// page title
UIMessage.make(tofill, "page-title", "controlevaluations.page.title");
/*
* top links here
*/
UIInternalLink.make(tofill, "summary-link",
UIMessage.make("summary.page.title"),
new SimpleViewParameters(SummaryProducer.VIEW_ID));
if (userAdmin) {
UIInternalLink.make(tofill, "administrate-link",
UIMessage.make("administrate.page.title"),
new SimpleViewParameters(AdministrateProducer.VIEW_ID));
}
if (createTemplate) {
UIInternalLink.make(tofill, "control-templates-link",
UIMessage.make("controltemplates.page.title"),
new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID));
UIInternalLink.make(tofill, "control-items-link",
UIMessage.make("controlitems.page.title"),
new SimpleViewParameters(ControlItemsProducer.VIEW_ID));
}
if (!beginEvaluation) {
throw new SecurityException("User attempted to access " +
ControlEvaluationsProducer.VIEW_ID + " when they are not allowed");
}
// get all the visible evaluations for the current user
List inqueueEvals = new ArrayList();
List activeEvals = new ArrayList();
List closedEvals = new ArrayList();
List evals = evaluationsLogic.getVisibleEvaluationsForUser(externalLogic.getCurrentUserId(), false, false);
for (int j = 0; j < evals.size(); j++) {
// get queued, active, closed evaluations by date
// check the state of the eval to determine display data
EvalEvaluation eval = (EvalEvaluation) evals.get(j);
String evalStatus = evaluationsLogic.getEvaluationState(eval.getId());
if ( EvalConstants.EVALUATION_STATE_INQUEUE.equals(evalStatus) ) {
inqueueEvals.add(eval);
} else if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus) ||
EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus) ) {
closedEvals.add(eval);
} else if (EvalConstants.EVALUATION_STATE_ACTIVE.equals(evalStatus) ||
EvalConstants.EVALUATION_STATE_DUE.equals(evalStatus) ) {
activeEvals.add(eval);
}
}
// create inqueue evaluations header and link
UIMessage.make(tofill, "evals-inqueue-header", "controlevaluations.inqueue.header");
UIMessage.make(tofill, "evals-inqueue-description", "controlevaluations.inqueue.description");
UIForm startEvalForm = UIForm.make(tofill, "begin-evaluation-form");
UICommand.make(startEvalForm, "begin-evaluation-link", UIMessage.make("starteval.page.title"), "#{evaluationBean.startEvaluation}");
if (inqueueEvals.size() > 0) {
UIBranchContainer evalListing = UIBranchContainer.make(tofill, "inqueue-eval-listing:");
UIForm evalForm = UIForm.make(evalListing, "inqueue-eval-form");
UIMessage.make(evalForm, "eval-title-header", "controlevaluations.eval.title.header");
UIMessage.make(evalForm, "eval-assigned-header", "controlevaluations.eval.assigned.header");
UIMessage.make(evalForm, "eval-startdate-header", "controlevaluations.eval.startdate.header");
UIMessage.make(evalForm, "eval-duedate-header", "controlevaluations.eval.duedate.header");
UIMessage.make(evalForm, "eval-settings-header", "controlevaluations.eval.settings.header");
for (int i = 0; i < inqueueEvals.size(); i++) {
EvalEvaluation evaluation = (EvalEvaluation) inqueueEvals.get(i);
UIBranchContainer evaluationRow = UIBranchContainer.make(evalForm, "inqueue-eval-row:", evaluation.getId().toString());
UIMessage.make(evalForm, "eval-preview-title", "controlevaluations.eval.preview.title");
UIMessage.make(evalForm, "eval-link-title", "controlevaluations.eval.link.title");
UIInternalLink.make(evaluationRow, "inqueue-eval-link", evaluation.getTitle(),
new PreviewEvalParameters( PreviewEvalProducer.VIEW_ID, evaluation.getId(), evaluation.getTemplate().getId() ) );
UILink.make(evaluationRow, "eval-direct-link", UIMessage.make("controlevaluations.eval.direct.link"),
externalLogic.getEntityURL(evaluation));
if (evaluation.getEvalCategory() != null) {
UILink catLink = UILink.make(evaluationRow, "eval-category-direct-link", shortenText(evaluation.getEvalCategory(), 20),
externalLogic.getEntityURL(EvalCategoryEntityProvider.ENTITY_PREFIX, evaluation.getEvalCategory()) );
catLink.decorators = new DecoratorList(
new UITooltipDecorator( UIMessage.make("general.category.link.tip", new Object[]{evaluation.getEvalCategory()}) ) );
}
// vary the display depending on the number of groups assigned
int groupsCount = evaluationsLogic.countEvaluationGroups(evaluation.getId());
if (groupsCount == 1) {
UICommand evalAssigned = UICommand.make(evaluationRow,
"inqueue-eval-assigned-link",
getTitleForFirstEvalGroup(evaluation.getId()),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
} else {
UICommand evalAssigned = UICommand.make(evaluationRow,
"inqueue-eval-assigned-link",
UIMessage.make("controlevaluations.eval.groups.link", new Object[] { new Integer(groupsCount) }),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
}
UIOutput.make(evaluationRow, "inqueue-eval-startdate", df.format(evaluation.getStartDate()));
UIOutput.make(evaluationRow, "inqueue-eval-duedate", df.format(evaluation.getDueDate()));
UICommand evalEdit = UICommand.make(evaluationRow,
"inqueue-eval-edit-link",
UIMessage.make("controlevaluations.eval.edit.link"),
"#{evaluationBean.editEvalSettingAction}");
evalEdit.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", evaluation.getId()));
// do the locked check first since it is more efficient
if ( ! evaluation.getLocked().booleanValue() &&
evaluationsLogic.canRemoveEvaluation(currentUserId, evaluation.getId()) ) {
// evaluation removable
UIInternalLink.make(evaluationRow, "inqueue-eval-delete-link",
UIMessage.make("controlevaluations.eval.delete.link"),
new TemplateViewParameters( RemoveEvalProducer.VIEW_ID, evaluation.getId() ) );
}
}
} else {
UIMessage.make(tofill, "no-inqueue-evals", "controlevaluations.inqueue.none");
}
// create active evaluations header and link
UIMessage.make(tofill, "evals-active-header", "controlevaluations.active.header");
UIMessage.make(tofill, "evals-active-description", "controlevaluations.active.description");
if (activeEvals.size() > 0) {
UIBranchContainer evalListing = UIBranchContainer.make(tofill, "active-eval-listing:");
UIForm evalForm = UIForm.make(evalListing, "active-eval-form");
UIMessage.make(evalForm, "eval-title-header", "controlevaluations.eval.title.header");
UIMessage.make(evalForm, "eval-assigned-header", "controlevaluations.eval.assigned.header");
UIMessage.make(evalForm, "eval-responses-header", "controlevaluations.eval.responses.header");
UIMessage.make(evalForm, "eval-startdate-header", "controlevaluations.eval.startdate.header");
UIMessage.make(evalForm, "eval-duedate-header", "controlevaluations.eval.duedate.header");
UIMessage.make(evalForm, "eval-settings-header", "controlevaluations.eval.settings.header");
for (int i = 0; i < activeEvals.size(); i++) {
EvalEvaluation evaluation = (EvalEvaluation) activeEvals.get(i);
UIBranchContainer evaluationRow = UIBranchContainer.make(evalForm, "active-eval-row:", evaluation.getId().toString());
UIMessage.make(evalForm, "eval-preview-title", "controlevaluations.eval.preview.title");
UIMessage.make(evalForm, "eval-link-title", "controlevaluations.eval.link.title");
UIInternalLink.make(evaluationRow, "active-eval-link", evaluation.getTitle(),
new PreviewEvalParameters( PreviewEvalProducer.VIEW_ID, evaluation.getId(), evaluation.getTemplate().getId() ) );
UILink.make(evaluationRow, "eval-direct-link", UIMessage.make("controlevaluations.eval.direct.link"),
externalLogic.getEntityURL(evaluation));
if (evaluation.getEvalCategory() != null) {
UILink catLink = UILink.make(evaluationRow, "eval-category-direct-link", shortenText(evaluation.getEvalCategory(), 20),
externalLogic.getEntityURL(EvalCategoryEntityProvider.ENTITY_PREFIX, evaluation.getEvalCategory()) );
catLink.decorators = new DecoratorList(
new UITooltipDecorator( UIMessage.make("general.category.link.tip", new Object[]{evaluation.getEvalCategory()}) ) );
}
// vary the display depending on the number of groups assigned
int groupsCount = evaluationsLogic.countEvaluationGroups(evaluation.getId());
if (groupsCount == 1) {
UICommand evalAssigned = UICommand.make(evaluationRow,
"active-eval-assigned-link",
getTitleForFirstEvalGroup(evaluation.getId()),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
} else {
UICommand evalAssigned = UICommand.make(evaluationRow,
"active-eval-assigned-link",
UIMessage.make("controlevaluations.eval.groups.link", new Object[] { new Integer(groupsCount) }),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
}
// calculate the response rate
int countResponses = responsesLogic.countResponses(evaluation.getId(), null);
int countEnrollments = getTotalEnrollmentsForEval(evaluation.getId());
if (countEnrollments > 0) {
UIOutput.make(evaluationRow, "active-eval-response-rate", countResponses + "/" + countEnrollments );
} else {
UIOutput.make(evaluationRow, "active-eval-response-rate", countResponses + "" );
}
UIOutput.make(evaluationRow, "active-eval-startdate", df.format(evaluation.getStartDate()));
UIOutput.make(evaluationRow, "active-eval-duedate", df.format(evaluation.getDueDate()));
UICommand evalEdit = UICommand.make(evaluationRow,
"active-eval-edit-link",
UIMessage.make("controlevaluations.eval.edit.link"),
"#{evaluationBean.editEvalSettingAction}");
evalEdit.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", evaluation.getId()));
if ( ! evaluation.getLocked().booleanValue() &&
evaluationsLogic.canRemoveEvaluation(currentUserId, evaluation.getId()) ) {
// evaluation removable
UIInternalLink.make(evaluationRow, "active-eval-delete-link",
UIMessage.make("controlevaluations.eval.delete.link"),
new TemplateViewParameters( RemoveEvalProducer.VIEW_ID, evaluation.getId() ) );
}
}
} else {
UIMessage.make(tofill, "no-active-evals", "controlevaluations.active.none");
}
// create closed evaluations header and link
UIMessage.make(tofill, "evals-closed-header", "controlevaluations.closed.header");
UIMessage.make(tofill, "evals-closed-description", "controlevaluations.closed.description");
if (closedEvals.size() > 0) {
UIBranchContainer evalListing = UIBranchContainer.make(tofill, "closed-eval-listing:");
UIForm evalForm = UIForm.make(evalListing, "closed-eval-form");
UIMessage.make(evalForm, "eval-title-header", "controlevaluations.eval.title.header");
UIMessage.make(evalForm, "eval-assigned-header", "controlevaluations.eval.assigned.header");
UIMessage.make(evalForm, "eval-response-rate-header", "controlevaluations.eval.responserate.header");
UIMessage.make(evalForm, "eval-startdate-header", "controlevaluations.eval.startdate.header");
UIMessage.make(evalForm, "eval-report-header", "controlevaluations.eval.report.header");
for (int i = 0; i < closedEvals.size(); i++) {
EvalEvaluation evaluation = (EvalEvaluation) closedEvals.get(i);
UIBranchContainer evaluationRow = UIBranchContainer.make(evalForm, "closed-eval-row:", evaluation.getId().toString());
UIMessage.make(evalForm, "eval-preview-title", "controlevaluations.eval.preview.title");
UIMessage.make(evalForm, "eval-link-title", "controlevaluations.eval.link.title");
UIInternalLink.make(evaluationRow, "closed-eval-link", evaluation.getTitle(),
new PreviewEvalParameters( PreviewEvalProducer.VIEW_ID, evaluation.getId(), evaluation.getTemplate().getId() ) );
if (evaluation.getEvalCategory() != null) {
UIOutput category = UIOutput.make(evaluationRow, "eval-category", shortenText(evaluation.getEvalCategory(), 20) );
category.decorators = new DecoratorList(
new UITooltipDecorator( evaluation.getEvalCategory() ) );
}
// vary the display depending on the number of groups assigned
int groupsCount = evaluationsLogic.countEvaluationGroups(evaluation.getId());
if (groupsCount == 1) {
UICommand evalAssigned = UICommand.make(evaluationRow,
"closed-eval-assigned-link",
getTitleForFirstEvalGroup(evaluation.getId()),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
} else {
UICommand evalAssigned = UICommand.make(evaluationRow,
"closed-eval-assigned-link",
UIMessage.make("controlevaluations.eval.groups.link", new Object[] { new Integer(groupsCount) }),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
}
// calculate the response rate
int countResponses = responsesLogic.countResponses(evaluation.getId(), null);
int countEnrollments = getTotalEnrollmentsForEval(evaluation.getId());
long percentage = 0;
if (countEnrollments > 0) {
percentage = Math.round( (1.0 * countResponses )/countEnrollments )*100;
UIOutput.make(evaluationRow, "closed-eval-response-rate", countResponses + "/"+ countEnrollments +" - "+percentage +"%");
} else {
// don't bother showing percentage or "out of" when there are no enrollments
UIOutput.make(evaluationRow, "closed-eval-response-rate", countResponses + "");
}
UIOutput.make(evaluationRow, "closed-eval-duedate", df.format(evaluation.getDueDate()));
UICommand evalEdit = UICommand.make(evaluationRow,
"closed-eval-edit-link",
UIMessage.make("controlevaluations.eval.edit.link"),
"#{evaluationBean.editEvalSettingAction}");
evalEdit.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", evaluation.getId()));
if (EvalConstants.EVALUATION_STATE_VIEWABLE.equals(EvalUtils.getEvaluationState(evaluation)) ) {
int respReqToViewResults = ((Integer) settings.get(EvalSettings.RESPONSES_REQUIRED_TO_VIEW_RESULTS)).intValue();
// make sure there is at least one response before showing the link
if ( (respReqToViewResults <= countResponses || countResponses >= countEnrollments) &&
countResponses > 0 ) {
UIInternalLink.make(evaluationRow, "closed-eval-report-link",
UIMessage.make("controlevaluations.eval.report.link"),
new ReportParameters(ReportChooseGroupsProducer.VIEW_ID, evaluation.getId() ));
} else {
UIMessage.make(evaluationRow, "closed-eval-message",
"controlevaluations.eval.report.awaiting.responses");
}
} else {
UIMessage.make(evaluationRow, "closed-eval-message",
"controlevaluations.eval.report.viewable.on",
new String[] { df.format(evaluation.getViewDate()) });
}
if ( ! evaluation.getLocked().booleanValue() &&
evaluationsLogic.canRemoveEvaluation(currentUserId, evaluation.getId()) ) {
// evaluation removable
UIInternalLink.make(evaluationRow, "closed-eval-delete-link",
UIMessage.make("controlevaluations.eval.delete.link"),
new TemplateViewParameters( RemoveEvalProducer.VIEW_ID, evaluation.getId() ) );
}
}
} else {
UIMessage.make(tofill, "no-closed-evals", "controlevaluations.closed.none");
}
}
| public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
// local variables used in the render logic
String currentUserId = externalLogic.getCurrentUserId();
boolean userAdmin = externalLogic.isUserAdmin(currentUserId);
boolean createTemplate = templatesLogic.canCreateTemplate(currentUserId);
boolean beginEvaluation = evaluationsLogic.canBeginEvaluation(currentUserId);
// use a date which is related to the current users locale
DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
// page title
UIMessage.make(tofill, "page-title", "controlevaluations.page.title");
/*
* top links here
*/
UIInternalLink.make(tofill, "summary-link",
UIMessage.make("summary.page.title"),
new SimpleViewParameters(SummaryProducer.VIEW_ID));
if (userAdmin) {
UIInternalLink.make(tofill, "administrate-link",
UIMessage.make("administrate.page.title"),
new SimpleViewParameters(AdministrateProducer.VIEW_ID));
}
if (createTemplate) {
UIInternalLink.make(tofill, "control-templates-link",
UIMessage.make("controltemplates.page.title"),
new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID));
UIInternalLink.make(tofill, "control-items-link",
UIMessage.make("controlitems.page.title"),
new SimpleViewParameters(ControlItemsProducer.VIEW_ID));
}
if (!beginEvaluation) {
throw new SecurityException("User attempted to access " +
ControlEvaluationsProducer.VIEW_ID + " when they are not allowed");
}
// get all the visible evaluations for the current user
List inqueueEvals = new ArrayList();
List activeEvals = new ArrayList();
List closedEvals = new ArrayList();
List evals = evaluationsLogic.getVisibleEvaluationsForUser(externalLogic.getCurrentUserId(), false, false);
for (int j = 0; j < evals.size(); j++) {
// get queued, active, closed evaluations by date
// check the state of the eval to determine display data
EvalEvaluation eval = (EvalEvaluation) evals.get(j);
String evalStatus = evaluationsLogic.getEvaluationState(eval.getId());
if ( EvalConstants.EVALUATION_STATE_INQUEUE.equals(evalStatus) ) {
inqueueEvals.add(eval);
} else if (EvalConstants.EVALUATION_STATE_CLOSED.equals(evalStatus) ||
EvalConstants.EVALUATION_STATE_VIEWABLE.equals(evalStatus) ) {
closedEvals.add(eval);
} else if (EvalConstants.EVALUATION_STATE_ACTIVE.equals(evalStatus) ||
EvalConstants.EVALUATION_STATE_DUE.equals(evalStatus) ) {
activeEvals.add(eval);
}
}
// create inqueue evaluations header and link
UIMessage.make(tofill, "evals-inqueue-header", "controlevaluations.inqueue.header");
UIMessage.make(tofill, "evals-inqueue-description", "controlevaluations.inqueue.description");
UIForm startEvalForm = UIForm.make(tofill, "begin-evaluation-form");
UICommand.make(startEvalForm, "begin-evaluation-link", UIMessage.make("starteval.page.title"), "#{evaluationBean.startEvaluation}");
if (inqueueEvals.size() > 0) {
UIBranchContainer evalListing = UIBranchContainer.make(tofill, "inqueue-eval-listing:");
UIForm evalForm = UIForm.make(evalListing, "inqueue-eval-form");
UIMessage.make(evalForm, "eval-title-header", "controlevaluations.eval.title.header");
UIMessage.make(evalForm, "eval-assigned-header", "controlevaluations.eval.assigned.header");
UIMessage.make(evalForm, "eval-startdate-header", "controlevaluations.eval.startdate.header");
UIMessage.make(evalForm, "eval-duedate-header", "controlevaluations.eval.duedate.header");
UIMessage.make(evalForm, "eval-settings-header", "controlevaluations.eval.settings.header");
for (int i = 0; i < inqueueEvals.size(); i++) {
EvalEvaluation evaluation = (EvalEvaluation) inqueueEvals.get(i);
UIBranchContainer evaluationRow = UIBranchContainer.make(evalForm, "inqueue-eval-row:", evaluation.getId().toString());
UIMessage.make(evalForm, "eval-preview-title", "controlevaluations.eval.preview.title");
UIMessage.make(evalForm, "eval-link-title", "controlevaluations.eval.link.title");
UIInternalLink.make(evaluationRow, "inqueue-eval-link", evaluation.getTitle(),
new PreviewEvalParameters( PreviewEvalProducer.VIEW_ID, evaluation.getId(), evaluation.getTemplate().getId() ) );
UILink.make(evaluationRow, "eval-direct-link", UIMessage.make("controlevaluations.eval.direct.link"),
externalLogic.getEntityURL(evaluation));
if (evaluation.getEvalCategory() != null) {
UILink catLink = UILink.make(evaluationRow, "eval-category-direct-link", shortenText(evaluation.getEvalCategory(), 20),
externalLogic.getEntityURL(EvalCategoryEntityProvider.ENTITY_PREFIX, evaluation.getEvalCategory()) );
catLink.decorators = new DecoratorList(
new UITooltipDecorator( UIMessage.make("general.category.link.tip", new Object[]{evaluation.getEvalCategory()}) ) );
}
// vary the display depending on the number of groups assigned
int groupsCount = evaluationsLogic.countEvaluationGroups(evaluation.getId());
if (groupsCount == 1) {
UICommand evalAssigned = UICommand.make(evaluationRow,
"inqueue-eval-assigned-link",
getTitleForFirstEvalGroup(evaluation.getId()),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
} else {
UICommand evalAssigned = UICommand.make(evaluationRow,
"inqueue-eval-assigned-link",
UIMessage.make("controlevaluations.eval.groups.link", new Object[] { new Integer(groupsCount) }),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
}
UIOutput.make(evaluationRow, "inqueue-eval-startdate", df.format(evaluation.getStartDate()));
UIOutput.make(evaluationRow, "inqueue-eval-duedate", df.format(evaluation.getDueDate()));
UICommand evalEdit = UICommand.make(evaluationRow,
"inqueue-eval-edit-link",
UIMessage.make("controlevaluations.eval.edit.link"),
"#{evaluationBean.editEvalSettingAction}");
evalEdit.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", evaluation.getId()));
// do the locked check first since it is more efficient
if ( ! evaluation.getLocked().booleanValue() &&
evaluationsLogic.canRemoveEvaluation(currentUserId, evaluation.getId()) ) {
// evaluation removable
UIInternalLink.make(evaluationRow, "inqueue-eval-delete-link",
UIMessage.make("controlevaluations.eval.delete.link"),
new TemplateViewParameters( RemoveEvalProducer.VIEW_ID, evaluation.getId() ) );
}
}
} else {
UIMessage.make(tofill, "no-inqueue-evals", "controlevaluations.inqueue.none");
}
// create active evaluations header and link
UIMessage.make(tofill, "evals-active-header", "controlevaluations.active.header");
UIMessage.make(tofill, "evals-active-description", "controlevaluations.active.description");
if (activeEvals.size() > 0) {
UIBranchContainer evalListing = UIBranchContainer.make(tofill, "active-eval-listing:");
UIForm evalForm = UIForm.make(evalListing, "active-eval-form");
UIMessage.make(evalForm, "eval-title-header", "controlevaluations.eval.title.header");
UIMessage.make(evalForm, "eval-assigned-header", "controlevaluations.eval.assigned.header");
UIMessage.make(evalForm, "eval-responses-header", "controlevaluations.eval.responses.header");
UIMessage.make(evalForm, "eval-startdate-header", "controlevaluations.eval.startdate.header");
UIMessage.make(evalForm, "eval-duedate-header", "controlevaluations.eval.duedate.header");
UIMessage.make(evalForm, "eval-settings-header", "controlevaluations.eval.settings.header");
for (int i = 0; i < activeEvals.size(); i++) {
EvalEvaluation evaluation = (EvalEvaluation) activeEvals.get(i);
UIBranchContainer evaluationRow = UIBranchContainer.make(evalForm, "active-eval-row:", evaluation.getId().toString());
UIMessage.make(evalForm, "eval-preview-title", "controlevaluations.eval.preview.title");
UIMessage.make(evalForm, "eval-link-title", "controlevaluations.eval.link.title");
UIInternalLink.make(evaluationRow, "active-eval-link", evaluation.getTitle(),
new PreviewEvalParameters( PreviewEvalProducer.VIEW_ID, evaluation.getId(), evaluation.getTemplate().getId() ) );
UILink.make(evaluationRow, "eval-direct-link", UIMessage.make("controlevaluations.eval.direct.link"),
externalLogic.getEntityURL(evaluation));
if (evaluation.getEvalCategory() != null) {
UILink catLink = UILink.make(evaluationRow, "eval-category-direct-link", shortenText(evaluation.getEvalCategory(), 20),
externalLogic.getEntityURL(EvalCategoryEntityProvider.ENTITY_PREFIX, evaluation.getEvalCategory()) );
catLink.decorators = new DecoratorList(
new UITooltipDecorator( UIMessage.make("general.category.link.tip", new Object[]{evaluation.getEvalCategory()}) ) );
}
// vary the display depending on the number of groups assigned
int groupsCount = evaluationsLogic.countEvaluationGroups(evaluation.getId());
if (groupsCount == 1) {
UICommand evalAssigned = UICommand.make(evaluationRow,
"active-eval-assigned-link",
getTitleForFirstEvalGroup(evaluation.getId()),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
} else {
UICommand evalAssigned = UICommand.make(evaluationRow,
"active-eval-assigned-link",
UIMessage.make("controlevaluations.eval.groups.link", new Object[] { new Integer(groupsCount) }),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
}
// calculate the response rate
int countResponses = responsesLogic.countResponses(evaluation.getId(), null);
int countEnrollments = getTotalEnrollmentsForEval(evaluation.getId());
if (countEnrollments > 0) {
UIOutput.make(evaluationRow, "active-eval-response-rate", countResponses + "/" + countEnrollments );
} else {
UIOutput.make(evaluationRow, "active-eval-response-rate", countResponses + "" );
}
UIOutput.make(evaluationRow, "active-eval-startdate", df.format(evaluation.getStartDate()));
UIOutput.make(evaluationRow, "active-eval-duedate", df.format(evaluation.getDueDate()));
UICommand evalEdit = UICommand.make(evaluationRow,
"active-eval-edit-link",
UIMessage.make("controlevaluations.eval.edit.link"),
"#{evaluationBean.editEvalSettingAction}");
evalEdit.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", evaluation.getId()));
if ( ! evaluation.getLocked().booleanValue() &&
evaluationsLogic.canRemoveEvaluation(currentUserId, evaluation.getId()) ) {
// evaluation removable
UIInternalLink.make(evaluationRow, "active-eval-delete-link",
UIMessage.make("controlevaluations.eval.delete.link"),
new TemplateViewParameters( RemoveEvalProducer.VIEW_ID, evaluation.getId() ) );
}
}
} else {
UIMessage.make(tofill, "no-active-evals", "controlevaluations.active.none");
}
// create closed evaluations header and link
UIMessage.make(tofill, "evals-closed-header", "controlevaluations.closed.header");
UIMessage.make(tofill, "evals-closed-description", "controlevaluations.closed.description");
if (closedEvals.size() > 0) {
UIBranchContainer evalListing = UIBranchContainer.make(tofill, "closed-eval-listing:");
UIForm evalForm = UIForm.make(evalListing, "closed-eval-form");
UIMessage.make(evalForm, "eval-title-header", "controlevaluations.eval.title.header");
UIMessage.make(evalForm, "eval-report-header", "controlevaluations.eval.report.header");
UIMessage.make(evalForm, "eval-assigned-header", "controlevaluations.eval.assigned.header");
UIMessage.make(evalForm, "eval-response-rate-header", "controlevaluations.eval.responserate.header");
UIMessage.make(evalForm, "eval-duedate-header", "controlevaluations.eval.startdate.header");
for (int i = 0; i < closedEvals.size(); i++) {
EvalEvaluation evaluation = (EvalEvaluation) closedEvals.get(i);
UIBranchContainer evaluationRow = UIBranchContainer.make(evalForm, "closed-eval-row:", evaluation.getId().toString());
UIMessage.make(evalForm, "eval-preview-title", "controlevaluations.eval.preview.title");
UIMessage.make(evalForm, "eval-link-title", "controlevaluations.eval.link.title");
UIInternalLink.make(evaluationRow, "closed-eval-link", evaluation.getTitle(),
new PreviewEvalParameters( PreviewEvalProducer.VIEW_ID, evaluation.getId(), evaluation.getTemplate().getId() ) );
if (evaluation.getEvalCategory() != null) {
UIOutput category = UIOutput.make(evaluationRow, "eval-category", shortenText(evaluation.getEvalCategory(), 20) );
category.decorators = new DecoratorList(
new UITooltipDecorator( evaluation.getEvalCategory() ) );
}
// vary the display depending on the number of groups assigned
int groupsCount = evaluationsLogic.countEvaluationGroups(evaluation.getId());
if (groupsCount == 1) {
UICommand evalAssigned = UICommand.make(evaluationRow,
"closed-eval-assigned-link",
getTitleForFirstEvalGroup(evaluation.getId()),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
} else {
UICommand evalAssigned = UICommand.make(evaluationRow,
"closed-eval-assigned-link",
UIMessage.make("controlevaluations.eval.groups.link", new Object[] { new Integer(groupsCount) }),
"#{evaluationBean.evalAssigned}");
evalAssigned.parameters.add(new UIELBinding("#{evaluationBean.evalId}", evaluation.getId()));
}
// calculate the response rate
int countResponses = responsesLogic.countResponses(evaluation.getId(), null);
int countEnrollments = getTotalEnrollmentsForEval(evaluation.getId());
long percentage = 0;
if (countEnrollments > 0) {
percentage = Math.round( (((float)countResponses) / (float)countEnrollments) * 100.0 );
UIOutput.make(evaluationRow, "closed-eval-response-rate", countResponses + "/"
+ countEnrollments + " - " + percentage + "%");
} else {
// don't bother showing percentage or "out of" when there are no enrollments
UIOutput.make(evaluationRow, "closed-eval-response-rate", countResponses + "");
}
UIOutput.make(evaluationRow, "closed-eval-duedate", df.format(evaluation.getDueDate()));
UICommand evalEdit = UICommand.make(evaluationRow,
"closed-eval-edit-link",
UIMessage.make("controlevaluations.eval.edit.link"),
"#{evaluationBean.editEvalSettingAction}");
evalEdit.parameters.add(new UIELBinding("#{evaluationBean.eval.id}", evaluation.getId()));
if (EvalConstants.EVALUATION_STATE_VIEWABLE.equals(EvalUtils.getEvaluationState(evaluation)) ) {
int respReqToViewResults = ((Integer) settings.get(EvalSettings.RESPONSES_REQUIRED_TO_VIEW_RESULTS)).intValue();
// make sure there is at least one response before showing the link
if ( (respReqToViewResults <= countResponses || countResponses >= countEnrollments) &&
countResponses > 0 ) {
UIInternalLink.make(evaluationRow, "closed-eval-report-link",
UIMessage.make("controlevaluations.eval.report.link"),
new ReportParameters(ReportChooseGroupsProducer.VIEW_ID, evaluation.getId() ));
} else {
UIMessage.make(evaluationRow, "closed-eval-message",
"controlevaluations.eval.report.awaiting.responses");
}
} else {
UIMessage.make(evaluationRow, "closed-eval-message",
"controlevaluations.eval.report.viewable.on",
new String[] { df.format(evaluation.getViewDate()) });
}
if ( ! evaluation.getLocked().booleanValue() &&
evaluationsLogic.canRemoveEvaluation(currentUserId, evaluation.getId()) ) {
// evaluation removable
UIInternalLink.make(evaluationRow, "closed-eval-delete-link",
UIMessage.make("controlevaluations.eval.delete.link"),
new TemplateViewParameters( RemoveEvalProducer.VIEW_ID, evaluation.getId() ) );
}
}
} else {
UIMessage.make(tofill, "no-closed-evals", "controlevaluations.closed.none");
}
}
|
diff --git a/enabler/test/de/schildbach/pte/live/SeptaProviderLiveTest.java b/enabler/test/de/schildbach/pte/live/SeptaProviderLiveTest.java
index c1b38cd4..3f007bc9 100644
--- a/enabler/test/de/schildbach/pte/live/SeptaProviderLiveTest.java
+++ b/enabler/test/de/schildbach/pte/live/SeptaProviderLiveTest.java
@@ -1,97 +1,97 @@
/*
* Copyright 2010-2012 the original author or authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.schildbach.pte.live;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import de.schildbach.pte.NetworkProvider.Accessibility;
import de.schildbach.pte.NetworkProvider.WalkSpeed;
import de.schildbach.pte.SeptaProvider;
import de.schildbach.pte.dto.Location;
import de.schildbach.pte.dto.LocationType;
import de.schildbach.pte.dto.NearbyStationsResult;
import de.schildbach.pte.dto.QueryConnectionsResult;
import de.schildbach.pte.dto.QueryDeparturesResult;
/**
* @author Andreas Schildbach
*/
public class SeptaProviderLiveTest extends AbstractProviderLiveTest
{
public SeptaProviderLiveTest()
{
super(new SeptaProvider());
}
@Test
public void nearbyStations() throws Exception
{
final NearbyStationsResult result = provider.queryNearbyStations(new Location(LocationType.STATION, 2090227), 0, 0);
print(result);
}
@Test
public void nearbyStationsByCoordinate() throws Exception
{
final NearbyStationsResult result = provider.queryNearbyStations(new Location(LocationType.ADDRESS, 39954122, -75161705), 0, 0);
print(result);
}
@Test
public void queryDepartures() throws Exception
{
final QueryDeparturesResult result = provider.queryDepartures(2090227, 0, false);
print(result);
}
@Test
public void autocomplete() throws Exception
{
final List<Location> autocompletes = provider.autocompleteStations("Airport");
print(autocompletes);
}
@Test
public void shortConnection() throws Exception
{
- final QueryConnectionsResult result = queryConnections(new Location(LocationType.STATION, 2090227, null, "Main Street"), null, new Location(
- LocationType.STATION, 1015755, null, "Harbison Av + Unruh Av"), new Date(), true, ALL_PRODUCTS, WalkSpeed.NORMAL,
+ final QueryConnectionsResult result = queryConnections(new Location(LocationType.STATION, 1021532, null, "30th St Station"), null,
+ new Location(LocationType.STATION, 1001392, null, "15th St Station"), new Date(), true, ALL_PRODUCTS, WalkSpeed.NORMAL,
Accessibility.NEUTRAL);
System.out.println(result);
final QueryConnectionsResult laterResult = queryMoreConnections(result.context, true);
System.out.println(laterResult);
}
@Test
public void addressConnection() throws Exception
{
final QueryConnectionsResult result = queryConnections(new Location(LocationType.ADDRESS, 0, 40015670, -75209400, "Philadelphia 19127",
"3601 Main St"), null, new Location(LocationType.STATION, 2090227, null, "Main Street"), new Date(), true, ALL_PRODUCTS,
WalkSpeed.NORMAL, Accessibility.NEUTRAL);
System.out.println(result);
final QueryConnectionsResult laterResult = queryMoreConnections(result.context, true);
System.out.println(laterResult);
}
}
| true | true | public void shortConnection() throws Exception
{
final QueryConnectionsResult result = queryConnections(new Location(LocationType.STATION, 2090227, null, "Main Street"), null, new Location(
LocationType.STATION, 1015755, null, "Harbison Av + Unruh Av"), new Date(), true, ALL_PRODUCTS, WalkSpeed.NORMAL,
Accessibility.NEUTRAL);
System.out.println(result);
final QueryConnectionsResult laterResult = queryMoreConnections(result.context, true);
System.out.println(laterResult);
}
| public void shortConnection() throws Exception
{
final QueryConnectionsResult result = queryConnections(new Location(LocationType.STATION, 1021532, null, "30th St Station"), null,
new Location(LocationType.STATION, 1001392, null, "15th St Station"), new Date(), true, ALL_PRODUCTS, WalkSpeed.NORMAL,
Accessibility.NEUTRAL);
System.out.println(result);
final QueryConnectionsResult laterResult = queryMoreConnections(result.context, true);
System.out.println(laterResult);
}
|
diff --git a/jetty/src/main/java/org/mortbay/jetty/servlet/DefaultServlet.java b/jetty/src/main/java/org/mortbay/jetty/servlet/DefaultServlet.java
index 54cb220b7..a398e3779 100644
--- a/jetty/src/main/java/org/mortbay/jetty/servlet/DefaultServlet.java
+++ b/jetty/src/main/java/org/mortbay/jetty/servlet/DefaultServlet.java
@@ -1,936 +1,936 @@
// ========================================================================
// Copyright 199-2004 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// 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.mortbay.jetty.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.io.Buffer;
import org.mortbay.io.ByteArrayBuffer;
import org.mortbay.io.WriterOutputStream;
import org.mortbay.io.nio.NIOBuffer;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.HttpContent;
import org.mortbay.jetty.HttpFields;
import org.mortbay.jetty.HttpHeaders;
import org.mortbay.jetty.HttpMethods;
import org.mortbay.jetty.InclusiveByteRange;
import org.mortbay.jetty.MimeTypes;
import org.mortbay.jetty.ResourceCache;
import org.mortbay.jetty.Response;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.nio.NIOConnector;
import org.mortbay.log.Log;
import org.mortbay.resource.Resource;
import org.mortbay.resource.ResourceFactory;
import org.mortbay.util.IO;
import org.mortbay.util.MultiPartOutputStream;
import org.mortbay.util.TypeUtil;
import org.mortbay.util.URIUtil;
/* ------------------------------------------------------------ */
/** The default servlet.
* This servlet, normally mapped to /, provides the handling for static
* content, OPTION and TRACE methods for the context.
* The following initParameters are supported, these can be set either
* on the servlet itself or as ServletContext initParameters with a prefix
* of org.mortbay.jetty.servlet.Default. :
* <PRE>
* acceptRanges If true, range requests and responses are
* supported
*
* dirAllowed If true, directory listings are returned if no
* welcome file is found. Else 403 Forbidden.
*
* redirectWelcome If true, welcome files are redirected rather than
* forwarded to.
*
* gzip If set to true, then static content will be served as
* gzip content encoded if a matching resource is
* found ending with ".gz"
*
* resourceBase Set to replace the context resource base
*
* relativeResourceBase
* Set with a pathname relative to the base of the
* servlet context root. Useful for only serving static content out
* of only specific subdirectories.
*
* aliases If True, aliases of resources are allowed (eg. symbolic
* links and caps variations). May bypass security constraints.
*
* maxCacheSize The maximum total size of the cache or 0 for no cache.
* maxCachedFileSize The maximum size of a file to cache
* maxCachedFiles The maximum number of files to cache
* cacheType Set to "bio", "nio" or "both" to determine the type resource cache.
* A bio cached buffer may be used by nio but is not as efficient as an
* nio buffer. An nio cached buffer may not be used by bio.
*
* useFileMappedBuffer
* If set to true, it will use mapped file buffer to serve static content
* when using NIO connector. Setting this value to false means that
* a direct buffer will be used instead of a mapped file buffer.
* By default, this is set to true.
*
* cacheControl If set, all static content will have this value set as the cache-control
* header.
*
*
* </PRE>
*
*
* @author Greg Wilkins (gregw)
* @author Nigel Canonizado
*/
public class DefaultServlet extends HttpServlet implements ResourceFactory
{
private static ByteArrayBuffer BYTE_RANGES=new ByteArrayBuffer("bytes");
private ContextHandler.SContext _context;
private boolean _acceptRanges=true;
private boolean _dirAllowed=true;
private boolean _redirectWelcome=false;
private boolean _gzip=true;
private Resource _resourceBase;
private NIOResourceCache _nioCache;
private ResourceCache _bioCache;
private MimeTypes _mimeTypes;
private String[] _welcomes;
private boolean _aliases=false;
private boolean _useFileMappedBuffer=false;
ByteArrayBuffer _cacheControl;
/* ------------------------------------------------------------ */
public void init()
throws UnavailableException
{
ServletContext config=getServletContext();
_context = (ContextHandler.SContext)config;
_mimeTypes = _context.getContextHandler().getMimeTypes();
_welcomes = _context.getContextHandler().getWelcomeFiles();
if (_welcomes==null)
_welcomes=new String[] {"index.jsp","index.html"};
_acceptRanges=getInitBoolean("acceptRanges",_acceptRanges);
_dirAllowed=getInitBoolean("dirAllowed",_dirAllowed);
_redirectWelcome=getInitBoolean("redirectWelcome",_redirectWelcome);
_gzip=getInitBoolean("gzip",_gzip);
_aliases=getInitBoolean("aliases",_aliases);
_useFileMappedBuffer=getInitBoolean("useFileMappedBuffer",_useFileMappedBuffer);
String rrb = getInitParameter("relativeResourceBase");
if (rrb!=null)
{
try
{
_resourceBase=Resource.newResource(_context.getResource(URIUtil.SLASH)).addPath(rrb);
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION,e);
throw new UnavailableException(e.toString());
}
}
String rb=getInitParameter("resourceBase");
if (rrb != null && rb != null)
throw new UnavailableException("resourceBase & relativeResourceBase");
if (rb!=null)
{
try{_resourceBase=Resource.newResource(rb);}
catch (Exception e)
{
Log.warn(Log.EXCEPTION,e);
throw new UnavailableException(e.toString());
}
}
String t=getInitParameter("cacheControl");
if (t!=null)
_cacheControl=new ByteArrayBuffer(t);
try
{
if (_resourceBase==null)
_resourceBase=Resource.newResource(_context.getResource(URIUtil.SLASH));
String cache_type =getInitParameter("cacheType");
int max_cache_size=getInitInt("maxCacheSize", -2);
int max_cached_file_size=getInitInt("maxCachedFileSize", -2);
int max_cached_files=getInitInt("maxCachedFiles", -2);
if (cache_type==null || "nio".equals(cache_type)|| "both".equals(cache_type))
{
if (max_cache_size==-2 || max_cache_size>0)
{
_nioCache=new NIOResourceCache(_mimeTypes);
if (max_cache_size>0)
_nioCache.setMaxCacheSize(max_cache_size);
if (max_cached_file_size>=-1)
_nioCache.setMaxCachedFileSize(max_cached_file_size);
if (max_cached_files>=-1)
_nioCache.setMaxCachedFiles(max_cached_files);
_nioCache.start();
}
}
if ("bio".equals(cache_type)|| "both".equals(cache_type))
{
if (max_cache_size==-2 || max_cache_size>0)
{
_bioCache=new ResourceCache(_mimeTypes);
if (max_cache_size>0)
_bioCache.setMaxCacheSize(max_cache_size);
if (max_cached_file_size>=-1)
_bioCache.setMaxCachedFileSize(max_cached_file_size);
if (max_cached_files>=-1)
_bioCache.setMaxCachedFiles(max_cached_files);
_bioCache.start();
}
}
if (_nioCache==null)
_bioCache=null;
}
catch (Exception e)
{
Log.warn(Log.EXCEPTION,e);
throw new UnavailableException(e.toString());
}
if (Log.isDebugEnabled()) Log.debug("resource base = "+_resourceBase);
}
/* ------------------------------------------------------------ */
public String getInitParameter(String name)
{
String value=getServletContext().getInitParameter("org.mortbay.jetty.servlet.Default."+name);
if (value==null)
value=super.getInitParameter(name);
return value;
}
/* ------------------------------------------------------------ */
private boolean getInitBoolean(String name, boolean dft)
{
String value=getInitParameter(name);
if (value==null || value.length()==0)
return dft;
return (value.startsWith("t")||
value.startsWith("T")||
value.startsWith("y")||
value.startsWith("Y")||
value.startsWith("1"));
}
/* ------------------------------------------------------------ */
private int getInitInt(String name, int dft)
{
String value=getInitParameter(name);
if (value==null)
value=getInitParameter(name);
if (value!=null && value.length()>0)
return Integer.parseInt(value);
return dft;
}
/* ------------------------------------------------------------ */
/** get Resource to serve.
* Map a path to a resource. The default implementation calls
* HttpContext.getResource but derived servlets may provide
* their own mapping.
* @param pathInContext The path to find a resource for.
* @return The resource to serve.
*/
public Resource getResource(String pathInContext)
{
if (_resourceBase==null)
return null;
Resource r=null;
try
{
r = _resourceBase.addPath(pathInContext);
if (!_aliases && r.getAlias()!=null)
{
if (r.exists())
Log.warn("Aliased resource: "+r+"=="+r.getAlias());
return null;
}
if (Log.isDebugEnabled()) Log.debug("RESOURCE="+r);
}
catch (IOException e)
{
Log.ignore(e);
}
return r;
}
/* ------------------------------------------------------------ */
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String servletPath=null;
String pathInfo=null;
Enumeration reqRanges = null;
Boolean included =(Boolean)request.getAttribute(Dispatcher.__INCLUDE_JETTY);
if (included!=null && included.booleanValue())
{
servletPath=(String)request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
pathInfo=(String)request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);
if (servletPath==null)
{
servletPath=request.getServletPath();
pathInfo=request.getPathInfo();
}
}
else
{
included=Boolean.FALSE;
servletPath=request.getServletPath();
pathInfo=request.getPathInfo();
// Is this a range request?
reqRanges = request.getHeaders(HttpHeaders.RANGE);
if (reqRanges!=null && !reqRanges.hasMoreElements())
reqRanges=null;
}
String pathInContext=URIUtil.addPaths(servletPath,pathInfo);
boolean endsWithSlash=pathInContext.endsWith(URIUtil.SLASH);
// Can we gzip this request?
String pathInContextGz=null;
boolean gzip=false;
- if (_gzip && reqRanges==null && !endsWithSlash )
+ if (!included.booleanValue() && _gzip && reqRanges==null && !endsWithSlash )
{
String accept=request.getHeader(HttpHeaders.ACCEPT_ENCODING);
if (accept!=null && accept.indexOf("gzip")>=0)
gzip=true;
}
// Find the resource and content
Resource resource=null;
HttpContent content=null;
Connector connector = HttpConnection.getCurrentConnection().getConnector();
ResourceCache cache=(connector instanceof NIOConnector) ?_nioCache:_bioCache;
try
{
// Try gzipped content first
if (gzip)
{
pathInContextGz=pathInContext+".gz";
resource=getResource(pathInContextGz);
if (resource==null || !resource.exists()|| resource.isDirectory())
{
gzip=false;
pathInContextGz=null;
}
else if (cache!=null)
{
content=cache.lookup(pathInContextGz,resource);
if (content!=null)
resource=content.getResource();
}
if (resource==null || !resource.exists()|| resource.isDirectory())
{
gzip=false;
pathInContextGz=null;
}
}
// find resource
if (!gzip)
{
if (cache==null)
resource=getResource(pathInContext);
else
{
content=cache.lookup(pathInContext,this);
if (content!=null)
resource=content.getResource();
else
resource=getResource(pathInContext);
}
}
if (Log.isDebugEnabled())
Log.debug("resource="+resource+(content!=null?" content":""));
// Handle resource
if (resource==null || !resource.exists())
response.sendError(HttpServletResponse.SC_NOT_FOUND);
else if (!resource.isDirectory())
{
// ensure we have content
if (content==null)
content=new UnCachedContent(resource);
if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
{
if (gzip)
{
response.setHeader(HttpHeaders.CONTENT_ENCODING,"gzip");
String mt=_context.getMimeType(pathInContext);
if (mt!=null)
response.setContentType(mt);
}
sendData(request,response,included.booleanValue(),resource,content,reqRanges);
}
}
else
{
String welcome=null;
if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.mortbay.jetty.nullPathInfo")!=null))
{
StringBuffer buf=request.getRequestURL();
int param=buf.lastIndexOf(";");
if (param<0)
buf.append('/');
else
buf.insert(param,'/');
String q=request.getQueryString();
if (q!=null&&q.length()!=0)
{
buf.append('?');
buf.append(q);
}
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(buf.toString()));
}
// else look for a welcome file
else if (null!=(welcome=getWelcomeFile(resource)))
{
String ipath=URIUtil.addPaths(pathInContext,welcome);
if (_redirectWelcome)
{
// Redirect to the index
response.setContentLength(0);
String q=request.getQueryString();
if (q!=null&&q.length()!=0)
response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath)+"?"+q);
else
response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath));
}
else
{
// Forward to the index
RequestDispatcher dispatcher=request.getRequestDispatcher(ipath);
if (dispatcher!=null)
{
if (included.booleanValue())
dispatcher.include(request,response);
else
{
request.setAttribute("org.mortbay.jetty.welcome",ipath);
dispatcher.forward(request,response);
}
}
}
}
else
{
content=new UnCachedContent(resource);
if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
sendDirectory(request,response,resource,pathInContext.length()>1);
}
}
}
catch(IllegalArgumentException e)
{
Log.warn(Log.EXCEPTION,e);
}
finally
{
if (content!=null)
content.release();
else if (resource!=null)
resource.release();
}
}
/* ------------------------------------------------------------ */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doGet(request,response);
}
/* ------------------------------------------------------------ */
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doTrace(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
protected void doTrace(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
/* ------------------------------------------------------------ */
/**
* Finds a matching welcome file for the supplied {@link Resource}. This will be the first entry in the list of
* configured {@link #_welcomes welcome files} that existing within the directory referenced by the <code>Resource</code>.
* If the resource is not a directory, or no matching file is found, then <code>null</code> is returned.
* The list of welcome files is read from the {@link ContextHandler} for this servlet, or
* <code>"index.jsp" , "index.html"</code> if that is <code>null</code>.
* @param resource
* @return The name of the matching welcome file.
* @throws IOException
* @throws MalformedURLException
*/
private String getWelcomeFile(Resource resource) throws MalformedURLException, IOException
{
if (!resource.isDirectory() || _welcomes==null)
return null;
for (int i=0;i<_welcomes.length;i++)
{
Resource welcome=resource.addPath(_welcomes[i]);
if (welcome.exists())
return _welcomes[i];
}
return null;
}
/* ------------------------------------------------------------ */
/* Check modification date headers.
*/
protected boolean passConditionalHeaders(HttpServletRequest request,HttpServletResponse response, Resource resource, HttpContent content)
throws IOException
{
if (!request.getMethod().equals(HttpMethods.HEAD) )
{
String ifms=request.getHeader(HttpHeaders.IF_MODIFIED_SINCE);
if (ifms!=null)
{
if (content!=null)
{
Buffer mdlm=content.getLastModified();
if (mdlm!=null)
{
if (ifms.equals(mdlm.toString()))
{
response.reset();
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.flushBuffer();
return false;
}
}
}
long ifmsl=request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
if (ifmsl!=-1)
{
if (resource.lastModified()/1000 <= ifmsl/1000)
{
response.reset();
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.flushBuffer();
return false;
}
}
}
// Parse the if[un]modified dates and compare to resource
long date=request.getDateHeader(HttpHeaders.IF_UNMODIFIED_SINCE);
if (date!=-1)
{
if (resource.lastModified()/1000 > date/1000)
{
response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
return false;
}
}
}
return true;
}
/* ------------------------------------------------------------------- */
protected void sendDirectory(HttpServletRequest request,
HttpServletResponse response,
Resource resource,
boolean parent)
throws IOException
{
if (!_dirAllowed)
{
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
byte[] data=null;
String base = URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH);
String dir = resource.getListHTML(base,parent);
if (dir==null)
{
response.sendError(HttpServletResponse.SC_FORBIDDEN,
"No directory");
return;
}
data=dir.getBytes("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setContentLength(data.length);
response.getOutputStream().write(data);
}
/* ------------------------------------------------------------ */
protected void sendData(HttpServletRequest request,
HttpServletResponse response,
boolean include,
Resource resource,
HttpContent content,
Enumeration reqRanges)
throws IOException
{
long content_length=resource.length();
// Get the output stream (or writer)
OutputStream out =null;
try{out = response.getOutputStream();}
catch(IllegalStateException e) {out = new WriterOutputStream(response.getWriter());}
if ( reqRanges == null || !reqRanges.hasMoreElements())
{
// if there were no ranges, send entire entity
if (include)
{
resource.writeTo(out,0,content_length);
}
else
{
// See if a short direct method can be used?
if (out instanceof HttpConnection.Output)
{
if (_cacheControl!=null)
{
if (response instanceof Response)
((Response)response).getHttpFields().put(HttpHeaders.CACHE_CONTROL_BUFFER,_cacheControl);
else
response.setHeader(HttpHeaders.CACHE_CONTROL,_cacheControl.toString());
}
((HttpConnection.Output)out).sendContent(content);
}
else
{
// Write content normally
writeHeaders(response,content,content_length);
resource.writeTo(out,0,content_length);
}
}
}
else
{
// Parse the satisfiable ranges
List ranges =InclusiveByteRange.satisfiableRanges(reqRanges,content_length);
// if there are no satisfiable ranges, send 416 response
if (ranges==null || ranges.size()==0)
{
writeHeaders(response, content, content_length);
response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
response.setHeader(HttpHeaders.CONTENT_RANGE,
InclusiveByteRange.to416HeaderRangeString(content_length));
resource.writeTo(out,0,content_length);
return;
}
// if there is only a single valid range (must be satisfiable
// since were here now), send that range with a 216 response
if ( ranges.size()== 1)
{
InclusiveByteRange singleSatisfiableRange =
(InclusiveByteRange)ranges.get(0);
long singleLength = singleSatisfiableRange.getSize(content_length);
writeHeaders(response,content,singleLength );
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setHeader(HttpHeaders.CONTENT_RANGE,
singleSatisfiableRange.toHeaderRangeString(content_length));
resource.writeTo(out,singleSatisfiableRange.getFirst(content_length),singleLength);
return;
}
// multiple non-overlapping valid ranges cause a multipart
// 216 response which does not require an overall
// content-length header
//
writeHeaders(response,content,-1);
String mimetype=content.getContentType().toString();
MultiPartOutputStream multi = new MultiPartOutputStream(out);
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
// If the request has a "Request-Range" header then we need to
// send an old style multipart/x-byteranges Content-Type. This
// keeps Netscape and acrobat happy. This is what Apache does.
String ctp;
if (request.getHeader(HttpHeaders.REQUEST_RANGE)!=null)
ctp = "multipart/x-byteranges; boundary=";
else
ctp = "multipart/byteranges; boundary=";
response.setContentType(ctp+multi.getBoundary());
InputStream in=resource.getInputStream();
long pos=0;
for (int i=0;i<ranges.size();i++)
{
InclusiveByteRange ibr = (InclusiveByteRange) ranges.get(i);
String header=HttpHeaders.CONTENT_RANGE+": "+
ibr.toHeaderRangeString(content_length);
multi.startPart(mimetype,new String[]{header});
long start=ibr.getFirst(content_length);
long size=ibr.getSize(content_length);
if (in!=null)
{
// Handle non cached resource
if (start<pos)
{
in.close();
in=resource.getInputStream();
pos=0;
}
if (pos<start)
{
in.skip(start-pos);
pos=start;
}
IO.copy(in,multi,size);
pos+=size;
}
else
// Handle cached resource
(resource).writeTo(multi,start,size);
}
if (in!=null)
in.close();
multi.close();
}
return;
}
/* ------------------------------------------------------------ */
protected void writeHeaders(HttpServletResponse response,HttpContent content,long count)
throws IOException
{
if (content.getContentType()!=null)
response.setContentType(content.getContentType().toString());
if (response instanceof Response)
{
Response r=(Response)response;
HttpFields fields = r.getHttpFields();
if (content.getLastModified()!=null)
fields.put(HttpHeaders.LAST_MODIFIED_BUFFER,content.getLastModified());
else if (content.getResource()!=null)
{
long lml=content.getResource().lastModified();
if (lml!=-1)
fields.putDateField(HttpHeaders.LAST_MODIFIED_BUFFER,lml);
}
if (count != -1)
r.setLongContentLength(count);
if (_acceptRanges)
fields.put(HttpHeaders.ACCEPT_RANGES_BUFFER,BYTE_RANGES);
if (_cacheControl!=null)
fields.put(HttpHeaders.CACHE_CONTROL_BUFFER,_cacheControl);
}
else
{
if (content.getLastModified()!=null)
response.setHeader(HttpHeaders.LAST_MODIFIED,content.getLastModified().toString());
else
response.setDateHeader(HttpHeaders.LAST_MODIFIED,content.getResource().lastModified());
if (count != -1)
{
if (count<Integer.MAX_VALUE)
response.setContentLength((int)count);
else
response.setHeader(HttpHeaders.CONTENT_LENGTH,TypeUtil.toString(count));
}
if (_acceptRanges)
response.setHeader(HttpHeaders.ACCEPT_RANGES,"bytes");
if (_cacheControl!=null)
response.setHeader(HttpHeaders.CACHE_CONTROL,_cacheControl.toString());
}
}
/* ------------------------------------------------------------ */
/*
* @see javax.servlet.Servlet#destroy()
*/
public void destroy()
{
try
{
if (_nioCache!=null)
_nioCache.stop();
if (_bioCache!=null)
_bioCache.stop();
}
catch(Exception e)
{
Log.warn(Log.EXCEPTION,e);
}
finally
{
super.destroy();
}
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private class UnCachedContent implements HttpContent
{
Resource _resource;
UnCachedContent(Resource resource)
{
_resource=resource;
}
/* ------------------------------------------------------------ */
public Buffer getContentType()
{
return _mimeTypes.getMimeByExtension(_resource.toString());
}
/* ------------------------------------------------------------ */
public Buffer getLastModified()
{
return null;
}
/* ------------------------------------------------------------ */
public Buffer getBuffer()
{
return null;
}
/* ------------------------------------------------------------ */
public long getContentLength()
{
return _resource.length();
}
/* ------------------------------------------------------------ */
public InputStream getInputStream() throws IOException
{
return _resource.getInputStream();
}
/* ------------------------------------------------------------ */
public Resource getResource()
{
return _resource;
}
/* ------------------------------------------------------------ */
public void release()
{
_resource.release();
_resource=null;
}
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
class NIOResourceCache extends ResourceCache
{
/* ------------------------------------------------------------ */
public NIOResourceCache(MimeTypes mimeTypes)
{
super(mimeTypes);
}
/* ------------------------------------------------------------ */
protected void fill(Content content) throws IOException
{
Buffer buffer=null;
Resource resource=content.getResource();
long length=resource.length();
if (_useFileMappedBuffer && resource.getFile()!=null)
{
File file = resource.getFile();
if (file != null)
buffer = new NIOBuffer(file);
}
else
{
InputStream is = resource.getInputStream();
try
{
Connector connector = HttpConnection.getCurrentConnection().getConnector();
buffer = new NIOBuffer((int) length, ((NIOConnector)connector).getUseDirectBuffers()?NIOBuffer.DIRECT:NIOBuffer.INDIRECT);
}
catch(OutOfMemoryError e)
{
Log.warn(e.toString());
Log.debug(e);
buffer = new NIOBuffer((int) length, NIOBuffer.INDIRECT);
}
buffer.readFrom(is,(int)length);
is.close();
}
content.setBuffer(buffer);
}
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String servletPath=null;
String pathInfo=null;
Enumeration reqRanges = null;
Boolean included =(Boolean)request.getAttribute(Dispatcher.__INCLUDE_JETTY);
if (included!=null && included.booleanValue())
{
servletPath=(String)request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
pathInfo=(String)request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);
if (servletPath==null)
{
servletPath=request.getServletPath();
pathInfo=request.getPathInfo();
}
}
else
{
included=Boolean.FALSE;
servletPath=request.getServletPath();
pathInfo=request.getPathInfo();
// Is this a range request?
reqRanges = request.getHeaders(HttpHeaders.RANGE);
if (reqRanges!=null && !reqRanges.hasMoreElements())
reqRanges=null;
}
String pathInContext=URIUtil.addPaths(servletPath,pathInfo);
boolean endsWithSlash=pathInContext.endsWith(URIUtil.SLASH);
// Can we gzip this request?
String pathInContextGz=null;
boolean gzip=false;
if (_gzip && reqRanges==null && !endsWithSlash )
{
String accept=request.getHeader(HttpHeaders.ACCEPT_ENCODING);
if (accept!=null && accept.indexOf("gzip")>=0)
gzip=true;
}
// Find the resource and content
Resource resource=null;
HttpContent content=null;
Connector connector = HttpConnection.getCurrentConnection().getConnector();
ResourceCache cache=(connector instanceof NIOConnector) ?_nioCache:_bioCache;
try
{
// Try gzipped content first
if (gzip)
{
pathInContextGz=pathInContext+".gz";
resource=getResource(pathInContextGz);
if (resource==null || !resource.exists()|| resource.isDirectory())
{
gzip=false;
pathInContextGz=null;
}
else if (cache!=null)
{
content=cache.lookup(pathInContextGz,resource);
if (content!=null)
resource=content.getResource();
}
if (resource==null || !resource.exists()|| resource.isDirectory())
{
gzip=false;
pathInContextGz=null;
}
}
// find resource
if (!gzip)
{
if (cache==null)
resource=getResource(pathInContext);
else
{
content=cache.lookup(pathInContext,this);
if (content!=null)
resource=content.getResource();
else
resource=getResource(pathInContext);
}
}
if (Log.isDebugEnabled())
Log.debug("resource="+resource+(content!=null?" content":""));
// Handle resource
if (resource==null || !resource.exists())
response.sendError(HttpServletResponse.SC_NOT_FOUND);
else if (!resource.isDirectory())
{
// ensure we have content
if (content==null)
content=new UnCachedContent(resource);
if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
{
if (gzip)
{
response.setHeader(HttpHeaders.CONTENT_ENCODING,"gzip");
String mt=_context.getMimeType(pathInContext);
if (mt!=null)
response.setContentType(mt);
}
sendData(request,response,included.booleanValue(),resource,content,reqRanges);
}
}
else
{
String welcome=null;
if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.mortbay.jetty.nullPathInfo")!=null))
{
StringBuffer buf=request.getRequestURL();
int param=buf.lastIndexOf(";");
if (param<0)
buf.append('/');
else
buf.insert(param,'/');
String q=request.getQueryString();
if (q!=null&&q.length()!=0)
{
buf.append('?');
buf.append(q);
}
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(buf.toString()));
}
// else look for a welcome file
else if (null!=(welcome=getWelcomeFile(resource)))
{
String ipath=URIUtil.addPaths(pathInContext,welcome);
if (_redirectWelcome)
{
// Redirect to the index
response.setContentLength(0);
String q=request.getQueryString();
if (q!=null&&q.length()!=0)
response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath)+"?"+q);
else
response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath));
}
else
{
// Forward to the index
RequestDispatcher dispatcher=request.getRequestDispatcher(ipath);
if (dispatcher!=null)
{
if (included.booleanValue())
dispatcher.include(request,response);
else
{
request.setAttribute("org.mortbay.jetty.welcome",ipath);
dispatcher.forward(request,response);
}
}
}
}
else
{
content=new UnCachedContent(resource);
if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
sendDirectory(request,response,resource,pathInContext.length()>1);
}
}
}
catch(IllegalArgumentException e)
{
Log.warn(Log.EXCEPTION,e);
}
finally
{
if (content!=null)
content.release();
else if (resource!=null)
resource.release();
}
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String servletPath=null;
String pathInfo=null;
Enumeration reqRanges = null;
Boolean included =(Boolean)request.getAttribute(Dispatcher.__INCLUDE_JETTY);
if (included!=null && included.booleanValue())
{
servletPath=(String)request.getAttribute(Dispatcher.__INCLUDE_SERVLET_PATH);
pathInfo=(String)request.getAttribute(Dispatcher.__INCLUDE_PATH_INFO);
if (servletPath==null)
{
servletPath=request.getServletPath();
pathInfo=request.getPathInfo();
}
}
else
{
included=Boolean.FALSE;
servletPath=request.getServletPath();
pathInfo=request.getPathInfo();
// Is this a range request?
reqRanges = request.getHeaders(HttpHeaders.RANGE);
if (reqRanges!=null && !reqRanges.hasMoreElements())
reqRanges=null;
}
String pathInContext=URIUtil.addPaths(servletPath,pathInfo);
boolean endsWithSlash=pathInContext.endsWith(URIUtil.SLASH);
// Can we gzip this request?
String pathInContextGz=null;
boolean gzip=false;
if (!included.booleanValue() && _gzip && reqRanges==null && !endsWithSlash )
{
String accept=request.getHeader(HttpHeaders.ACCEPT_ENCODING);
if (accept!=null && accept.indexOf("gzip")>=0)
gzip=true;
}
// Find the resource and content
Resource resource=null;
HttpContent content=null;
Connector connector = HttpConnection.getCurrentConnection().getConnector();
ResourceCache cache=(connector instanceof NIOConnector) ?_nioCache:_bioCache;
try
{
// Try gzipped content first
if (gzip)
{
pathInContextGz=pathInContext+".gz";
resource=getResource(pathInContextGz);
if (resource==null || !resource.exists()|| resource.isDirectory())
{
gzip=false;
pathInContextGz=null;
}
else if (cache!=null)
{
content=cache.lookup(pathInContextGz,resource);
if (content!=null)
resource=content.getResource();
}
if (resource==null || !resource.exists()|| resource.isDirectory())
{
gzip=false;
pathInContextGz=null;
}
}
// find resource
if (!gzip)
{
if (cache==null)
resource=getResource(pathInContext);
else
{
content=cache.lookup(pathInContext,this);
if (content!=null)
resource=content.getResource();
else
resource=getResource(pathInContext);
}
}
if (Log.isDebugEnabled())
Log.debug("resource="+resource+(content!=null?" content":""));
// Handle resource
if (resource==null || !resource.exists())
response.sendError(HttpServletResponse.SC_NOT_FOUND);
else if (!resource.isDirectory())
{
// ensure we have content
if (content==null)
content=new UnCachedContent(resource);
if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
{
if (gzip)
{
response.setHeader(HttpHeaders.CONTENT_ENCODING,"gzip");
String mt=_context.getMimeType(pathInContext);
if (mt!=null)
response.setContentType(mt);
}
sendData(request,response,included.booleanValue(),resource,content,reqRanges);
}
}
else
{
String welcome=null;
if (!endsWithSlash || (pathInContext.length()==1 && request.getAttribute("org.mortbay.jetty.nullPathInfo")!=null))
{
StringBuffer buf=request.getRequestURL();
int param=buf.lastIndexOf(";");
if (param<0)
buf.append('/');
else
buf.insert(param,'/');
String q=request.getQueryString();
if (q!=null&&q.length()!=0)
{
buf.append('?');
buf.append(q);
}
response.setContentLength(0);
response.sendRedirect(response.encodeRedirectURL(buf.toString()));
}
// else look for a welcome file
else if (null!=(welcome=getWelcomeFile(resource)))
{
String ipath=URIUtil.addPaths(pathInContext,welcome);
if (_redirectWelcome)
{
// Redirect to the index
response.setContentLength(0);
String q=request.getQueryString();
if (q!=null&&q.length()!=0)
response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath)+"?"+q);
else
response.sendRedirect(URIUtil.addPaths( _context.getContextPath(),ipath));
}
else
{
// Forward to the index
RequestDispatcher dispatcher=request.getRequestDispatcher(ipath);
if (dispatcher!=null)
{
if (included.booleanValue())
dispatcher.include(request,response);
else
{
request.setAttribute("org.mortbay.jetty.welcome",ipath);
dispatcher.forward(request,response);
}
}
}
}
else
{
content=new UnCachedContent(resource);
if (included.booleanValue() || passConditionalHeaders(request,response, resource,content))
sendDirectory(request,response,resource,pathInContext.length()>1);
}
}
}
catch(IllegalArgumentException e)
{
Log.warn(Log.EXCEPTION,e);
}
finally
{
if (content!=null)
content.release();
else if (resource!=null)
resource.release();
}
}
|
diff --git a/src/dirmi/io/QueuedBroker.java b/src/dirmi/io/QueuedBroker.java
index 1e59508..5194b41 100644
--- a/src/dirmi/io/QueuedBroker.java
+++ b/src/dirmi/io/QueuedBroker.java
@@ -1,186 +1,191 @@
/*
* Copyright 2007 Brian S O'Neill
*
* 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 dirmi.io;
import java.io.InterruptedIOException;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Broker which vends connections from queues.
*
* @author Brian S O'Neill
*/
public class QueuedBroker implements Broker {
private final BlockingQueue<Connection> mReadyToConnect;
private final BlockingQueue<Connection> mReadyToAccept;
private volatile boolean mClosed;
public QueuedBroker() {
this(new LinkedBlockingQueue<Connection>(),
new LinkedBlockingQueue<Connection>());
}
public QueuedBroker(BlockingQueue<Connection> connectQueue,
BlockingQueue<Connection> acceptQueue)
{
mReadyToConnect = connectQueue;
mReadyToAccept = acceptQueue;
}
public Connection connect() throws IOException {
checkClosed();
try {
Connection con = mReadyToConnect.take();
if (con == Unconnection.THE) {
connectClose(); // enqueue again for any other waiters
throw new IOException("Broker is closed");
}
return con;
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
public Connection tryConnect(long time, TimeUnit unit) throws IOException {
checkClosed();
try {
Connection con = mReadyToConnect.poll(time, unit);
if (con == Unconnection.THE) {
connectClose(); // enqueue again for any other waiters
throw new IOException("Broker is closed");
}
return con;
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
public Connection accept() throws IOException {
checkClosed();
try {
Connection con = mReadyToAccept.take();
if (con == Unconnection.THE) {
acceptClose(); // enqueue again for any other waiters
throw new IOException("Broker is closed");
}
return con;
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
public Connection tryAccept(long time, TimeUnit unit) throws IOException {
checkClosed();
try {
Connection con = mReadyToAccept.poll(time, unit);
if (con == Unconnection.THE) {
acceptClose(); // enqueue again for any other waiters
throw new IOException("Broker is closed");
}
return con;
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
/**
* Pass connection to connect queue, possibly blocking.
*/
public void connected(Connection con) throws IOException {
if (mClosed || mReadyToConnect == null) {
con.close();
return;
}
try {
mReadyToConnect.put(con);
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
/**
* Pass connection to accept queue, possibly blocking.
*/
public void accepted(Connection con) throws IOException {
if (mClosed || mReadyToAccept == null) {
con.close();
return;
}
try {
mReadyToAccept.put(con);
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
public void close() throws IOException {
mClosed = true;
// Drain any existing connections.
- Connection con;
- while ((con = mReadyToConnect.poll()) != null) {
- try {
- con.close();
- } catch (IOException e) {
- // Don't care.
+ if (mReadyToConnect != null) {
+ Connection con;
+ while ((con = mReadyToConnect.poll()) != null) {
+ try {
+ con.close();
+ } catch (IOException e) {
+ // Don't care.
+ }
}
}
- while ((con = mReadyToAccept.poll()) != null) {
- try {
- con.close();
- } catch (IOException e) {
- // Don't care.
+ if (mReadyToAccept != null) {
+ Connection con;
+ while ((con = mReadyToAccept.poll()) != null) {
+ try {
+ con.close();
+ } catch (IOException e) {
+ // Don't care.
+ }
}
}
// Notify any waiters.
connectClose();
acceptClose();
}
protected void checkClosed() throws IOException {
if (mClosed) {
throw new IOException("Broker is closed");
}
}
private void connectClose() throws IOException {
if (mReadyToConnect != null) {
try {
mReadyToConnect.put(Unconnection.THE);
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
}
private void acceptClose() throws IOException {
if (mReadyToAccept != null) {
try {
mReadyToAccept.put(Unconnection.THE);
} catch (InterruptedException e) {
throw new InterruptedIOException();
}
}
}
}
| false | true | public void close() throws IOException {
mClosed = true;
// Drain any existing connections.
Connection con;
while ((con = mReadyToConnect.poll()) != null) {
try {
con.close();
} catch (IOException e) {
// Don't care.
}
}
while ((con = mReadyToAccept.poll()) != null) {
try {
con.close();
} catch (IOException e) {
// Don't care.
}
}
// Notify any waiters.
connectClose();
acceptClose();
}
| public void close() throws IOException {
mClosed = true;
// Drain any existing connections.
if (mReadyToConnect != null) {
Connection con;
while ((con = mReadyToConnect.poll()) != null) {
try {
con.close();
} catch (IOException e) {
// Don't care.
}
}
}
if (mReadyToAccept != null) {
Connection con;
while ((con = mReadyToAccept.poll()) != null) {
try {
con.close();
} catch (IOException e) {
// Don't care.
}
}
}
// Notify any waiters.
connectClose();
acceptClose();
}
|
diff --git a/Bibliothek/src/view/LoanTableModel.java b/Bibliothek/src/view/LoanTableModel.java
index cd96f85..08b5dfb 100644
--- a/Bibliothek/src/view/LoanTableModel.java
+++ b/Bibliothek/src/view/LoanTableModel.java
@@ -1,77 +1,77 @@
package view;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import domain.Book;
import domain.Copy;
import domain.Library;
import domain.Loan;
public class LoanTableModel extends AbstractTableModel {
private Library lib;
public LoanTableModel(Library lib) {
this.lib = lib;
}
private String[] columnNames = new String[] {
"Status", "Copy-ID", "Title", "Lend to"
};
private static final long serialVersionUID = 3924577490865829762L;
Class[] columnTypes = new Class[] {
String.class, String.class, String.class, String.class
};
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnTypes[columnIndex];
}
boolean[] columnEditables = new boolean[] {
false, false, false, false
};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
@Override
public int getColumnCount() {
return columnTypes.length;
}
@Override
public int getRowCount() {
return lib.getLentLoans().size();
}
@Override
public Object getValueAt(int arg0, int arg1) {
List<Loan> loans = lib.getLentLoans();
if(loans.size() < 1)
return "";
Loan loan = loans.get(arg0);
switch (arg1) {
case 0:
if(loan.isOverdue()){
return (String)"Overdue!";
}
return (String)"Ok";
case 1:
- return loan.getCopy().getInventoryNumber();
+ return "" + loan.getCopy().getInventoryNumber();
case 2:
return loan.getCopy().getTitle().getName();
default:
return (String)loan.getCustomer().getFirstname() + " " + loan.getCustomer().getLastname();
}
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
}
| true | true | public Object getValueAt(int arg0, int arg1) {
List<Loan> loans = lib.getLentLoans();
if(loans.size() < 1)
return "";
Loan loan = loans.get(arg0);
switch (arg1) {
case 0:
if(loan.isOverdue()){
return (String)"Overdue!";
}
return (String)"Ok";
case 1:
return loan.getCopy().getInventoryNumber();
case 2:
return loan.getCopy().getTitle().getName();
default:
return (String)loan.getCustomer().getFirstname() + " " + loan.getCustomer().getLastname();
}
}
| public Object getValueAt(int arg0, int arg1) {
List<Loan> loans = lib.getLentLoans();
if(loans.size() < 1)
return "";
Loan loan = loans.get(arg0);
switch (arg1) {
case 0:
if(loan.isOverdue()){
return (String)"Overdue!";
}
return (String)"Ok";
case 1:
return "" + loan.getCopy().getInventoryNumber();
case 2:
return loan.getCopy().getTitle().getName();
default:
return (String)loan.getCustomer().getFirstname() + " " + loan.getCustomer().getLastname();
}
}
|
diff --git a/wordswithcrosses/src/com/adamrosenfield/wordswithcrosses/io/KingFeaturesPlaintextIO.java b/wordswithcrosses/src/com/adamrosenfield/wordswithcrosses/io/KingFeaturesPlaintextIO.java
index ec70cf2..1a3b2e0 100644
--- a/wordswithcrosses/src/com/adamrosenfield/wordswithcrosses/io/KingFeaturesPlaintextIO.java
+++ b/wordswithcrosses/src/com/adamrosenfield/wordswithcrosses/io/KingFeaturesPlaintextIO.java
@@ -1,210 +1,210 @@
package com.adamrosenfield.wordswithcrosses.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;
import android.util.SparseArray;
import com.adamrosenfield.wordswithcrosses.io.charset.MacRoman;
import com.adamrosenfield.wordswithcrosses.puz.Box;
import com.adamrosenfield.wordswithcrosses.puz.Puzzle;
/**
* Converts a puzzle from the plaintext format used by King Features Syndicate
* puzzles to the Across Lite .puz format. The format is:
*
* -Grid shape and clue numbers (redundant)
* -Solution grid
* -Across Clues
* -Down Clues
*
* Each section begins with a { character, and each line except the last in a section
* ends with a | character. The charset used is Mac Roman.
*
* For an example puzzle in this format, see:
* http://joseph.king-online.com/clues/20130528.txt
*/
public class KingFeaturesPlaintextIO {
private static final Logger LOG = Logger.getLogger("com.adamrosenfield.wordswithcrosses");
/**
* Take an InputStream containing a plaintext puzzle to a OutputStream containing
* the generated .puz file. Returns true if the process succeeded, or false if it fails
* (for example, if the plaintext file is not in a valid format).
*/
public static boolean convertKFPuzzle(InputStream is, OutputStream os,
String title, String author, String copyright, Calendar date) {
Puzzle puz = new Puzzle();
Scanner scanner = new Scanner(new InputStreamReader(is, new MacRoman()));
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: File empty.");
return false;
}
String line = scanner.nextLine();
if (!line.startsWith("{") || !scanner.hasNextLine()) {
LOG.warning("KFIO: First line format incorrect.");
return false;
}
// Skip over redundant grid information.
line = scanner.nextLine();
while (!line.startsWith("{")) {
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Grid information.");
return false;
}
line = scanner.nextLine();
}
// Process solution grid.
List<char[]> solGrid = new ArrayList<char[]>();
line = line.substring(1, line.length()-2);
String[] rowString = line.split(" ");
int width = rowString.length;
do {
if (line.endsWith(" |")) {
line = line.substring(0, line.length()-2);
}
rowString = line.split(" ");
if (rowString.length != width) {
LOG.warning("KFIO: Not a square grid.");
return false;
}
char[] row = new char[width];
for (int x = 0; x < width; x++) {
row[x] = rowString[x].charAt(0);
}
solGrid.add(row);
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Solution grid.");
return false;
}
line = scanner.nextLine();
} while (!line.startsWith("{"));
// Convert solution grid into Box grid.
int height = solGrid.size();
puz.setWidth(width);
puz.setHeight(height);
Box[][] boxes = new Box[height][width];
- for (int x = 0; x < height; x++) {
- char[] row = solGrid.get(x);
- for (int y = 0; y < width; y++) {
- if (row[y] != '#') {
- boxes[x][y] = new Box();
- boxes[x][y].setSolution(row[y]);
- boxes[x][y].setResponse(' ');
+ for (int r = 0; r < height; r++) {
+ char[] row = solGrid.get(r);
+ for (int c = 0; c < width; c++) {
+ if (row[c] != '#') {
+ boxes[r][c] = new Box();
+ boxes[r][c].setSolution(row[c]);
+ boxes[r][c].setResponse(' ');
}
}
}
puz.setBoxes(boxes);
// Process clues.
SparseArray<String> acrossNumToClueMap = new SparseArray<String>();
line = line.substring(1);
int clueNum;
do {
if (line.endsWith(" |")) {
line = line.substring(0, line.length()-2);
}
clueNum = 0;
int i = 0;
while (line.charAt(i) != '.') {
if (clueNum != 0) {
clueNum *= 10;
}
clueNum += line.charAt(i) - '0';
i++;
}
String clue = line.substring(i+2).trim();
acrossNumToClueMap.put(clueNum, clue);
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Across clues.");
return false;
}
line = scanner.nextLine();
} while (!line.startsWith("{"));
int maxClueNum = clueNum;
SparseArray<String> downNumToClueMap = new SparseArray<String>();
line = line.substring(1);
boolean finished = false;
do {
if (line.endsWith(" |")) {
line = line.substring(0, line.length()-2);
} else {
finished = true;
}
clueNum = 0;
int i = 0;
while (line.charAt(i) != '.') {
if (clueNum != 0) {
clueNum *= 10;
}
clueNum += line.charAt(i) - '0';
i++;
}
String clue = line.substring(i+2).trim();
downNumToClueMap.put(clueNum, clue);
if(!finished) {
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Down clues.");
return false;
}
line = scanner.nextLine();
}
} while (!finished);
maxClueNum = clueNum > maxClueNum ? clueNum : maxClueNum;
// Convert clues into raw clues format.
int numberOfClues = acrossNumToClueMap.size() + downNumToClueMap.size();
puz.setNumberOfClues(numberOfClues);
String[] rawClues = new String[numberOfClues];
int i = 0;
for (clueNum = 1; clueNum <= maxClueNum; clueNum++) {
String clue = acrossNumToClueMap.get(clueNum);
if (clue != null) {
rawClues[i] = clue;
i++;
}
clue = downNumToClueMap.get(clueNum);
if (clue != null) {
rawClues[i] = clue;
i++;
}
}
puz.setRawClues(rawClues);
// Set puzzle information
puz.setTitle(title);
puz.setAuthor(author);
puz.setDate(date);
puz.setCopyright(copyright);
try {
IO.save(puz, os);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
| true | true | public static boolean convertKFPuzzle(InputStream is, OutputStream os,
String title, String author, String copyright, Calendar date) {
Puzzle puz = new Puzzle();
Scanner scanner = new Scanner(new InputStreamReader(is, new MacRoman()));
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: File empty.");
return false;
}
String line = scanner.nextLine();
if (!line.startsWith("{") || !scanner.hasNextLine()) {
LOG.warning("KFIO: First line format incorrect.");
return false;
}
// Skip over redundant grid information.
line = scanner.nextLine();
while (!line.startsWith("{")) {
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Grid information.");
return false;
}
line = scanner.nextLine();
}
// Process solution grid.
List<char[]> solGrid = new ArrayList<char[]>();
line = line.substring(1, line.length()-2);
String[] rowString = line.split(" ");
int width = rowString.length;
do {
if (line.endsWith(" |")) {
line = line.substring(0, line.length()-2);
}
rowString = line.split(" ");
if (rowString.length != width) {
LOG.warning("KFIO: Not a square grid.");
return false;
}
char[] row = new char[width];
for (int x = 0; x < width; x++) {
row[x] = rowString[x].charAt(0);
}
solGrid.add(row);
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Solution grid.");
return false;
}
line = scanner.nextLine();
} while (!line.startsWith("{"));
// Convert solution grid into Box grid.
int height = solGrid.size();
puz.setWidth(width);
puz.setHeight(height);
Box[][] boxes = new Box[height][width];
for (int x = 0; x < height; x++) {
char[] row = solGrid.get(x);
for (int y = 0; y < width; y++) {
if (row[y] != '#') {
boxes[x][y] = new Box();
boxes[x][y].setSolution(row[y]);
boxes[x][y].setResponse(' ');
}
}
}
puz.setBoxes(boxes);
// Process clues.
SparseArray<String> acrossNumToClueMap = new SparseArray<String>();
line = line.substring(1);
int clueNum;
do {
if (line.endsWith(" |")) {
line = line.substring(0, line.length()-2);
}
clueNum = 0;
int i = 0;
while (line.charAt(i) != '.') {
if (clueNum != 0) {
clueNum *= 10;
}
clueNum += line.charAt(i) - '0';
i++;
}
String clue = line.substring(i+2).trim();
acrossNumToClueMap.put(clueNum, clue);
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Across clues.");
return false;
}
line = scanner.nextLine();
} while (!line.startsWith("{"));
int maxClueNum = clueNum;
SparseArray<String> downNumToClueMap = new SparseArray<String>();
line = line.substring(1);
boolean finished = false;
do {
if (line.endsWith(" |")) {
line = line.substring(0, line.length()-2);
} else {
finished = true;
}
clueNum = 0;
int i = 0;
while (line.charAt(i) != '.') {
if (clueNum != 0) {
clueNum *= 10;
}
clueNum += line.charAt(i) - '0';
i++;
}
String clue = line.substring(i+2).trim();
downNumToClueMap.put(clueNum, clue);
if(!finished) {
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Down clues.");
return false;
}
line = scanner.nextLine();
}
} while (!finished);
maxClueNum = clueNum > maxClueNum ? clueNum : maxClueNum;
// Convert clues into raw clues format.
int numberOfClues = acrossNumToClueMap.size() + downNumToClueMap.size();
puz.setNumberOfClues(numberOfClues);
String[] rawClues = new String[numberOfClues];
int i = 0;
for (clueNum = 1; clueNum <= maxClueNum; clueNum++) {
String clue = acrossNumToClueMap.get(clueNum);
if (clue != null) {
rawClues[i] = clue;
i++;
}
clue = downNumToClueMap.get(clueNum);
if (clue != null) {
rawClues[i] = clue;
i++;
}
}
puz.setRawClues(rawClues);
// Set puzzle information
puz.setTitle(title);
puz.setAuthor(author);
puz.setDate(date);
puz.setCopyright(copyright);
try {
IO.save(puz, os);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
| public static boolean convertKFPuzzle(InputStream is, OutputStream os,
String title, String author, String copyright, Calendar date) {
Puzzle puz = new Puzzle();
Scanner scanner = new Scanner(new InputStreamReader(is, new MacRoman()));
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: File empty.");
return false;
}
String line = scanner.nextLine();
if (!line.startsWith("{") || !scanner.hasNextLine()) {
LOG.warning("KFIO: First line format incorrect.");
return false;
}
// Skip over redundant grid information.
line = scanner.nextLine();
while (!line.startsWith("{")) {
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Grid information.");
return false;
}
line = scanner.nextLine();
}
// Process solution grid.
List<char[]> solGrid = new ArrayList<char[]>();
line = line.substring(1, line.length()-2);
String[] rowString = line.split(" ");
int width = rowString.length;
do {
if (line.endsWith(" |")) {
line = line.substring(0, line.length()-2);
}
rowString = line.split(" ");
if (rowString.length != width) {
LOG.warning("KFIO: Not a square grid.");
return false;
}
char[] row = new char[width];
for (int x = 0; x < width; x++) {
row[x] = rowString[x].charAt(0);
}
solGrid.add(row);
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Solution grid.");
return false;
}
line = scanner.nextLine();
} while (!line.startsWith("{"));
// Convert solution grid into Box grid.
int height = solGrid.size();
puz.setWidth(width);
puz.setHeight(height);
Box[][] boxes = new Box[height][width];
for (int r = 0; r < height; r++) {
char[] row = solGrid.get(r);
for (int c = 0; c < width; c++) {
if (row[c] != '#') {
boxes[r][c] = new Box();
boxes[r][c].setSolution(row[c]);
boxes[r][c].setResponse(' ');
}
}
}
puz.setBoxes(boxes);
// Process clues.
SparseArray<String> acrossNumToClueMap = new SparseArray<String>();
line = line.substring(1);
int clueNum;
do {
if (line.endsWith(" |")) {
line = line.substring(0, line.length()-2);
}
clueNum = 0;
int i = 0;
while (line.charAt(i) != '.') {
if (clueNum != 0) {
clueNum *= 10;
}
clueNum += line.charAt(i) - '0';
i++;
}
String clue = line.substring(i+2).trim();
acrossNumToClueMap.put(clueNum, clue);
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Across clues.");
return false;
}
line = scanner.nextLine();
} while (!line.startsWith("{"));
int maxClueNum = clueNum;
SparseArray<String> downNumToClueMap = new SparseArray<String>();
line = line.substring(1);
boolean finished = false;
do {
if (line.endsWith(" |")) {
line = line.substring(0, line.length()-2);
} else {
finished = true;
}
clueNum = 0;
int i = 0;
while (line.charAt(i) != '.') {
if (clueNum != 0) {
clueNum *= 10;
}
clueNum += line.charAt(i) - '0';
i++;
}
String clue = line.substring(i+2).trim();
downNumToClueMap.put(clueNum, clue);
if(!finished) {
if (!scanner.hasNextLine()) {
LOG.warning("KFIO: Unexpected EOF - Down clues.");
return false;
}
line = scanner.nextLine();
}
} while (!finished);
maxClueNum = clueNum > maxClueNum ? clueNum : maxClueNum;
// Convert clues into raw clues format.
int numberOfClues = acrossNumToClueMap.size() + downNumToClueMap.size();
puz.setNumberOfClues(numberOfClues);
String[] rawClues = new String[numberOfClues];
int i = 0;
for (clueNum = 1; clueNum <= maxClueNum; clueNum++) {
String clue = acrossNumToClueMap.get(clueNum);
if (clue != null) {
rawClues[i] = clue;
i++;
}
clue = downNumToClueMap.get(clueNum);
if (clue != null) {
rawClues[i] = clue;
i++;
}
}
puz.setRawClues(rawClues);
// Set puzzle information
puz.setTitle(title);
puz.setAuthor(author);
puz.setDate(date);
puz.setCopyright(copyright);
try {
IO.save(puz, os);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
|
diff --git a/src/main/java/org/scala_tools/maven/ScalaRunMojo.java b/src/main/java/org/scala_tools/maven/ScalaRunMojo.java
index 7538e6a..f9a3099 100644
--- a/src/main/java/org/scala_tools/maven/ScalaRunMojo.java
+++ b/src/main/java/org/scala_tools/maven/ScalaRunMojo.java
@@ -1,105 +1,105 @@
/*
* Copyright 2007 scala-tools.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
*/
package org.scala_tools.maven;
import org.codehaus.plexus.util.StringUtils;
/**
* Run a Scala class using the Scala runtime
*
* @goal run
* @requiresDependencyResolution test
* @execute phase="test-compile"
*/
public class ScalaRunMojo extends ScalaMojoSupport {
/**
* @parameter expression="${launcher}"
*/
protected String launcher;
/**
* Additional parameter to use to call the main class
* Using this parameter only from command line ("-DaddArgs=arg1|arg2|arg3|..."), not from pom.xml.
* @parameter expression="${addArgs}"
*/
protected String addArgs;
/**
* A list of launcher definition (to avoid rewriting long command line or share way to call an application)
* launchers could be define by :
* <pre>
* <launchers>
* <launcher>
* <id>myLauncher</id>
* <mainClass>my.project.Main</mainClass>
* <args>
* <arg>arg1</arg>
* </args>
* <jvmArgs>
* <jvmArg>-Xmx64m</jvmArg>
* </jvmArgs>
* </launcher>
* <launcher>
* <id>myLauncher2</id>
* ...
* <><>
* </launcher>
* </launchers>
* </pre>
* @parameter
*/
protected Launcher[] launchers;
/**
* Main class to call, the call use the jvmArgs and args define in the pom.xml, and the addArgs define in the command line if define.
*
* Higher priority to launcher parameter)
* Using this parameter only from command line (-DmainClass=...), not from pom.xml.
* @parameter expression="${mainClass}"
*/
protected String mainClass;
@Override
@SuppressWarnings("unchecked")
protected void doExecute() throws Exception {
JavaCommand jcmd = null;
if (StringUtils.isNotEmpty(mainClass)) {
jcmd = new JavaCommand(this, mainClass, JavaCommand.toMultiPath(project.getTestClasspathElements()), jvmArgs, args);
} else if ((launchers != null) && (launchers.length > 0)) {
if (StringUtils.isNotEmpty(launcher)) {
for(int i = 0; (i < launchers.length) && (jcmd == null); i++) {
if (launcher.equals(launchers[i].id)) {
getLog().info("launcher '"+ launchers[i].id + "' selected => "+ launchers[i].mainClass );
jcmd = new JavaCommand(this, launchers[i].mainClass, JavaCommand.toMultiPath(project.getTestClasspathElements()), launchers[i].jvmArgs, launchers[i].args);
}
}
} else {
getLog().info("launcher '"+ launchers[0].id + "' selected => "+ launchers[0].mainClass );
jcmd = new JavaCommand(this, launchers[0].mainClass, JavaCommand.toMultiPath(project.getTestClasspathElements()), launchers[0].jvmArgs, launchers[0].args);
}
}
if (jcmd != null) {
if (StringUtils.isNotEmpty(addArgs)) {
- jcmd.addArgs(addArgs.split("|"));
+ jcmd.addArgs(StringUtils.split(addArgs, "|"));
}
jcmd.run(displayCmd);
} else {
getLog().warn("Not mainClass or valid launcher found/define");
}
}
}
| true | true | protected void doExecute() throws Exception {
JavaCommand jcmd = null;
if (StringUtils.isNotEmpty(mainClass)) {
jcmd = new JavaCommand(this, mainClass, JavaCommand.toMultiPath(project.getTestClasspathElements()), jvmArgs, args);
} else if ((launchers != null) && (launchers.length > 0)) {
if (StringUtils.isNotEmpty(launcher)) {
for(int i = 0; (i < launchers.length) && (jcmd == null); i++) {
if (launcher.equals(launchers[i].id)) {
getLog().info("launcher '"+ launchers[i].id + "' selected => "+ launchers[i].mainClass );
jcmd = new JavaCommand(this, launchers[i].mainClass, JavaCommand.toMultiPath(project.getTestClasspathElements()), launchers[i].jvmArgs, launchers[i].args);
}
}
} else {
getLog().info("launcher '"+ launchers[0].id + "' selected => "+ launchers[0].mainClass );
jcmd = new JavaCommand(this, launchers[0].mainClass, JavaCommand.toMultiPath(project.getTestClasspathElements()), launchers[0].jvmArgs, launchers[0].args);
}
}
if (jcmd != null) {
if (StringUtils.isNotEmpty(addArgs)) {
jcmd.addArgs(addArgs.split("|"));
}
jcmd.run(displayCmd);
} else {
getLog().warn("Not mainClass or valid launcher found/define");
}
}
| protected void doExecute() throws Exception {
JavaCommand jcmd = null;
if (StringUtils.isNotEmpty(mainClass)) {
jcmd = new JavaCommand(this, mainClass, JavaCommand.toMultiPath(project.getTestClasspathElements()), jvmArgs, args);
} else if ((launchers != null) && (launchers.length > 0)) {
if (StringUtils.isNotEmpty(launcher)) {
for(int i = 0; (i < launchers.length) && (jcmd == null); i++) {
if (launcher.equals(launchers[i].id)) {
getLog().info("launcher '"+ launchers[i].id + "' selected => "+ launchers[i].mainClass );
jcmd = new JavaCommand(this, launchers[i].mainClass, JavaCommand.toMultiPath(project.getTestClasspathElements()), launchers[i].jvmArgs, launchers[i].args);
}
}
} else {
getLog().info("launcher '"+ launchers[0].id + "' selected => "+ launchers[0].mainClass );
jcmd = new JavaCommand(this, launchers[0].mainClass, JavaCommand.toMultiPath(project.getTestClasspathElements()), launchers[0].jvmArgs, launchers[0].args);
}
}
if (jcmd != null) {
if (StringUtils.isNotEmpty(addArgs)) {
jcmd.addArgs(StringUtils.split(addArgs, "|"));
}
jcmd.run(displayCmd);
} else {
getLog().warn("Not mainClass or valid launcher found/define");
}
}
|
diff --git a/src/com/papagiannis/tuberun/ClaimActivity.java b/src/com/papagiannis/tuberun/ClaimActivity.java
index b243575..4ddc194 100644
--- a/src/com/papagiannis/tuberun/ClaimActivity.java
+++ b/src/com/papagiannis/tuberun/ClaimActivity.java
@@ -1,456 +1,457 @@
package com.papagiannis.tuberun;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.papagiannis.tuberun.claims.Claim;
import com.papagiannis.tuberun.claims.ClaimStore;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.app.Dialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class ClaimActivity extends TabActivity {
private static final String LIST1_TAB_TAG = "Overview";
private static final String LIST2_TAB_TAG = "Journey";
private static final String LIST3_TAB_TAG = "Delay";
private static final String LIST4_TAB_TAG = "Personal";
private static final String LIST5_TAB_TAG = "Ticket";
private TabHost tabHost;
Claim claim;
ClaimStore store;
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, dd/MM/yyyy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat durationFormat = new SimpleDateFormat("mm");
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.claim);
tabHost = getTabHost();
// add views to tab host
tabHost.addTab(tabHost.newTabSpec(LIST1_TAB_TAG).setIndicator(LIST1_TAB_TAG)
.setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return (LinearLayout) findViewById(R.id.overview_tab);
}
}));
tabHost.addTab(tabHost.newTabSpec(LIST2_TAB_TAG).setIndicator(LIST2_TAB_TAG)
.setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return (LinearLayout) findViewById(R.id.journey_tab);
}
}));
tabHost.addTab(tabHost.newTabSpec(LIST3_TAB_TAG).setIndicator(LIST3_TAB_TAG)
.setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return (LinearLayout) findViewById(R.id.delay_tab);
}
}));
tabHost.addTab(tabHost.newTabSpec(LIST4_TAB_TAG).setIndicator(LIST4_TAB_TAG)
.setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return (LinearLayout) findViewById(R.id.personal_tab);
}
}));
tabHost.addTab(tabHost.newTabSpec(LIST5_TAB_TAG).setIndicator(LIST5_TAB_TAG)
.setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return (LinearLayout) findViewById(R.id.ticket_tab);
}
}));
store = ClaimStore.getInstance();
Bundle extras = getIntent().getExtras();
int index = Integer.parseInt(extras.getString("index"));
claim = store.getAll(this).get(index);
setupViewReferences();
setupViewHandlers();
}
@Override
protected void onPause() {
super.onPause();
store.storeToFile(this);
}
// Views
private Spinner ticketSpinner;
private View submitButton;
private View oysterLayout;
private View tflLayout;
private View railLayout;
private EditText infoEdit;
private TextView resultView;
private Button journeyStartDate;
private Spinner journeyStartStation;
private Spinner journeyLineUsed;
private Spinner journeyEndStation;
private Spinner delayAtStation;
private Spinner delayStation1;
private Spinner delayStation2;
private RadioButton delayAt;
private RadioButton delayBetween;
private Button delayWhen;
private Button delayDuration;
private Spinner personalTitle;
private EditText personalSurname;
private EditText personalName;
private EditText personalLine1;
private EditText personalLine2;
private EditText personalCity;
private EditText personalPostcode;
private EditText personalPhone;
private EditText personalEmail;
private EditText personalPhotocard;
private void setupViewReferences() {
oysterLayout = findViewById(R.id.oyster_layout);
tflLayout = findViewById(R.id.tfl_layout);
railLayout = findViewById(R.id.rail_layout);
submitButton = findViewById(R.id.submit_button);
ticketSpinner = (Spinner) findViewById(R.id.ticket_type_spinner);
infoEdit = (EditText) findViewById(R.id.claim_info);
resultView = (TextView) findViewById(R.id.claim_result);
journeyStartDate = (Button) findViewById(R.id.claim_journey_startdate);
journeyStartStation = (Spinner) findViewById(R.id.claim_journey_startstation);
journeyEndStation = (Spinner) findViewById(R.id.claim_journey_endstation);
journeyLineUsed = (Spinner) findViewById(R.id.claim_journey_lineused);
delayAtStation = (Spinner) findViewById(R.id.claim_delay_atstation);
delayStation1 = (Spinner) findViewById(R.id.claim_delay_station1);
delayStation2 = (Spinner) findViewById(R.id.claim_delay_station2);
delayAt = (RadioButton) findViewById(R.id.claim_delay_at);
delayBetween = (RadioButton) findViewById(R.id.claim_delay_between);
delayWhen = (Button) findViewById(R.id.claim_delay_when);
delayDuration = (Button) findViewById(R.id.claim_delay_duration);
personalTitle = (Spinner) findViewById(R.id.claim_personal_title);
personalSurname = (EditText) findViewById(R.id.claim_personal_surname);
personalName = (EditText) findViewById(R.id.claim_personal_name);
personalLine1 = (EditText) findViewById(R.id.claim_personal_line1);
personalLine2 = (EditText) findViewById(R.id.claim_personal_line2);
personalCity = (EditText) findViewById(R.id.claim_personal_city);
personalPostcode = (EditText) findViewById(R.id.claim_personal_postcode);
personalPhone = (EditText) findViewById(R.id.claim_personal_phone);
personalEmail = (EditText) findViewById(R.id.claim_personal_email);
personalPhotocard = (EditText) findViewById(R.id.claim_personal_photocard);
}
private void setupViewHandlers() {
int i = 0;
for (i = 0; i < ticketSpinner.getAdapter().getCount(); i++) {
if (ticketSpinner.getAdapter().getItem(i).equals(claim.ticket_type))
break;
}
+ if (i == ticketSpinner.getAdapter().getCount()) i=0; //the default if the claim is new
ticketSpinner.setSelection(i);
ticketSpinner.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.ticket_type = (String) ticketSpinner.getItemAtPosition(position);
oysterLayout.setVisibility(claim.getTicketOysterVisibility());
tflLayout.setVisibility(claim.getTicketTflVisibility());
railLayout.setVisibility(claim.getTicketRailVisibility());
}
});
infoEdit.setText(claim.user_notes);
infoEdit.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.user_notes = e.toString();
}
});
resultView.setText(claim.getResult());
journeyStartDate.setText(dateFormat.format(claim.journey_started));
journeyStartDate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(v.getId());
}
});
final List<String> stations = StationDetails.FetchTubeStationsClaims();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stations);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
journeyStartStation.setAdapter(adapter);
journeyStartStation.setSelection(stations.indexOf(claim.journey_startstation));
journeyStartStation.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.journey_startstation = stations.get(position);
}
});
journeyEndStation.setAdapter(adapter);
journeyEndStation.setSelection(stations.indexOf(claim.journey_endstation));
journeyEndStation.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.journey_endstation = stations.get(position);
}
});
final List<String> lines = LinePresentation.getLinesStringListClaims();
ArrayAdapter<String> lines_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lines);
lines_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
journeyLineUsed.setAdapter(lines_adapter);
journeyLineUsed.setSelection(stations.indexOf(claim.journey_lineused));
journeyLineUsed.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.journey_lineused = stations.get(position);
}
});
//////////// delay tab /////////////////////
delayWhen.setText(timeFormat.format(claim.delay_when));
delayWhen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(v.getId());
}
});
delayDuration.setText(durationFormat.format(claim.delay_duration)+" minutes");
delayDuration.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(v.getId());
}
});
updateJourneySpinners();
//I don't use a buttongroup, instead I crate and manage the group manually
final List<RadioButton> radioButtons = new ArrayList<RadioButton>();
radioButtons.add(delayAt);
radioButtons.add(delayBetween);
for (RadioButton button : radioButtons) {
button.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) claim.setDelayAt( buttonView.getId()==delayAt.getId() && isChecked );
updateJourneySpinners();
}
});
}
delayAtStation.setAdapter(adapter);
delayAtStation.setSelection(stations.indexOf(claim.getDelayAtStation()));
delayAtStation.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.setDelayAtstation(stations.get(position));
delayStation1.setSelection(0);
delayStation2.setSelection(0);
}
});
delayStation1.setAdapter(adapter);
delayStation1.setSelection(stations.indexOf(claim.getDelayStation1()));
delayStation1.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.setDelayStation1(stations.get(position));
delayAtStation.setSelection(0);
delayStation2.setSelection(0);
}
});
delayStation2.setAdapter(adapter);
delayStation2.setSelection(stations.indexOf(claim.getDelayStation2()));
delayStation2.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.setDelayStation2(stations.get(position));
delayAtStation.setSelection(0);
delayStation1.setSelection(0);
}
});
////////////personal tab /////////////////////
final String[] titles = getResources().getStringArray(R.array.claim_title_spinner);
int j=0;
- for (i=0;i<titles.length;i++) {
- if (titles[i].equals(claim.personal_title)) { j=i; break; }
+ for (int ii=0;ii<titles.length;ii++) {
+ if (titles[ii].equals(claim.personal_title)) { j=ii; break; }
}
personalTitle.setSelection(j);
personalTitle.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.personal_title=titles[position];
}
});
personalSurname.setText(claim.personal_surname);
personalSurname.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_surname = e.toString();
}
});
personalName.setText(claim.personal_name);
personalName.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_name = e.toString();
}
});
personalLine1.setText(claim.personal_address1);
personalLine1.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_address1 = e.toString();
}
});
personalLine2.setText(claim.personal_address2);
personalLine2.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_address2 = e.toString();
}
});
personalCity.setText(claim.personal_city);
personalCity.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_city = e.toString();
}
});
personalPostcode.setText(claim.personal_postcode);
personalPostcode.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_postcode = e.toString();
}
});
personalPhone.setText(claim.personal_phone);
personalPhone.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_phone = e.toString();
}
});
personalEmail.setText(claim.personal_email);
personalEmail.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_email = e.toString();
}
});
personalPhotocard.setText(claim.personal_photocard);
personalPhotocard.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_photocard = e.toString();
}
});
}
private void updateJourneySpinners() {
if (claim.isDelayAtStation()) {
delayAtStation.setEnabled(true);
delayStation1.setEnabled(false);
delayStation2.setEnabled(false);
delayAt.setChecked(true);
delayBetween.setChecked(false);
} else {
delayStation1.setEnabled(true);
delayStation2.setEnabled(true);
delayAtStation.setEnabled(false);
delayAt.setChecked(false);
delayBetween.setChecked(true);
}
}
@Override
protected Dialog onCreateDialog(int id) {
if (journeyStartDate.getId() == id) {
Date d = claim.journey_started;
return new DatePickerDialog(this, new OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
claim.journey_started = new Date(year - 1900, monthOfYear, dayOfMonth);
journeyStartDate.setText(dateFormat.format(claim.journey_started));
}
}, d.getYear() + 1900, d.getMonth(), d.getDate());
}
else if (delayWhen.getId() == id) {
Date d = claim.delay_when;
return new TimePickerDialog(this, new OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int h, int m) {
claim.delay_when=new Date();
claim.delay_when.setHours(h);
claim.delay_when.setMinutes(m);
delayWhen.setText(timeFormat.format(claim.delay_when));
}
},d.getHours(),d.getMinutes(),true);
}
else if (delayDuration.getId() == id) {
final CharSequence[] items = {"15", "20", "25", "30", "40", "50", "59+"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delay duration (minutes)");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
claim.delay_duration=new Date();
claim.delay_duration.setHours(0);
claim.delay_duration.setMinutes(Integer.parseInt(items[item].subSequence(0, 2).toString()));
delayDuration.setText(durationFormat.format(claim.delay_duration) + " minutes");
}
});
return builder.create();
}
return null;
}
}
| false | true | private void setupViewHandlers() {
int i = 0;
for (i = 0; i < ticketSpinner.getAdapter().getCount(); i++) {
if (ticketSpinner.getAdapter().getItem(i).equals(claim.ticket_type))
break;
}
ticketSpinner.setSelection(i);
ticketSpinner.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.ticket_type = (String) ticketSpinner.getItemAtPosition(position);
oysterLayout.setVisibility(claim.getTicketOysterVisibility());
tflLayout.setVisibility(claim.getTicketTflVisibility());
railLayout.setVisibility(claim.getTicketRailVisibility());
}
});
infoEdit.setText(claim.user_notes);
infoEdit.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.user_notes = e.toString();
}
});
resultView.setText(claim.getResult());
journeyStartDate.setText(dateFormat.format(claim.journey_started));
journeyStartDate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(v.getId());
}
});
final List<String> stations = StationDetails.FetchTubeStationsClaims();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stations);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
journeyStartStation.setAdapter(adapter);
journeyStartStation.setSelection(stations.indexOf(claim.journey_startstation));
journeyStartStation.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.journey_startstation = stations.get(position);
}
});
journeyEndStation.setAdapter(adapter);
journeyEndStation.setSelection(stations.indexOf(claim.journey_endstation));
journeyEndStation.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.journey_endstation = stations.get(position);
}
});
final List<String> lines = LinePresentation.getLinesStringListClaims();
ArrayAdapter<String> lines_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lines);
lines_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
journeyLineUsed.setAdapter(lines_adapter);
journeyLineUsed.setSelection(stations.indexOf(claim.journey_lineused));
journeyLineUsed.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.journey_lineused = stations.get(position);
}
});
//////////// delay tab /////////////////////
delayWhen.setText(timeFormat.format(claim.delay_when));
delayWhen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(v.getId());
}
});
delayDuration.setText(durationFormat.format(claim.delay_duration)+" minutes");
delayDuration.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(v.getId());
}
});
updateJourneySpinners();
//I don't use a buttongroup, instead I crate and manage the group manually
final List<RadioButton> radioButtons = new ArrayList<RadioButton>();
radioButtons.add(delayAt);
radioButtons.add(delayBetween);
for (RadioButton button : radioButtons) {
button.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) claim.setDelayAt( buttonView.getId()==delayAt.getId() && isChecked );
updateJourneySpinners();
}
});
}
delayAtStation.setAdapter(adapter);
delayAtStation.setSelection(stations.indexOf(claim.getDelayAtStation()));
delayAtStation.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.setDelayAtstation(stations.get(position));
delayStation1.setSelection(0);
delayStation2.setSelection(0);
}
});
delayStation1.setAdapter(adapter);
delayStation1.setSelection(stations.indexOf(claim.getDelayStation1()));
delayStation1.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.setDelayStation1(stations.get(position));
delayAtStation.setSelection(0);
delayStation2.setSelection(0);
}
});
delayStation2.setAdapter(adapter);
delayStation2.setSelection(stations.indexOf(claim.getDelayStation2()));
delayStation2.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.setDelayStation2(stations.get(position));
delayAtStation.setSelection(0);
delayStation1.setSelection(0);
}
});
////////////personal tab /////////////////////
final String[] titles = getResources().getStringArray(R.array.claim_title_spinner);
int j=0;
for (i=0;i<titles.length;i++) {
if (titles[i].equals(claim.personal_title)) { j=i; break; }
}
personalTitle.setSelection(j);
personalTitle.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.personal_title=titles[position];
}
});
personalSurname.setText(claim.personal_surname);
personalSurname.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_surname = e.toString();
}
});
personalName.setText(claim.personal_name);
personalName.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_name = e.toString();
}
});
personalLine1.setText(claim.personal_address1);
personalLine1.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_address1 = e.toString();
}
});
personalLine2.setText(claim.personal_address2);
personalLine2.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_address2 = e.toString();
}
});
personalCity.setText(claim.personal_city);
personalCity.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_city = e.toString();
}
});
personalPostcode.setText(claim.personal_postcode);
personalPostcode.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_postcode = e.toString();
}
});
personalPhone.setText(claim.personal_phone);
personalPhone.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_phone = e.toString();
}
});
personalEmail.setText(claim.personal_email);
personalEmail.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_email = e.toString();
}
});
personalPhotocard.setText(claim.personal_photocard);
personalPhotocard.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_photocard = e.toString();
}
});
}
| private void setupViewHandlers() {
int i = 0;
for (i = 0; i < ticketSpinner.getAdapter().getCount(); i++) {
if (ticketSpinner.getAdapter().getItem(i).equals(claim.ticket_type))
break;
}
if (i == ticketSpinner.getAdapter().getCount()) i=0; //the default if the claim is new
ticketSpinner.setSelection(i);
ticketSpinner.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.ticket_type = (String) ticketSpinner.getItemAtPosition(position);
oysterLayout.setVisibility(claim.getTicketOysterVisibility());
tflLayout.setVisibility(claim.getTicketTflVisibility());
railLayout.setVisibility(claim.getTicketRailVisibility());
}
});
infoEdit.setText(claim.user_notes);
infoEdit.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.user_notes = e.toString();
}
});
resultView.setText(claim.getResult());
journeyStartDate.setText(dateFormat.format(claim.journey_started));
journeyStartDate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(v.getId());
}
});
final List<String> stations = StationDetails.FetchTubeStationsClaims();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, stations);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
journeyStartStation.setAdapter(adapter);
journeyStartStation.setSelection(stations.indexOf(claim.journey_startstation));
journeyStartStation.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.journey_startstation = stations.get(position);
}
});
journeyEndStation.setAdapter(adapter);
journeyEndStation.setSelection(stations.indexOf(claim.journey_endstation));
journeyEndStation.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.journey_endstation = stations.get(position);
}
});
final List<String> lines = LinePresentation.getLinesStringListClaims();
ArrayAdapter<String> lines_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lines);
lines_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
journeyLineUsed.setAdapter(lines_adapter);
journeyLineUsed.setSelection(stations.indexOf(claim.journey_lineused));
journeyLineUsed.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.journey_lineused = stations.get(position);
}
});
//////////// delay tab /////////////////////
delayWhen.setText(timeFormat.format(claim.delay_when));
delayWhen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(v.getId());
}
});
delayDuration.setText(durationFormat.format(claim.delay_duration)+" minutes");
delayDuration.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(v.getId());
}
});
updateJourneySpinners();
//I don't use a buttongroup, instead I crate and manage the group manually
final List<RadioButton> radioButtons = new ArrayList<RadioButton>();
radioButtons.add(delayAt);
radioButtons.add(delayBetween);
for (RadioButton button : radioButtons) {
button.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) claim.setDelayAt( buttonView.getId()==delayAt.getId() && isChecked );
updateJourneySpinners();
}
});
}
delayAtStation.setAdapter(adapter);
delayAtStation.setSelection(stations.indexOf(claim.getDelayAtStation()));
delayAtStation.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.setDelayAtstation(stations.get(position));
delayStation1.setSelection(0);
delayStation2.setSelection(0);
}
});
delayStation1.setAdapter(adapter);
delayStation1.setSelection(stations.indexOf(claim.getDelayStation1()));
delayStation1.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.setDelayStation1(stations.get(position));
delayAtStation.setSelection(0);
delayStation2.setSelection(0);
}
});
delayStation2.setAdapter(adapter);
delayStation2.setSelection(stations.indexOf(claim.getDelayStation2()));
delayStation2.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.setDelayStation2(stations.get(position));
delayAtStation.setSelection(0);
delayStation1.setSelection(0);
}
});
////////////personal tab /////////////////////
final String[] titles = getResources().getStringArray(R.array.claim_title_spinner);
int j=0;
for (int ii=0;ii<titles.length;ii++) {
if (titles[ii].equals(claim.personal_title)) { j=ii; break; }
}
personalTitle.setSelection(j);
personalTitle.setOnItemSelectedListener(new SimpleOnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
claim.personal_title=titles[position];
}
});
personalSurname.setText(claim.personal_surname);
personalSurname.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_surname = e.toString();
}
});
personalName.setText(claim.personal_name);
personalName.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_name = e.toString();
}
});
personalLine1.setText(claim.personal_address1);
personalLine1.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_address1 = e.toString();
}
});
personalLine2.setText(claim.personal_address2);
personalLine2.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_address2 = e.toString();
}
});
personalCity.setText(claim.personal_city);
personalCity.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_city = e.toString();
}
});
personalPostcode.setText(claim.personal_postcode);
personalPostcode.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_postcode = e.toString();
}
});
personalPhone.setText(claim.personal_phone);
personalPhone.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_phone = e.toString();
}
});
personalEmail.setText(claim.personal_email);
personalEmail.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_email = e.toString();
}
});
personalPhotocard.setText(claim.personal_photocard);
personalPhotocard.addTextChangedListener(new SimpleTextWatcher() {
@Override
public void afterTextChanged(Editable e) {
claim.personal_photocard = e.toString();
}
});
}
|
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 dc91d5ed..63376fe8 100644
--- a/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java
+++ b/E-Adventure/src/es/eucm/eadventure/editor/control/Controller.java
@@ -1,3698 +1,3698 @@
/*******************************************************************************
* <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.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( " " ) ) {
+ 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);
}
}
| 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( " " ) ) {
// 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 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);
}
}
|
diff --git a/web/src/main/java/org/eurekastreams/web/client/ui/pages/widget/ShareActivityWidget.java b/web/src/main/java/org/eurekastreams/web/client/ui/pages/widget/ShareActivityWidget.java
index 32598581b..d6f97afa0 100644
--- a/web/src/main/java/org/eurekastreams/web/client/ui/pages/widget/ShareActivityWidget.java
+++ b/web/src/main/java/org/eurekastreams/web/client/ui/pages/widget/ShareActivityWidget.java
@@ -1,72 +1,73 @@
/*
* Copyright (c) 2011 Lockheed Martin Corporation
*
* 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.eurekastreams.web.client.ui.pages.widget;
import org.eurekastreams.web.client.events.EventBus;
import org.eurekastreams.web.client.events.Observer;
import org.eurekastreams.web.client.events.data.GotActivityResponseEvent;
import org.eurekastreams.web.client.jsni.WidgetJSNIFacadeImpl;
import org.eurekastreams.web.client.model.ActivityModel;
import org.eurekastreams.web.client.ui.common.dialog.DialogContentHost;
import org.eurekastreams.web.client.ui.common.stream.share.ShareMessageDialogContent;
import org.eurekastreams.web.client.ui.pages.master.StaticResourceBundle;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
/**
* Secondary widget used by the other widgets to share an activity.
*/
public class ShareActivityWidget extends Composite
{
/**
* Constructor.
*
* @param activityId
* ID of activity to share.
*/
public ShareActivityWidget(final Long activityId)
{
final SimplePanel main = new SimplePanel();
+ main.addStyleName(StaticResourceBundle.INSTANCE.coreCss().shareMessageDialog());
initWidget(main);
EventBus.getInstance().addObserver(GotActivityResponseEvent.class, new Observer<GotActivityResponseEvent>()
{
public void update(final GotActivityResponseEvent ev)
{
ShareMessageDialogContent dialogContent = new ShareMessageDialogContent(ev.getResponse());
dialogContent.setHost(new DialogContentHost()
{
public void center()
{
}
public void hide()
{
WidgetJSNIFacadeImpl.nativeClose();
}
});
Widget dialogWidget = dialogContent.getBody();
dialogWidget.addStyleName(StaticResourceBundle.INSTANCE.coreCss().embeddedWidget());
dialogWidget.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectCommentWidget());
main.add(dialogWidget);
}
});
ActivityModel.getInstance().fetch(activityId, true);
}
}
| true | true | public ShareActivityWidget(final Long activityId)
{
final SimplePanel main = new SimplePanel();
initWidget(main);
EventBus.getInstance().addObserver(GotActivityResponseEvent.class, new Observer<GotActivityResponseEvent>()
{
public void update(final GotActivityResponseEvent ev)
{
ShareMessageDialogContent dialogContent = new ShareMessageDialogContent(ev.getResponse());
dialogContent.setHost(new DialogContentHost()
{
public void center()
{
}
public void hide()
{
WidgetJSNIFacadeImpl.nativeClose();
}
});
Widget dialogWidget = dialogContent.getBody();
dialogWidget.addStyleName(StaticResourceBundle.INSTANCE.coreCss().embeddedWidget());
dialogWidget.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectCommentWidget());
main.add(dialogWidget);
}
});
ActivityModel.getInstance().fetch(activityId, true);
}
| public ShareActivityWidget(final Long activityId)
{
final SimplePanel main = new SimplePanel();
main.addStyleName(StaticResourceBundle.INSTANCE.coreCss().shareMessageDialog());
initWidget(main);
EventBus.getInstance().addObserver(GotActivityResponseEvent.class, new Observer<GotActivityResponseEvent>()
{
public void update(final GotActivityResponseEvent ev)
{
ShareMessageDialogContent dialogContent = new ShareMessageDialogContent(ev.getResponse());
dialogContent.setHost(new DialogContentHost()
{
public void center()
{
}
public void hide()
{
WidgetJSNIFacadeImpl.nativeClose();
}
});
Widget dialogWidget = dialogContent.getBody();
dialogWidget.addStyleName(StaticResourceBundle.INSTANCE.coreCss().embeddedWidget());
dialogWidget.addStyleName(StaticResourceBundle.INSTANCE.coreCss().connectCommentWidget());
main.add(dialogWidget);
}
});
ActivityModel.getInstance().fetch(activityId, true);
}
|
diff --git a/src/net/sf/freecol/server/generator/SimpleMapGenerator.java b/src/net/sf/freecol/server/generator/SimpleMapGenerator.java
index 0a9d7dd26..2a7567bfd 100644
--- a/src/net/sf/freecol/server/generator/SimpleMapGenerator.java
+++ b/src/net/sf/freecol/server/generator/SimpleMapGenerator.java
@@ -1,1086 +1,1090 @@
/**
* 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.generator;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.FreeColException;
import net.sf.freecol.common.debug.FreeColDebugger;
import net.sf.freecol.common.io.FreeColSavegameFile;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.AbstractUnit;
import net.sf.freecol.common.model.Building;
import net.sf.freecol.common.model.BuildingType;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.ColonyTile;
import net.sf.freecol.common.model.EuropeanNationType;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.IndianNationType;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.LostCityRumour;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Map.Direction;
import net.sf.freecol.common.model.Map.Position;
import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.NationType;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileImprovement;
import net.sf.freecol.common.model.TileImprovementType;
import net.sf.freecol.common.model.TileItemContainer;
import net.sf.freecol.common.model.TileType;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.option.FileOption;
import net.sf.freecol.common.option.IntegerOption;
import net.sf.freecol.common.option.MapGeneratorOptions;
import net.sf.freecol.common.option.OptionGroup;
import net.sf.freecol.common.util.RandomChoice;
import net.sf.freecol.server.FreeColServer;
import net.sf.freecol.server.model.ServerBuilding;
import net.sf.freecol.server.model.ServerColony;
import net.sf.freecol.server.model.ServerIndianSettlement;
import net.sf.freecol.server.model.ServerRegion;
import net.sf.freecol.server.model.ServerUnit;
/**
* Creates random maps and sets the starting locations for the players.
*/
public class SimpleMapGenerator implements MapGenerator {
private static final Logger logger = Logger.getLogger(SimpleMapGenerator.class.getName());
private final Random random;
private final OptionGroup mapGeneratorOptions;
private final LandGenerator landGenerator;
private final TerrainGenerator terrainGenerator;
// To avoid starting positions to be too close to the poles
// percentage indicating how much of the half map close to the pole cannot be spawned on
private static final float MIN_DISTANCE_FROM_POLE = 0.30f;
/**
* Creates a <code>MapGenerator</code>
*
* @param random The <code>Random</code> number source to use.
* @param specification a <code>Specification</code> value
* @see #createMap
*/
public SimpleMapGenerator(Random random, Specification specification) {
this.random = random;
this.mapGeneratorOptions = specification.getOptionGroup("mapGeneratorOptions");
landGenerator = new LandGenerator(mapGeneratorOptions, random);
terrainGenerator = new TerrainGenerator(mapGeneratorOptions, random);
}
/**
* Gets the approximate number of land tiles.
*
* @return The approximate number of land tiles
*/
private int getApproximateLandCount() {
return mapGeneratorOptions.getInteger("model.option.mapWidth")
* mapGeneratorOptions.getInteger("model.option.mapHeight")
* mapGeneratorOptions.getInteger("model.option.landMass")
/ 100;
}
/**
* Creates a map given for a game.
*
* @param game The <code>Game</code> to use.
* @see net.sf.freecol.server.generator.MapGenerator#createMap(net.sf.freecol.common.model.Game)
*/
public void createMap(Game game) throws FreeColException {
// Prepare imports:
final File importFile = ((FileOption) getMapGeneratorOptions()
.getOption(MapGeneratorOptions.IMPORT_FILE)).getValue();
final Game importGame;
if (importFile != null) {
Game g = null;
try {
logger.info("Importing file " + importFile.getPath());
g = FreeColServer.readGame(new FreeColSavegameFile(importFile),
game.getSpecification(), null);
} catch (IOException ioe) {
g = null;
}
importGame = g;
} else {
importGame = null;
}
// Create land map.
boolean[][] landMap;
if (importGame != null) {
landMap = LandGenerator.importLandMap(importGame);
} else {
landMap = landGenerator.createLandMap();
}
// Create terrain:
terrainGenerator.createMap(game, importGame, landMap);
Map map = game.getMap();
createIndianSettlements(map, game.getPlayers());
createEuropeanUnits(map, game.getPlayers());
createLostCityRumours(map, importGame);
}
/**
* Creates a <code>Map</code> for the given <code>Game</code>.
*
* The <code>Map</code> is added to the <code>Game</code> after
* it is created.
*
* @param game The game.
* @param landMap Determines whether there should be land
* or ocean on a given tile. This array also
* specifies the size of the map that is going
* to be created.
* @see Map
* @see TerrainGenerator#createMap
*/
public void createEmptyMap(Game game, boolean[][] landMap) {
terrainGenerator.createMap(game, null, landMap);
}
public LandGenerator getLandGenerator() {
return landGenerator;
}
public TerrainGenerator getTerrainGenerator() {
return terrainGenerator;
}
/* (non-Javadoc)
* @see net.sf.freecol.server.generator.IMapGenerator#getMapGeneratorOptions()
*/
public OptionGroup getMapGeneratorOptions() {
return mapGeneratorOptions;
}
/**
* Creates lost city rumours on the given map.
* The number of rumours depends on the map size.
*
* @param map The map to use.
* @param importGame The game to lost city rumours from.
*/
private void createLostCityRumours(Map map, Game importGame) {
final boolean importRumours = getMapGeneratorOptions().getBoolean(MapGeneratorOptions.IMPORT_RUMOURS);
if (importGame != null && importRumours) {
for (Tile importTile : importGame.getMap().getAllTiles()) {
LostCityRumour rumor = importTile.getLostCityRumour();
// no rumor
if(rumor == null){
continue;
}
final Position p = importTile.getPosition();
if (map.isValid(p)) {
final Tile t = map.getTile(p);
t.add(rumor);
}
}
} else {
int number = getApproximateLandCount() / getMapGeneratorOptions().getInteger("model.option.rumourNumber");
int counter = 0;
// TODO: Remove temporary fix:
if (importGame != null) {
number = map.getWidth() * map.getHeight() * 25 / (100 * 35);
}
// END TODO
int difficulty = map.getGame().getSpecification()
.getInteger("model.option.rumourDifficulty");
for (int i = 0; i < number; i++) {
for (int tries=0; tries<100; tries++) {
Position p = terrainGenerator.getRandomLandPosition(map, random);
Tile t = map.getTile(p);
if (t.isPolar()) continue; // No polar lost cities
if (t.isLand() && !t.hasLostCityRumour()
&& t.getSettlement() == null && t.getUnitCount() == 0) {
LostCityRumour r = new LostCityRumour(t.getGame(), t);
if (r.chooseType(null, difficulty, random)
== LostCityRumour.RumourType.MOUNDS
&& t.getOwningSettlement() != null) {
r.setType(LostCityRumour.RumourType.MOUNDS);
}
t.addLostCityRumour(r);
counter++;
break;
}
}
}
logger.info("Created " + counter
+ " lost city rumours of maximum " + number + ".");
}
}
/**
* Create the Indian settlements, at least a capital for every nation and
* random numbers of other settlements.
*
* @param map The <code>Map</code> to place the indian settlements on.
* @param players The players to create <code>Settlement</code>s
* and starting locations for. That is; both indian and
* european players. If players does not contain any indian players,
* no settlements are added.
*/
private void createIndianSettlements(final Map map, List<Player> players) {
Specification spec = map.getGame().getSpecification();
float shares = 0f;
List<IndianSettlement> settlements = new ArrayList<IndianSettlement>();
List<Player> indians = new ArrayList<Player>();
HashMap<String, Territory> territoryMap
= new HashMap<String, Territory>();
for (Player player : players) {
if (!player.isIndian()) continue;
switch (((IndianNationType) player.getNationType())
.getNumberOfSettlements()) {
case HIGH:
shares += 4;
break;
case AVERAGE:
shares += 3;
break;
case LOW:
shares += 2;
break;
}
indians.add(player);
List<String> regionNames
= ((IndianNationType) player.getNationType()).getRegionNames();
Territory territory = null;
if (regionNames == null || regionNames.isEmpty()) {
territory = new Territory(player, terrainGenerator.getRandomLandPosition(map, random));
territoryMap.put(player.getId(), territory);
} else {
for (String name : regionNames) {
if (territoryMap.get(name) == null) {
ServerRegion region = (ServerRegion) map.getRegion(name);
if (region == null) {
territory = new Territory(player, terrainGenerator.getRandomLandPosition(map, random));
} else {
territory = new Territory(player, region);
}
territoryMap.put(name, territory);
logger.fine("Allocated region " + name
+ " for " + player
+ ". Center is " + territory.getCenter()
+ ".");
break;
}
}
if (territory == null) {
logger.warning("Failed to allocate preferred region " + regionNames.get(0)
+ " for " + player.getNation());
outer: for (String name : regionNames) {
Territory otherTerritory = territoryMap.get(name);
for (String otherName : ((IndianNationType) otherTerritory.player.getNationType())
.getRegionNames()) {
if (territoryMap.get(otherName) == null) {
ServerRegion foundRegion = otherTerritory.region;
otherTerritory.region = (ServerRegion) map.getRegion(otherName);
territoryMap.put(otherName, otherTerritory);
territory = new Territory(player, foundRegion);
territoryMap.put(name, territory);
break outer;
}
}
}
if (territory == null) {
logger.warning("Unable to find free region for "
+ player.getName());
territory = new Territory(player, terrainGenerator.getRandomLandPosition(map, random));
territoryMap.put(player.getId(), territory);
}
}
}
}
if (indians.isEmpty()) return;
// Examine all the non-polar settleable tiles in a random
// order picking out as many as possible suitable tiles for
// native settlements such that can be guaranteed at least one
// layer of surrounding tiles to own.
int minSettlementDistance
= spec.getRangeOption("model.option.settlementNumber").getValue();
List<Tile> settlementTiles = new ArrayList<Tile>();
tiles: for (Tile tile : map.getAllTiles()) {
if (!tile.isPolar() && suitableForNativeSettlement(tile)) {
for (Tile t : settlementTiles) {
if (tile.getDistanceTo(t) < minSettlementDistance) {
continue tiles;
}
}
settlementTiles.add(tile);
}
}
Collections.shuffle(settlementTiles, random);
// Check number of settlements.
int settlementsToPlace = settlementTiles.size();
float share = settlementsToPlace / shares;
if (settlementTiles.size() < indians.size()) {
// TODO: something drastic to boost the settlement number
logger.warning("There are only " + settlementTiles.size()
+ " settlement sites."
+ " This is smaller than " + indians.size()
+ " the number of tribes.");
}
// Find the capitals
List<Territory> territories
= new ArrayList<Territory>(territoryMap.values());
int settlementsPlaced = 0;
for (Territory territory : territories) {
switch (((IndianNationType) territory.player.getNationType())
.getNumberOfSettlements()) {
case HIGH:
territory.numberOfSettlements = Math.round(4 * share);
break;
case AVERAGE:
territory.numberOfSettlements = Math.round(3 * share);
break;
case LOW:
territory.numberOfSettlements = Math.round(2 * share);
break;
}
int radius = territory.player.getNationType().getCapitalType().getClaimableRadius();
ArrayList<Tile> capitalTiles = new ArrayList<Tile>(settlementTiles);
while (!capitalTiles.isEmpty()) {
Tile tile = getClosestTile(territory.getCenter(),
capitalTiles);
capitalTiles.remove(tile);
// Choose this tile if it is free and half the expected tile
// claim can succeed (preventing capitals on small islands).
if (map.getClaimableTiles(territory.player, tile, radius).size()
>= (2 * radius + 1) * (2 * radius + 1) / 2) {
String name = (territory.region == null) ? "default region"
: territory.region.getNameKey();
logger.fine("Placing the " + territory.player
+ " capital in region: " + name
+ " at Tile: "+ tile.getPosition());
settlements.add(placeIndianSettlement(territory.player,
true, tile.getPosition(), map));
territory.numberOfSettlements--;
territory.position = tile.getPosition();
settlementTiles.remove(tile);
settlementsPlaced++;
break;
}
}
}
// Sort tiles from the edges of the map inward
Collections.sort(settlementTiles, new Comparator<Tile>() {
public int compare(Tile tile1, Tile tile2) {
int distance1 = Math.min(Math.min(tile1.getX(), map.getWidth() - tile1.getX()),
Math.min(tile1.getY(), map.getHeight() - tile1.getY()));
int distance2 = Math.min(Math.min(tile2.getX(), map.getWidth() - tile2.getX()),
Math.min(tile2.getY(), map.getHeight() - tile2.getY()));
return (distance1 - distance2);
}
});
// Now place other settlements
while (!settlementTiles.isEmpty() && !territories.isEmpty()) {
Tile tile = settlementTiles.remove(0);
if (tile.getOwner() != null) continue; // No close overlap
Territory territory = getClosestTerritory(tile, territories);
int radius = territory.player.getNationType().getSettlementType(false)
.getClaimableRadius();
// Insist that the settlement can not be linear
if (map.getClaimableTiles(territory.player, tile, radius).size()
> 2 * radius + 1) {
String name = (territory.region == null) ? "default region"
: territory.region.getNameKey();
logger.fine("Placing a " + territory.player
+ " camp in region: " + name
+ " at Tile: " + tile.getPosition());
settlements.add(placeIndianSettlement(territory.player,
false, tile.getPosition(), map));
settlementsPlaced++;
territory.numberOfSettlements--;
if (territory.numberOfSettlements <= 0) {
territories.remove(territory);
}
}
}
// Grow some more tiles.
// TODO: move the magic numbers below to the spec RSN
// Also collect the skills provided
HashMap<UnitType, List<IndianSettlement>> skills
= new HashMap<UnitType, List<IndianSettlement>>();
Collections.shuffle(settlements, random);
for (IndianSettlement is : settlements) {
List<Tile> tiles = new ArrayList<Tile>();
for (Tile tile : is.getOwnedTiles()) {
for (Tile t : tile.getSurroundingTiles(1)) {
if (t.getOwningSettlement() == null) {
tiles.add(tile);
break;
}
}
}
Collections.shuffle(tiles, random);
int minGrow = is.getType().getMinimumGrowth();
int maxGrow = is.getType().getMaximumGrowth();
if (maxGrow > minGrow) {
for (int i = random.nextInt(maxGrow - minGrow) + minGrow;
i > 0; i--) {
Tile tile = findFreeNeighbouringTile(is, tiles, random);
if (tile == null) break;
tile.changeOwnership(is.getOwner(), is);
tiles.add(tile);
}
}
// Collect settlements by skill
UnitType skill = is.getLearnableSkill();
List<IndianSettlement> isList = skills.get(skill);
if (isList == null) {
isList = new ArrayList<IndianSettlement>();
isList.add(is);
skills.put(skill, isList);
} else {
isList.add(is);
}
}
// Require that there be experts for all the new world goods types.
// Collect the list of needed experts
List<UnitType> expertsNeeded = new ArrayList<UnitType>();
for (GoodsType goodsType : spec.getNewWorldGoodsTypeList()) {
UnitType expert = spec.getExpertForProducing(goodsType);
if (!skills.containsKey(expert)) expertsNeeded.add(expert);
}
// Extract just the settlement lists.
List<List<IndianSettlement>> isList
= new ArrayList<List<IndianSettlement>>(skills.values());
Comparator<List<IndianSettlement>> listComparator
= new Comparator<List<IndianSettlement>>() {
public int compare(List<IndianSettlement> l1,
List<IndianSettlement> l2) {
return l2.size() - l1.size();
}
};
// For each missing skill...
while (!expertsNeeded.isEmpty()) {
UnitType neededSkill = expertsNeeded.remove(0);
Collections.sort(isList, listComparator);
List<IndianSettlement> extras = isList.remove(0);
UnitType extraSkill = extras.get(0).getLearnableSkill();
List<RandomChoice<IndianSettlement>> choices
= new ArrayList<RandomChoice<IndianSettlement>>();
// ...look at the settlements with the most common skill
// with a bit of favoritism to capitals as the needed skill
// is so rare,...
for (IndianSettlement is : extras) {
IndianNationType nation
= (IndianNationType) is.getOwner().getNationType();
int cm = (is.isCapital()) ? 2 : 1;
RandomChoice<IndianSettlement> rc = null;
for (RandomChoice<UnitType> c : nation.generateSkillsForTile(is.getTile())) {
if (c.getObject() == neededSkill) {
rc = new RandomChoice<IndianSettlement>(is, c.getProbability() * cm);
break;
}
}
choices.add((rc != null) ? rc
: new RandomChoice<IndianSettlement>(is, 1));
}
if (!choices.isEmpty()) {
// ...and pick one that could do the missing job.
IndianSettlement chose
= RandomChoice.getWeightedRandom(logger, "expert", random,
choices);
logger.finest("At " + chose.getName()
+ " replaced " + extraSkill
+ " (one of " + extras.size() + ")"
+ " by missing " + neededSkill);
chose.setLearnableSkill(neededSkill);
extras.remove(chose);
isList.add(0, extras); // Try to stay well sorted
List<IndianSettlement> neededList
= new ArrayList<IndianSettlement>();
neededList.add(chose);
isList.add(neededList);
} else { // `can not happen'
logger.finest("Game is missing skill: " + neededSkill);
}
}
String msg = "Settlement skills:";
for (List<IndianSettlement> iss : isList) {
- msg += " " + iss.size() + " x " + iss.get(0).getLearnableSkill();
+ if (iss.isEmpty()) {
+ msg += " 0 x <none>";
+ } else {
+ msg += " " + iss.size() + " x " + iss.get(0).getLearnableSkill();
+ }
}
logger.info(msg);
logger.info("Created " + settlementsPlaced
+ " Indian settlements of maximum " + settlementsToPlace);
}
/**
* Is a tile suitable for a native settlement?
* Require the tile be settleable, and at least half its neighbours
* also be settleable. TODO: degrade the second test to usability,
* but fix this when the natives-use-water situation is sorted.
*
* @param tile The <code>Tile</code> to examine.
* @return True if this tile is suitable.
*/
private boolean suitableForNativeSettlement(Tile tile) {
if (!tile.getType().canSettle()) return false;
int good = 0, n = 0;
for (Tile t : tile.getSurroundingTiles(1)) {
if (t.getType().canSettle()) good++;
n++;
}
return good >= n / 2;
}
private Tile findFreeNeighbouringTile(IndianSettlement is,
List<Tile> tiles, Random random) {
for (Tile tile : tiles) {
for (Direction d : Direction.getRandomDirections("freeTile", random)) {
Tile t = tile.getNeighbourOrNull(d);
if ((t != null)
&& (t.getOwningSettlement() == null)
&& (is.getOwner().canClaimForSettlement(t))) return t;
}
}
return null;
}
private Tile getClosestTile(Position center, List<Tile> tiles) {
Tile result = null;
int minimumDistance = Integer.MAX_VALUE;
for (Tile tile : tiles) {
int distance = tile.getPosition().getDistance(center);
if (distance < minimumDistance) {
minimumDistance = distance;
result = tile;
}
}
return result;
}
private Territory getClosestTerritory(Tile tile, List<Territory> territories) {
Territory result = null;
int minimumDistance = Integer.MAX_VALUE;
for (Territory territory : territories) {
int distance = tile.getPosition().getDistance(territory.getCenter());
if (distance < minimumDistance) {
minimumDistance = distance;
result = territory;
}
}
return result;
}
/**
* Builds a <code>IndianSettlement</code> at the given position.
*
* @param player The player owning the new settlement.
* @param capital <code>true</code> if the settlement should be a
* {@link IndianSettlement#isCapital() capital}.
* @param position The position to place the settlement.
* @param map The map that should get a new settlement.
* @return The <code>IndianSettlement</code> just being placed
* on the map.
*/
private IndianSettlement placeIndianSettlement(Player player,
boolean capital, Position position, Map map) {
final Tile tile = map.getTile(position);
String name = (capital) ? player.getCapitalName(random)
: player.getSettlementName(random);
UnitType skill
= generateSkillForLocation(map, tile, player.getNationType());
IndianSettlement settlement
= new ServerIndianSettlement(map.getGame(), player, name, tile,
capital, skill,
new HashSet<Player>(), null);
player.addSettlement(settlement);
logger.fine("Generated skill: " + settlement.getLearnableSkill());
int low = settlement.getType().getMinimumSize();
int high = settlement.getType().getMaximumSize();
int unitCount = low + random.nextInt(high - low);
for (int i = 0; i < unitCount; i++) {
UnitType unitType = map.getSpecification().getUnitType("model.unit.brave");
Unit unit = new ServerUnit(map.getGame(), settlement, player,
unitType, unitType.getDefaultEquipment());
unit.setIndianSettlement(settlement);
if (i == 0) {
unit.setLocation(tile);
} else {
unit.setLocation(settlement);
}
}
settlement.placeSettlement(true);
if (FreeColDebugger.getDebugLevel() >= FreeColDebugger.DEBUG_FULL) {
for (GoodsType type : map.getSpecification().getGoodsTypeList()) {
if (type.isNewWorldGoodsType()) settlement.addGoods(type, 150);
}
}
return settlement;
}
/**
* Generates a skill that could be taught from a settlement on the given Tile.
*
* @param map The <code>Map</code>.
* @param tile The tile where the settlement will be located.
* @return A skill that can be taught to Europeans.
*/
private UnitType generateSkillForLocation(Map map, Tile tile, NationType nationType) {
List<RandomChoice<UnitType>> skills = ((IndianNationType) nationType).getSkills();
java.util.Map<GoodsType, Integer> scale = new HashMap<GoodsType, Integer>();
for (RandomChoice<UnitType> skill : skills) {
scale.put(skill.getObject().getExpertProduction(), 1);
}
for (Tile t: tile.getSurroundingTiles(1)) {
for (GoodsType goodsType : scale.keySet()) {
scale.put(goodsType, scale.get(goodsType).intValue() + t.potential(goodsType, null));
}
}
List<RandomChoice<UnitType>> scaledSkills = new ArrayList<RandomChoice<UnitType>>();
for (RandomChoice<UnitType> skill : skills) {
UnitType unitType = skill.getObject();
int scaleValue = scale.get(unitType.getExpertProduction()).intValue();
scaledSkills.add(new RandomChoice<UnitType>(unitType, skill.getProbability() * scaleValue));
}
UnitType skill = RandomChoice.getWeightedRandom(null, null,
random, scaledSkills);
if (skill == null) {
// Seasoned Scout
List<UnitType> unitList = map.getSpecification().getUnitTypesWithAbility(Ability.EXPERT_SCOUT);
return unitList.get(random.nextInt(unitList.size()));
} else {
return skill;
}
}
/**
* Create two ships, one with a colonist, for each player, and
* select suitable starting positions.
*
* @param map The <code>Map</code> to place the european units on.
* @param players The players to create <code>Settlement</code>s
* and starting locations for. That is; both indian and
* european players.
*/
private void createEuropeanUnits(Map map, List<Player> players) {
Game game = map.getGame();
Specification spec = game.getSpecification();
final int width = map.getWidth();
final int height = map.getHeight();
final int poleDistance = (int)(MIN_DISTANCE_FROM_POLE*height/2);
List<Player> europeanPlayers = new ArrayList<Player>();
for (Player player : players) {
if (player.isREF()) {
// eastern edge of the map
int x = width - 2;
// random latitude, not too close to the pole
int y = random.nextInt(height - 2*poleDistance) + poleDistance;
player.setEntryLocation(map.getTile(x, y));
continue;
}
if (player.isEuropean()) {
europeanPlayers.add(player);
logger.finest("found European player " + player);
}
}
List<Position> positions = generateStartingPositions(map, europeanPlayers);
List<Tile> startingTiles = new ArrayList<Tile>();
for (int index = 0; index < europeanPlayers.size(); index++) {
Player player = europeanPlayers.get(index);
Position position = positions.get(index);
logger.fine("generating units for player " + player);
List<Unit> carriers = new ArrayList<Unit>();
List<Unit> passengers = new ArrayList<Unit>();
List<AbstractUnit> unitList = ((EuropeanNationType) player.getNationType())
.getStartingUnits();
for (AbstractUnit startingUnit : unitList) {
UnitType type = startingUnit.getUnitType(spec);
Unit newUnit = new ServerUnit(game, null, player, type,
startingUnit.getEquipment(spec));
newUnit.setName(player.getUnitName(type, random));
if (newUnit.isNaval()) {
if (newUnit.canCarryUnits()) {
newUnit.setState(Unit.UnitState.ACTIVE);
carriers.add(newUnit);
}
} else {
newUnit.setState(Unit.UnitState.SENTRY);
passengers.add(newUnit);
}
}
boolean startAtSea = true;
if (carriers.isEmpty()) {
logger.warning("No carriers defined for player " + player);
startAtSea = false;
}
Tile startTile = null;
int x = position.getX();
int y = position.getY();
for (int i = 0; i < 2 * map.getHeight(); i++) {
int offset = (i % 2 == 0) ? i / 2 : -(1 + i / 2);
int row = y + offset;
if (row < 0 || row >= map.getHeight()) continue;
startTile = findTileFor(map, row, x, startAtSea);
if (startTile != null) {
if (startingTiles.contains(startTile)) {
startTile = null;
} else {
startingTiles.add(startTile);
break;
}
}
}
if (startTile == null) {
String err = "Failed to find start tile "
+ ((startAtSea) ? "at sea" : "on land")
+ " for player " + player
+ " from (" + x + "," + y + ")"
+ " avoiding:";
for (Tile t : startingTiles) err += " " + t.toString();
err += " with map: ";
for (int xx = 0; xx < map.getWidth(); xx++) {
err += map.getTile(xx, y);
}
throw new RuntimeException(err);
}
startTile.setExploredBy(player, true);
player.setEntryLocation(startTile);
if (startAtSea) {
for (Unit carrier : carriers) {
carrier.setLocation(startTile);
}
passengers: for (Unit unit : passengers) {
for (Unit carrier : carriers) {
if (carrier.canAdd(unit)) {
unit.setLocation(carrier);
continue passengers;
}
}
// no space left on carriers
unit.setLocation(player.getEurope());
}
} else {
for (Unit unit : passengers) {
unit.setLocation(startTile);
}
}
if (FreeColDebugger.getDebugLevel() >= FreeColDebugger.DEBUG_FULL) {
createDebugUnits(map, player, startTile);
IntegerOption op = spec.getIntegerOption(GameOptions.STARTING_MONEY);
if (op != null) op.setValue(10000);
}
}
}
private Tile findTileFor(Map map, int row, int start, boolean startAtSea) {
Tile tile = null;
Tile seas = null;
int offset = (start == 0) ? 1 : -1;
for (int x = start; 0 <= x && x < map.getWidth(); x += offset) {
tile = map.getTile(x, row);
if (tile.isDirectlyHighSeasConnected()) {
seas = tile;
} else if (tile.isLand()) {
if (startAtSea) {
if (seas == null) {
logger.warning("No high seas in row " + row);
}
return seas;
}
return tile;
}
}
logger.warning("No land in row " + row);
return null;
}
private void createDebugUnits(Map map, Player player, Tile startTile) {
Game game = map.getGame();
Specification spec = game.getSpecification();
// In debug mode give each player a few more units and a colony.
UnitType unitType = spec.getUnitType("model.unit.galleon");
Unit unit4 = new ServerUnit(game, startTile, player, unitType);
unitType = spec.getUnitType("model.unit.privateer");
@SuppressWarnings("unused")
Unit privateer = new ServerUnit(game, startTile, player, unitType);
unitType = spec.getUnitType("model.unit.freeColonist");
@SuppressWarnings("unused")
Unit unit5 = new ServerUnit(game, unit4, player, unitType);
unitType = spec.getUnitType("model.unit.veteranSoldier");
@SuppressWarnings("unused")
Unit unit6 = new ServerUnit(game, unit4, player, unitType);
unitType = spec.getUnitType("model.unit.jesuitMissionary");
@SuppressWarnings("unused")
Unit unit7 = new ServerUnit(game, unit4, player, unitType);
Tile colonyTile = null;
Iterator<Position> cti
= map.getFloodFillIterator(startTile.getPosition());
while (cti.hasNext()) {
Tile tempTile = map.getTile(cti.next());
if (tempTile.isPolar()) {
// do not place the initial colony at the pole
continue;
}
if (player.canClaimToFoundSettlement(tempTile)) {
colonyTile = tempTile;
break;
}
}
if (colonyTile == null) {
logger.warning("Could not find a debug colony site.");
return;
}
for (TileType t : spec.getTileTypeList()) {
if (!t.isWater()) {
colonyTile.setType(t);
break;
}
}
unitType = spec.getUnitType("model.unit.expertFarmer");
Unit buildColonyUnit = new ServerUnit(game, colonyTile,
player, unitType);
String colonyName = Messages.message(player.getNationName())
+ " Colony";
Colony colony = new ServerColony(game, player, colonyName, colonyTile);
player.addSettlement(colony);
colony.placeSettlement(true);
for (Tile tile : colonyTile.getSurroundingTiles(1)) {
if (tile.getSettlement() == null
&& (tile.getOwner() == null
|| !tile.getOwner().isEuropean())) {
tile.changeOwnership(player, colony);
if (tile.hasLostCityRumour()) {
tile.removeLostCityRumour();
}
}
}
buildColonyUnit.setLocation(colony);
if (buildColonyUnit.getLocation() instanceof ColonyTile) {
Tile ct = ((ColonyTile) buildColonyUnit.getLocation()).getWorkTile();
for (TileType t : spec.getTileTypeList()) {
if (!t.isWater()) {
ct.setType(t);
TileImprovementType plowType = map.getSpecification()
.getTileImprovementType("model.improvement.plow");
TileImprovementType roadType = map.getSpecification()
.getTileImprovementType("model.improvement.road");
TileImprovement road = new TileImprovement(game, ct, roadType);
road.setTurnsToComplete(0);
TileImprovement plow = new TileImprovement(game, ct, plowType);
plow.setTurnsToComplete(0);
ct.setTileItemContainer(new TileItemContainer(game, ct));
ct.getTileItemContainer().addTileItem(road);
ct.getTileItemContainer().addTileItem(plow);
break;
}
}
}
BuildingType schoolType = spec.getBuildingType("model.building.schoolhouse");
Building schoolhouse = new ServerBuilding(game, colony, schoolType);
colony.addBuilding(schoolhouse);
unitType = spec.getUnitType("model.unit.masterCarpenter");
Unit carpenter = new ServerUnit(game, colonyTile, player, unitType);
carpenter.setLocation(colony.getBuildingForProducing(unitType.getExpertProduction()));
unitType = spec.getUnitType("model.unit.elderStatesman");
Unit statesman = new ServerUnit(game, colonyTile, player, unitType);
statesman.setLocation(colony.getBuildingForProducing(unitType.getExpertProduction()));
unitType = spec.getUnitType("model.unit.expertLumberJack");
Unit lumberjack = new ServerUnit(game, colony, player, unitType);
if (lumberjack.getLocation() instanceof ColonyTile) {
Tile lt = ((ColonyTile) lumberjack.getLocation()).getWorkTile();
for (TileType t : spec.getTileTypeList()) {
if (t.isForested()) {
lt.setType(t);
break;
}
}
lumberjack.setWorkType(lumberjack.getType().getExpertProduction());
}
unitType = spec.getUnitType("model.unit.seasonedScout");
@SuppressWarnings("unused")
Unit scout = new ServerUnit(game, colonyTile, player, unitType);
unitType = spec.getUnitType("model.unit.veteranSoldier");
@SuppressWarnings("unused")
Unit unit8 = new ServerUnit(game, colonyTile, player, unitType);
@SuppressWarnings("unused")
Unit unit9 = new ServerUnit(game, colonyTile, player, unitType);
unitType = spec.getUnitType("model.unit.artillery");
@SuppressWarnings("unused")
Unit unit10 = new ServerUnit(game, colonyTile, player, unitType);
@SuppressWarnings("unused")
Unit unit11 = new ServerUnit(game, colonyTile, player, unitType);
@SuppressWarnings("unused")
Unit unit12 = new ServerUnit(game, colonyTile, player, unitType);
unitType = spec.getUnitType("model.unit.treasureTrain");
Unit unit13 = new ServerUnit(game, colonyTile, player, unitType);
unit13.setTreasureAmount(10000);
unitType = spec.getUnitType("model.unit.wagonTrain");
Unit unit14 = new ServerUnit(game, colonyTile, player, unitType);
GoodsType cigarsType = spec.getGoodsType("model.goods.cigars");
Goods cigards = new Goods(game, unit14, cigarsType, 5);
unit14.add(cigards);
unitType = spec.getUnitType("model.unit.jesuitMissionary");
@SuppressWarnings("unused")
Unit unit15 = new ServerUnit(game, colonyTile, player, unitType);
@SuppressWarnings("unused")
Unit unit16 = new ServerUnit(game, colonyTile, player, unitType);
// END DEBUG
}
private List<Position> generateStartingPositions(Map map, List<Player> players) {
int number = players.size();
List<Position> positions = new ArrayList<Position>(number);
if (number > 0) {
int west = 0;
int east = map.getWidth() - 1;
switch(map.getSpecification().getInteger(GameOptions.STARTING_POSITIONS)) {
case GameOptions.STARTING_POSITIONS_CLASSIC:
int distance = map.getHeight() / number;
int row = distance/2;
for (int index = 0; index < number; index++) {
positions.add(new Position(east, row));
row += distance;
}
Collections.shuffle(positions);
break;
case GameOptions.STARTING_POSITIONS_RANDOM:
distance = 2 * map.getHeight() / number;
row = distance/2;
for (int index = 0; index < number; index++) {
if (index % 2 == 0) {
positions.add(new Position(east, row));
} else {
positions.add(new Position(west, row));
row += distance;
}
}
Collections.shuffle(positions);
break;
case GameOptions.STARTING_POSITIONS_HISTORICAL:
for (Player player : players) {
Nation nation = player.getNation();
positions.add(new Position(nation.startsOnEastCoast() ? east : west,
map.getRow(nation.getPreferredLatitude())));
}
break;
}
}
return positions;
}
private class Territory {
public ServerRegion region;
public Position position;
public Player player;
public int numberOfSettlements;
public Territory(Player player, Position position) {
this.player = player;
this.position = position;
}
public Territory(Player player, ServerRegion region) {
this.player = player;
this.region = region;
}
public Position getCenter() {
if (position == null) {
return region.getCenter();
} else {
return position;
}
}
public String toString() {
return player + " territory at " + region.toString();
}
}
}
| true | true | private void createIndianSettlements(final Map map, List<Player> players) {
Specification spec = map.getGame().getSpecification();
float shares = 0f;
List<IndianSettlement> settlements = new ArrayList<IndianSettlement>();
List<Player> indians = new ArrayList<Player>();
HashMap<String, Territory> territoryMap
= new HashMap<String, Territory>();
for (Player player : players) {
if (!player.isIndian()) continue;
switch (((IndianNationType) player.getNationType())
.getNumberOfSettlements()) {
case HIGH:
shares += 4;
break;
case AVERAGE:
shares += 3;
break;
case LOW:
shares += 2;
break;
}
indians.add(player);
List<String> regionNames
= ((IndianNationType) player.getNationType()).getRegionNames();
Territory territory = null;
if (regionNames == null || regionNames.isEmpty()) {
territory = new Territory(player, terrainGenerator.getRandomLandPosition(map, random));
territoryMap.put(player.getId(), territory);
} else {
for (String name : regionNames) {
if (territoryMap.get(name) == null) {
ServerRegion region = (ServerRegion) map.getRegion(name);
if (region == null) {
territory = new Territory(player, terrainGenerator.getRandomLandPosition(map, random));
} else {
territory = new Territory(player, region);
}
territoryMap.put(name, territory);
logger.fine("Allocated region " + name
+ " for " + player
+ ". Center is " + territory.getCenter()
+ ".");
break;
}
}
if (territory == null) {
logger.warning("Failed to allocate preferred region " + regionNames.get(0)
+ " for " + player.getNation());
outer: for (String name : regionNames) {
Territory otherTerritory = territoryMap.get(name);
for (String otherName : ((IndianNationType) otherTerritory.player.getNationType())
.getRegionNames()) {
if (territoryMap.get(otherName) == null) {
ServerRegion foundRegion = otherTerritory.region;
otherTerritory.region = (ServerRegion) map.getRegion(otherName);
territoryMap.put(otherName, otherTerritory);
territory = new Territory(player, foundRegion);
territoryMap.put(name, territory);
break outer;
}
}
}
if (territory == null) {
logger.warning("Unable to find free region for "
+ player.getName());
territory = new Territory(player, terrainGenerator.getRandomLandPosition(map, random));
territoryMap.put(player.getId(), territory);
}
}
}
}
if (indians.isEmpty()) return;
// Examine all the non-polar settleable tiles in a random
// order picking out as many as possible suitable tiles for
// native settlements such that can be guaranteed at least one
// layer of surrounding tiles to own.
int minSettlementDistance
= spec.getRangeOption("model.option.settlementNumber").getValue();
List<Tile> settlementTiles = new ArrayList<Tile>();
tiles: for (Tile tile : map.getAllTiles()) {
if (!tile.isPolar() && suitableForNativeSettlement(tile)) {
for (Tile t : settlementTiles) {
if (tile.getDistanceTo(t) < minSettlementDistance) {
continue tiles;
}
}
settlementTiles.add(tile);
}
}
Collections.shuffle(settlementTiles, random);
// Check number of settlements.
int settlementsToPlace = settlementTiles.size();
float share = settlementsToPlace / shares;
if (settlementTiles.size() < indians.size()) {
// TODO: something drastic to boost the settlement number
logger.warning("There are only " + settlementTiles.size()
+ " settlement sites."
+ " This is smaller than " + indians.size()
+ " the number of tribes.");
}
// Find the capitals
List<Territory> territories
= new ArrayList<Territory>(territoryMap.values());
int settlementsPlaced = 0;
for (Territory territory : territories) {
switch (((IndianNationType) territory.player.getNationType())
.getNumberOfSettlements()) {
case HIGH:
territory.numberOfSettlements = Math.round(4 * share);
break;
case AVERAGE:
territory.numberOfSettlements = Math.round(3 * share);
break;
case LOW:
territory.numberOfSettlements = Math.round(2 * share);
break;
}
int radius = territory.player.getNationType().getCapitalType().getClaimableRadius();
ArrayList<Tile> capitalTiles = new ArrayList<Tile>(settlementTiles);
while (!capitalTiles.isEmpty()) {
Tile tile = getClosestTile(territory.getCenter(),
capitalTiles);
capitalTiles.remove(tile);
// Choose this tile if it is free and half the expected tile
// claim can succeed (preventing capitals on small islands).
if (map.getClaimableTiles(territory.player, tile, radius).size()
>= (2 * radius + 1) * (2 * radius + 1) / 2) {
String name = (territory.region == null) ? "default region"
: territory.region.getNameKey();
logger.fine("Placing the " + territory.player
+ " capital in region: " + name
+ " at Tile: "+ tile.getPosition());
settlements.add(placeIndianSettlement(territory.player,
true, tile.getPosition(), map));
territory.numberOfSettlements--;
territory.position = tile.getPosition();
settlementTiles.remove(tile);
settlementsPlaced++;
break;
}
}
}
// Sort tiles from the edges of the map inward
Collections.sort(settlementTiles, new Comparator<Tile>() {
public int compare(Tile tile1, Tile tile2) {
int distance1 = Math.min(Math.min(tile1.getX(), map.getWidth() - tile1.getX()),
Math.min(tile1.getY(), map.getHeight() - tile1.getY()));
int distance2 = Math.min(Math.min(tile2.getX(), map.getWidth() - tile2.getX()),
Math.min(tile2.getY(), map.getHeight() - tile2.getY()));
return (distance1 - distance2);
}
});
// Now place other settlements
while (!settlementTiles.isEmpty() && !territories.isEmpty()) {
Tile tile = settlementTiles.remove(0);
if (tile.getOwner() != null) continue; // No close overlap
Territory territory = getClosestTerritory(tile, territories);
int radius = territory.player.getNationType().getSettlementType(false)
.getClaimableRadius();
// Insist that the settlement can not be linear
if (map.getClaimableTiles(territory.player, tile, radius).size()
> 2 * radius + 1) {
String name = (territory.region == null) ? "default region"
: territory.region.getNameKey();
logger.fine("Placing a " + territory.player
+ " camp in region: " + name
+ " at Tile: " + tile.getPosition());
settlements.add(placeIndianSettlement(territory.player,
false, tile.getPosition(), map));
settlementsPlaced++;
territory.numberOfSettlements--;
if (territory.numberOfSettlements <= 0) {
territories.remove(territory);
}
}
}
// Grow some more tiles.
// TODO: move the magic numbers below to the spec RSN
// Also collect the skills provided
HashMap<UnitType, List<IndianSettlement>> skills
= new HashMap<UnitType, List<IndianSettlement>>();
Collections.shuffle(settlements, random);
for (IndianSettlement is : settlements) {
List<Tile> tiles = new ArrayList<Tile>();
for (Tile tile : is.getOwnedTiles()) {
for (Tile t : tile.getSurroundingTiles(1)) {
if (t.getOwningSettlement() == null) {
tiles.add(tile);
break;
}
}
}
Collections.shuffle(tiles, random);
int minGrow = is.getType().getMinimumGrowth();
int maxGrow = is.getType().getMaximumGrowth();
if (maxGrow > minGrow) {
for (int i = random.nextInt(maxGrow - minGrow) + minGrow;
i > 0; i--) {
Tile tile = findFreeNeighbouringTile(is, tiles, random);
if (tile == null) break;
tile.changeOwnership(is.getOwner(), is);
tiles.add(tile);
}
}
// Collect settlements by skill
UnitType skill = is.getLearnableSkill();
List<IndianSettlement> isList = skills.get(skill);
if (isList == null) {
isList = new ArrayList<IndianSettlement>();
isList.add(is);
skills.put(skill, isList);
} else {
isList.add(is);
}
}
// Require that there be experts for all the new world goods types.
// Collect the list of needed experts
List<UnitType> expertsNeeded = new ArrayList<UnitType>();
for (GoodsType goodsType : spec.getNewWorldGoodsTypeList()) {
UnitType expert = spec.getExpertForProducing(goodsType);
if (!skills.containsKey(expert)) expertsNeeded.add(expert);
}
// Extract just the settlement lists.
List<List<IndianSettlement>> isList
= new ArrayList<List<IndianSettlement>>(skills.values());
Comparator<List<IndianSettlement>> listComparator
= new Comparator<List<IndianSettlement>>() {
public int compare(List<IndianSettlement> l1,
List<IndianSettlement> l2) {
return l2.size() - l1.size();
}
};
// For each missing skill...
while (!expertsNeeded.isEmpty()) {
UnitType neededSkill = expertsNeeded.remove(0);
Collections.sort(isList, listComparator);
List<IndianSettlement> extras = isList.remove(0);
UnitType extraSkill = extras.get(0).getLearnableSkill();
List<RandomChoice<IndianSettlement>> choices
= new ArrayList<RandomChoice<IndianSettlement>>();
// ...look at the settlements with the most common skill
// with a bit of favoritism to capitals as the needed skill
// is so rare,...
for (IndianSettlement is : extras) {
IndianNationType nation
= (IndianNationType) is.getOwner().getNationType();
int cm = (is.isCapital()) ? 2 : 1;
RandomChoice<IndianSettlement> rc = null;
for (RandomChoice<UnitType> c : nation.generateSkillsForTile(is.getTile())) {
if (c.getObject() == neededSkill) {
rc = new RandomChoice<IndianSettlement>(is, c.getProbability() * cm);
break;
}
}
choices.add((rc != null) ? rc
: new RandomChoice<IndianSettlement>(is, 1));
}
if (!choices.isEmpty()) {
// ...and pick one that could do the missing job.
IndianSettlement chose
= RandomChoice.getWeightedRandom(logger, "expert", random,
choices);
logger.finest("At " + chose.getName()
+ " replaced " + extraSkill
+ " (one of " + extras.size() + ")"
+ " by missing " + neededSkill);
chose.setLearnableSkill(neededSkill);
extras.remove(chose);
isList.add(0, extras); // Try to stay well sorted
List<IndianSettlement> neededList
= new ArrayList<IndianSettlement>();
neededList.add(chose);
isList.add(neededList);
} else { // `can not happen'
logger.finest("Game is missing skill: " + neededSkill);
}
}
String msg = "Settlement skills:";
for (List<IndianSettlement> iss : isList) {
msg += " " + iss.size() + " x " + iss.get(0).getLearnableSkill();
}
logger.info(msg);
logger.info("Created " + settlementsPlaced
+ " Indian settlements of maximum " + settlementsToPlace);
}
| private void createIndianSettlements(final Map map, List<Player> players) {
Specification spec = map.getGame().getSpecification();
float shares = 0f;
List<IndianSettlement> settlements = new ArrayList<IndianSettlement>();
List<Player> indians = new ArrayList<Player>();
HashMap<String, Territory> territoryMap
= new HashMap<String, Territory>();
for (Player player : players) {
if (!player.isIndian()) continue;
switch (((IndianNationType) player.getNationType())
.getNumberOfSettlements()) {
case HIGH:
shares += 4;
break;
case AVERAGE:
shares += 3;
break;
case LOW:
shares += 2;
break;
}
indians.add(player);
List<String> regionNames
= ((IndianNationType) player.getNationType()).getRegionNames();
Territory territory = null;
if (regionNames == null || regionNames.isEmpty()) {
territory = new Territory(player, terrainGenerator.getRandomLandPosition(map, random));
territoryMap.put(player.getId(), territory);
} else {
for (String name : regionNames) {
if (territoryMap.get(name) == null) {
ServerRegion region = (ServerRegion) map.getRegion(name);
if (region == null) {
territory = new Territory(player, terrainGenerator.getRandomLandPosition(map, random));
} else {
territory = new Territory(player, region);
}
territoryMap.put(name, territory);
logger.fine("Allocated region " + name
+ " for " + player
+ ". Center is " + territory.getCenter()
+ ".");
break;
}
}
if (territory == null) {
logger.warning("Failed to allocate preferred region " + regionNames.get(0)
+ " for " + player.getNation());
outer: for (String name : regionNames) {
Territory otherTerritory = territoryMap.get(name);
for (String otherName : ((IndianNationType) otherTerritory.player.getNationType())
.getRegionNames()) {
if (territoryMap.get(otherName) == null) {
ServerRegion foundRegion = otherTerritory.region;
otherTerritory.region = (ServerRegion) map.getRegion(otherName);
territoryMap.put(otherName, otherTerritory);
territory = new Territory(player, foundRegion);
territoryMap.put(name, territory);
break outer;
}
}
}
if (territory == null) {
logger.warning("Unable to find free region for "
+ player.getName());
territory = new Territory(player, terrainGenerator.getRandomLandPosition(map, random));
territoryMap.put(player.getId(), territory);
}
}
}
}
if (indians.isEmpty()) return;
// Examine all the non-polar settleable tiles in a random
// order picking out as many as possible suitable tiles for
// native settlements such that can be guaranteed at least one
// layer of surrounding tiles to own.
int minSettlementDistance
= spec.getRangeOption("model.option.settlementNumber").getValue();
List<Tile> settlementTiles = new ArrayList<Tile>();
tiles: for (Tile tile : map.getAllTiles()) {
if (!tile.isPolar() && suitableForNativeSettlement(tile)) {
for (Tile t : settlementTiles) {
if (tile.getDistanceTo(t) < minSettlementDistance) {
continue tiles;
}
}
settlementTiles.add(tile);
}
}
Collections.shuffle(settlementTiles, random);
// Check number of settlements.
int settlementsToPlace = settlementTiles.size();
float share = settlementsToPlace / shares;
if (settlementTiles.size() < indians.size()) {
// TODO: something drastic to boost the settlement number
logger.warning("There are only " + settlementTiles.size()
+ " settlement sites."
+ " This is smaller than " + indians.size()
+ " the number of tribes.");
}
// Find the capitals
List<Territory> territories
= new ArrayList<Territory>(territoryMap.values());
int settlementsPlaced = 0;
for (Territory territory : territories) {
switch (((IndianNationType) territory.player.getNationType())
.getNumberOfSettlements()) {
case HIGH:
territory.numberOfSettlements = Math.round(4 * share);
break;
case AVERAGE:
territory.numberOfSettlements = Math.round(3 * share);
break;
case LOW:
territory.numberOfSettlements = Math.round(2 * share);
break;
}
int radius = territory.player.getNationType().getCapitalType().getClaimableRadius();
ArrayList<Tile> capitalTiles = new ArrayList<Tile>(settlementTiles);
while (!capitalTiles.isEmpty()) {
Tile tile = getClosestTile(territory.getCenter(),
capitalTiles);
capitalTiles.remove(tile);
// Choose this tile if it is free and half the expected tile
// claim can succeed (preventing capitals on small islands).
if (map.getClaimableTiles(territory.player, tile, radius).size()
>= (2 * radius + 1) * (2 * radius + 1) / 2) {
String name = (territory.region == null) ? "default region"
: territory.region.getNameKey();
logger.fine("Placing the " + territory.player
+ " capital in region: " + name
+ " at Tile: "+ tile.getPosition());
settlements.add(placeIndianSettlement(territory.player,
true, tile.getPosition(), map));
territory.numberOfSettlements--;
territory.position = tile.getPosition();
settlementTiles.remove(tile);
settlementsPlaced++;
break;
}
}
}
// Sort tiles from the edges of the map inward
Collections.sort(settlementTiles, new Comparator<Tile>() {
public int compare(Tile tile1, Tile tile2) {
int distance1 = Math.min(Math.min(tile1.getX(), map.getWidth() - tile1.getX()),
Math.min(tile1.getY(), map.getHeight() - tile1.getY()));
int distance2 = Math.min(Math.min(tile2.getX(), map.getWidth() - tile2.getX()),
Math.min(tile2.getY(), map.getHeight() - tile2.getY()));
return (distance1 - distance2);
}
});
// Now place other settlements
while (!settlementTiles.isEmpty() && !territories.isEmpty()) {
Tile tile = settlementTiles.remove(0);
if (tile.getOwner() != null) continue; // No close overlap
Territory territory = getClosestTerritory(tile, territories);
int radius = territory.player.getNationType().getSettlementType(false)
.getClaimableRadius();
// Insist that the settlement can not be linear
if (map.getClaimableTiles(territory.player, tile, radius).size()
> 2 * radius + 1) {
String name = (territory.region == null) ? "default region"
: territory.region.getNameKey();
logger.fine("Placing a " + territory.player
+ " camp in region: " + name
+ " at Tile: " + tile.getPosition());
settlements.add(placeIndianSettlement(territory.player,
false, tile.getPosition(), map));
settlementsPlaced++;
territory.numberOfSettlements--;
if (territory.numberOfSettlements <= 0) {
territories.remove(territory);
}
}
}
// Grow some more tiles.
// TODO: move the magic numbers below to the spec RSN
// Also collect the skills provided
HashMap<UnitType, List<IndianSettlement>> skills
= new HashMap<UnitType, List<IndianSettlement>>();
Collections.shuffle(settlements, random);
for (IndianSettlement is : settlements) {
List<Tile> tiles = new ArrayList<Tile>();
for (Tile tile : is.getOwnedTiles()) {
for (Tile t : tile.getSurroundingTiles(1)) {
if (t.getOwningSettlement() == null) {
tiles.add(tile);
break;
}
}
}
Collections.shuffle(tiles, random);
int minGrow = is.getType().getMinimumGrowth();
int maxGrow = is.getType().getMaximumGrowth();
if (maxGrow > minGrow) {
for (int i = random.nextInt(maxGrow - minGrow) + minGrow;
i > 0; i--) {
Tile tile = findFreeNeighbouringTile(is, tiles, random);
if (tile == null) break;
tile.changeOwnership(is.getOwner(), is);
tiles.add(tile);
}
}
// Collect settlements by skill
UnitType skill = is.getLearnableSkill();
List<IndianSettlement> isList = skills.get(skill);
if (isList == null) {
isList = new ArrayList<IndianSettlement>();
isList.add(is);
skills.put(skill, isList);
} else {
isList.add(is);
}
}
// Require that there be experts for all the new world goods types.
// Collect the list of needed experts
List<UnitType> expertsNeeded = new ArrayList<UnitType>();
for (GoodsType goodsType : spec.getNewWorldGoodsTypeList()) {
UnitType expert = spec.getExpertForProducing(goodsType);
if (!skills.containsKey(expert)) expertsNeeded.add(expert);
}
// Extract just the settlement lists.
List<List<IndianSettlement>> isList
= new ArrayList<List<IndianSettlement>>(skills.values());
Comparator<List<IndianSettlement>> listComparator
= new Comparator<List<IndianSettlement>>() {
public int compare(List<IndianSettlement> l1,
List<IndianSettlement> l2) {
return l2.size() - l1.size();
}
};
// For each missing skill...
while (!expertsNeeded.isEmpty()) {
UnitType neededSkill = expertsNeeded.remove(0);
Collections.sort(isList, listComparator);
List<IndianSettlement> extras = isList.remove(0);
UnitType extraSkill = extras.get(0).getLearnableSkill();
List<RandomChoice<IndianSettlement>> choices
= new ArrayList<RandomChoice<IndianSettlement>>();
// ...look at the settlements with the most common skill
// with a bit of favoritism to capitals as the needed skill
// is so rare,...
for (IndianSettlement is : extras) {
IndianNationType nation
= (IndianNationType) is.getOwner().getNationType();
int cm = (is.isCapital()) ? 2 : 1;
RandomChoice<IndianSettlement> rc = null;
for (RandomChoice<UnitType> c : nation.generateSkillsForTile(is.getTile())) {
if (c.getObject() == neededSkill) {
rc = new RandomChoice<IndianSettlement>(is, c.getProbability() * cm);
break;
}
}
choices.add((rc != null) ? rc
: new RandomChoice<IndianSettlement>(is, 1));
}
if (!choices.isEmpty()) {
// ...and pick one that could do the missing job.
IndianSettlement chose
= RandomChoice.getWeightedRandom(logger, "expert", random,
choices);
logger.finest("At " + chose.getName()
+ " replaced " + extraSkill
+ " (one of " + extras.size() + ")"
+ " by missing " + neededSkill);
chose.setLearnableSkill(neededSkill);
extras.remove(chose);
isList.add(0, extras); // Try to stay well sorted
List<IndianSettlement> neededList
= new ArrayList<IndianSettlement>();
neededList.add(chose);
isList.add(neededList);
} else { // `can not happen'
logger.finest("Game is missing skill: " + neededSkill);
}
}
String msg = "Settlement skills:";
for (List<IndianSettlement> iss : isList) {
if (iss.isEmpty()) {
msg += " 0 x <none>";
} else {
msg += " " + iss.size() + " x " + iss.get(0).getLearnableSkill();
}
}
logger.info(msg);
logger.info("Created " + settlementsPlaced
+ " Indian settlements of maximum " + settlementsToPlace);
}
|
diff --git a/src/main/java/org/openarchives/resourcesync/ResourceSyncDescription.java b/src/main/java/org/openarchives/resourcesync/ResourceSyncDescription.java
index eabfa21..5b8dd5a 100644
--- a/src/main/java/org/openarchives/resourcesync/ResourceSyncDescription.java
+++ b/src/main/java/org/openarchives/resourcesync/ResourceSyncDescription.java
@@ -1,47 +1,50 @@
package org.openarchives.resourcesync;
import java.util.List;
public class ResourceSyncDescription extends UrlSet
{
public ResourceSyncDescription()
{
super(ResourceSync.CAPABILITY_RESOURCESYNC);
}
public ResourceSyncDescription(String describedby, String describedByContentType)
{
this();
ResourceSyncLn ln = this.addLn(ResourceSync.REL_DESCRIBED_BY, describedby);
ln.setType(describedByContentType);
}
public void addCapabilityList(URL caplist)
{
if (!ResourceSync.CAPABILITY_CAPABILITYLIST.equals(caplist.getCapability()))
{
throw new SpecComplianceException("URL added to ResourceSyncDescription is not a Capability List");
}
this.addUrl(caplist);
}
public URL addCapabilityList(String loc)
{
return this.addCapabilityList(loc, null);
}
public URL addCapabilityList(String loc, String describedby)
{
URL caplist = new URL();
caplist.setLoc(loc);
- caplist.addLn(ResourceSync.REL_DESCRIBED_BY, describedby);
+ if (describedby != null)
+ {
+ caplist.addLn(ResourceSync.REL_DESCRIBED_BY, describedby);
+ }
caplist.setCapability(ResourceSync.CAPABILITY_CAPABILITYLIST);
this.addCapabilityList(caplist);
return caplist;
}
public List<ResourceSyncEntry> getCapabilityLists()
{
return this.getUrls();
}
}
| true | true | public URL addCapabilityList(String loc, String describedby)
{
URL caplist = new URL();
caplist.setLoc(loc);
caplist.addLn(ResourceSync.REL_DESCRIBED_BY, describedby);
caplist.setCapability(ResourceSync.CAPABILITY_CAPABILITYLIST);
this.addCapabilityList(caplist);
return caplist;
}
| public URL addCapabilityList(String loc, String describedby)
{
URL caplist = new URL();
caplist.setLoc(loc);
if (describedby != null)
{
caplist.addLn(ResourceSync.REL_DESCRIBED_BY, describedby);
}
caplist.setCapability(ResourceSync.CAPABILITY_CAPABILITYLIST);
this.addCapabilityList(caplist);
return caplist;
}
|
diff --git a/World.java b/World.java
index 11dd0c7..82fd3d6 100644
--- a/World.java
+++ b/World.java
@@ -1,640 +1,640 @@
package textbased;
import java.util.*;
/**
* Text based version of Karel the Robot
* Current version has 1 predefined map
* @author Heather,Noel,Sam,Amber,Josh,MacsR4Luzrs
*/
public class World
{
private ArrayList walls = new ArrayList();//walls in world
private ArrayList gems = new ArrayList(); //gems in world
private boolean isRunning = true; //game ending bool
Wall home = new Wall(0,0); // home space
Player player; //object for karel
//Map
public static String level =
"####################\n"
+ "# $ #\n"
+ "# $#$ #\n"
+ "# $###$ #\n"
+ "# $#####$ #\n"
+ "# $#######$ #\n"
+ "# $#########$ #\n"
+ "# $###########$ #\n"
+ "#^ #############$ .#\n"
+ "####################\n";
//Constructor - Set up world
public World()
{
initWorld();
}
//Reads the map and adds all objects and their coordinates to arraylists
public final void initWorld()
{
//create wall and gem objects
Wall wall;
Gem gem;
//variables used to keep track of coordinates during loop
int x = 0;
int y = 0;
for (int i = 0; i < level.length(); i++)
{
//Grab the item in string at i
char item = level.charAt(i);
//Adjust X,Y value based on what character is at i
//and create an item in the array list if needed
if (item == '\n')
{
y += 1;
x = 0;
}
else if (item == '#')
{
wall = new Wall(x,y);
walls.add(wall);
x += 1;
}
else if (item == '^')
{
player = new Player(x,y);
x += 1;
}
else if (item == '$')
{
gem = new Gem(x,y);
gems.add(gem);
x += 1;
}
else if (item == '.')
{
home.SetX(x);
home.SetY(y);
x += 1;
}
else if (item == ' ')
{
x += 1;
}
}
//Print the original map and legend
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println(" Karel the Robot");
System.out.print("Karel's directions: ^ North | "
+ "v South | > East | < West | ");
System.out.println("# Walls | $ Gems | . Home");
System.out.print(level);
System.out.println("(Pick up all gems and go home)");
//start up the game controller
mController game = new mController();
}
//updates the map with karels new position
public static void updateMap(int new_x, int new_y, char symbol)
{
int num_rows = 10; // The number of rows
int num_cols = 20; // The number of columns. Does not include the \n
int num_symbols = 4; // The number of symbols for Karel
int old_x = -1;
int old_y = -1;
char[] karel_symbols = {'^', '<', '>', 'v'}; // Karels symbols
/* Converting from level string to temporary string array */
String[] convert_map = new String [num_rows];
for (int i= 0; i < num_rows; i++)
{
int x = (i * (num_cols + 1));
convert_map[i] = level.substring(x, (x + num_cols));
}
/* Finding the last place Karel was and removing it */
for (int i = 0; i < num_rows; i++)
{
for (int h = 0; h < num_symbols; h++)
{
/* Iterating through all of the possible Karel symbols
and checking each string for their position. */
int checker = convert_map[i].indexOf(karel_symbols[h]);
if (checker != -1)
{
old_y = i;
old_x = checker;
break;
}
}
}
/* Converting from temp string array to 2d character array*/
char[][] current_map = new char [num_rows] [num_cols];
for (int i = 0; i < num_rows; i++)
{
current_map[i] = convert_map[i].toCharArray();
}
if ((old_x != -1) && (old_y != -1))
{ // Making sure old_x and old_y were found
current_map[old_y][old_x] = ' '; // Replacing Karel's old position
}
current_map[new_y][new_x] = symbol; // Putting Karel in his new position
/* Overwriting level with updated map */
String temp_level = new String();
for (int i = 0; i < num_rows; i++)
{
for (int h = 0; h < num_cols; h++)
{
temp_level += current_map[i][h];
}
temp_level += '\n';
}
level = temp_level;
}
//Game controller
final class mController
{
public mController()
{
//Run the game until finished
while (isRunning == true)
{
//prompt user with choices and process input
choiceMade(choiceOptions());
//Print the updated map
System.out.println(" Karel The Robot");
System.out.print(level);
System.out.println("Gems remaining: " + gems.size());
}
}
//Prompt the user with choices
public int choiceOptions()
{
System.out.println("Enter a choice:");
System.out.println("1 - Go (Move Karel one space forward in his "
+ "current direction)");
System.out.println("2 - Turn Karel Left");
System.out.println("3 - Turn Karel Right");
System.out.println("4 - Multiple Instructions (Command Line)");
Scanner in = new Scanner(System.in);
int user_input = in.nextInt();
System.out.print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
return user_input;
}
public void actions()
{
Scanner in = new Scanner(System.in);
List<String> user_input = new ArrayList<>();
String new_input = new String();
boolean check;
System.out.println("Input instructions followed by "
+ "enter (Use 0 to run all commands):");
System.out.println("Left");
System.out.println("Right");
System.out.println("Go");
System.out.println("While <condition>");
System.out.println("If <condition>");
System.out.println("Repeat <integer>");
System.out.println("Conditions are: gem, home, and wall");
System.out.println("Each can be preceded by 'not'");
System.out.println("---------------------------------------------"
+ "---------------------------");
while (true)
{ // Reading in the users instructions
new_input = in.nextLine().toLowerCase();
check = new_input.equals("0");
if (check)
{
break;
}
if (new_input.trim().length() > 0)
{ // If the line isn't blank
user_input.add(new_input); // Adding it
}
}
System.out.println("---------------------------------------------"
+ "---------------------------");
System.out.println("\n\n");
int line_count = doScript(0, 0, user_input); // Running the script
if (line_count > user_input.size())
{ // If an error was returned
System.out.println("Press enter to continue...");
in.nextLine();
}
}
public int doScript(int line_count, int scope, List<String> user_input)
{ // Runs a user defined list of commands. Used recursively.
// line_count is how far into the file we are
// scope is the level of nested commands
// user_input is the string array containing the file
int max_line_count = user_input.size(); // Size of the file
while (line_count < max_line_count)
{
String current_line = user_input.get(line_count); // Gets the line we're
// dealing with
String tempstr = new String(); // Used for swapping strings
String conditional = new String(); // Holds the condition
// to be checked.
int repeat_num = 0; //The number of times to repeat. Initialized
//to a valid value for error checking
int next_line = 0; //Keeps the next line when dealing with scope
final int throw_error = max_line_count + 1; // Error return value
if (scope > 0) // Checking for valid scope
{
int i;
for (i = 0; i < scope; i++)
{
if (!(current_line.startsWith("\t")))
{
return line_count; // Returning due to out of scope
}
else
{
current_line = current_line.substring(1); // Removing the tab
}
}
if (current_line.startsWith("\t"))
{
System.out.println("ERROR: undefined scope on line "
+ (line_count + 1));
return throw_error;
}
}
/* Parsing the current line for recognizable Syntax */
if (current_line.matches("^repeat [0-9]{1,}$")) // Parsing repeat
{
tempstr = current_line.substring(7); // Grabbing the number
repeat_num = Integer.valueOf(tempstr);
tempstr = current_line.substring(0, 6); // Grabbing the repeat
current_line = tempstr;
}
if(current_line.matches("^if (not )?(gem|home|wall)$")) // Parsing if
{
conditional = current_line.substring(3); // Grabbing condition
tempstr = current_line.substring(0, 2); // Grabbing if
current_line = tempstr;
}
if (current_line.matches("^while (not )?(gem|home|wall)$")) // Parsing while
{
conditional = current_line.substring(6); // Grabbing condition
tempstr = current_line.substring(0, 5); // Grabbing while
current_line = tempstr;
}
/* End Parsing */
current_line = current_line.trim();
switch (current_line)
{ // Controls the logic for each valid command
// If input is something unexpected, it halts execution and
// prints an appropriate error
// Any time an error is encountered, max_line_count + 1 is
// returned, signaling to end execution
// Note: Since line_count is post-incremented, all uses of
// next_line are reduced by 1 to account for the post increment
case "left" :
choiceMade(2);
break;
case "right":
choiceMade(3);
break;
case "go" :
choiceMade(1);
break;
case "repeat":
if ((repeat_num < 1) || (repeat_num > 999))
{ // Checking if the repeat integer is too small or
// too large
System.out.println("ERROR: Repeat value not "
+ "in valid range (1-999) "
+ "on line " + (line_count + 1));
return throw_error;
}
for (int i = 0; i < repeat_num; i++)
{
next_line = doScript((line_count + 1),
(scope + 1), user_input);
if (next_line > max_line_count)
{ // If an error was returned
return throw_error;
}
}
line_count = next_line - 1;
break; // End "Repeat" case
case "if" :
if(conditional.isEmpty())
{ // Checking if the conditional is blank
System.out.println ("ERROR: Expected condition"
+ " after If on line "
+ (line_count + 1));
return throw_error;
}
// Finding the accompanying Else statement
tempstr = "else";
for (int i = 0; i < scope; i++)
{ // Forming tempstr based on our scope
tempstr = "\t" + tempstr;
}
int else_line = line_count + 1;//Line the Else is on
while (! (user_input.get(else_line).matches(tempstr)))
{ // While the next line isn't our Else
else_line++;
if (else_line >= max_line_count)
{ // If we can't find an accompanying Else
System.out.println("ERROR: Accompanying "
+ "Else statement not found for"
+ " If statement on line "
+ (line_count + 1));
return throw_error;
}
}
// End check for accompanying Else
if (handleCondition(conditional))
{ // Successful If case
next_line = doScript((line_count + 1),
(scope + 1), user_input);
}
else
{ // Successful Else case
next_line = doScript((else_line + 1),
(scope + 1), user_input);
}
line_count = next_line - 1;
break;
case "else" : // Only falls in this after a successful If
// This code is used to skip the unnecessary
// Else and all statements within it
tempstr = "\t";
do
{ // As long as the line exceeds our scope
line_count++;
if (line_count >= max_line_count)
{ // If we've reached the end of the file
return line_count;
}
} while (user_input.get(line_count).startsWith(tempstr, scope));
break; // End "If-Else" case
case "while" :
int infinite_counter = 0;
if(conditional.isEmpty())
{ // Checking if the conditional is blank
System.out.println ("ERROR: Expected condition"
+ " on line "
+ (line_count + 1));
return throw_error;
}
int while_line = line_count;
while (handleCondition(conditional))
{
infinite_counter++;
next_line = doScript((while_line + 1),
(scope + 1), user_input);
- if (infinite_counter > 100000)
+ if (infinite_counter > 10000)
{ // Assuming a loop that iterates over 100K
// times is an infinite loop
System.out.println("ERROR: Infinite loop "
+ "detected in While"
+ " on line "
+ (line_count + 1));
return throw_error;
}
if (next_line > max_line_count)
{ // If an error was returned in this loop
return throw_error;
}
line_count = next_line - 1;
}
break; // End "While" case
default:
System.out.println("ERROR: Unrecognized syntax:");
System.out.println(current_line);
System.out.println("on line " + (line_count + 1));
return throw_error;
}
++line_count;
}
return line_count;
}
public boolean handleCondition(String conditional)
{ // Function to check if a conditional is true or false
char direction = player.GetDirection();
int x = 0;
int y = 0;
switch(direction) // Getting the correct x and y values to use
{
case '^':
x = 0;
y = -1;
break;
case 'v':
x = 0;
y = 1;
break;
case '>':
x = 1;
y = 0;
break;
case '<':
x = -1;
y = 0;
break;
}
int newX = x + player.GetX(); // Getting x of next space
int newY = y + player.GetY(); // Getting y of next space
x = player.GetX(); // Current space x
y = player.GetY(); // Current space Y
switch (conditional)
{
case "not gem" :
if ( (player.isGemCollision(newX, newY, gems)) == -1)
{ return true; }
else
{ return false; }
case "gem" :
if ( (player.isGemCollision(newX, newY, gems)) != -1)
{ return true; }
else
{ return false; }
case "not wall":
if (!player.isWallCollision(newX, newY, walls))
{ return true; }
else
{ return false; }
case "wall" :
if (player.isWallCollision(newX, newY, walls))
{ return true; }
else
{ return false; }
case "not home":
if (!player.isHomeCollision(newX, newY, home))
{ return true; }
else
{ return false; }
case "home" :
if (player.isHomeCollision(newX, newY, home))
{ return true; }
else
{ return false; }
}
return false; // Should never get here
}
public void choiceMade(int choice)
{
//Get karels current direction
char direction = player.GetDirection();
if (choice == 1) //Attempt to move the player
{
switch(direction)
{
case '^':
handleMove(0,-1);
break;
case 'v':
handleMove(0, 1);
break;
case '>':
handleMove(1,0);
break;
case '<':
handleMove(-1,0);
break;
}
}
else if (choice == 2) //Turn the player left
{
switch(direction)
{
case '^':
player.SetDirection('<');
break;
case 'v':
player.SetDirection('>');
break;
case '>':
player.SetDirection('^');
break;
case '<':
player.SetDirection('v');
break;
}
}
else if (choice == 3)//turn the player right
{
switch(direction)
{
case '^':
player.SetDirection('>');
break;
case 'v':
player.SetDirection('<');
break;
case '>':
player.SetDirection('v');
break;
case '<':
player.SetDirection('^');
break;
}
}
else if (choice == 4) //Get multiple commands
{
actions();
}
//update the map with new position or direction icon
updateMap(player.GetX(),player.GetY(),player.GetDirection());
}
public void handleMove(int x, int y)
{
//Get where karel wants to move
int newX = x + player.GetX();
int newY = y + player.GetY();
if (player.isWallCollision(newX, newY, walls))
{
//collided with wall - do not move karel
}
else if (player.isHomeCollision(newX,newY,home))
{
//if karel is home and all gems are taken, move and end game
if(gems.isEmpty())
{
player.move(x,y);
isRunning = false;
System.out.println("You have won!");
}
}
else if (player.isGemCollision(newX, newY, gems) != -1)
{
//pick up the gem and move karel
gems.remove(player.isGemCollision(newX, newY, gems));
player.move(x, y);
}
else
{
//move karel
player.move(x, y);
}
}
}
}
| true | true | public int doScript(int line_count, int scope, List<String> user_input)
{ // Runs a user defined list of commands. Used recursively.
// line_count is how far into the file we are
// scope is the level of nested commands
// user_input is the string array containing the file
int max_line_count = user_input.size(); // Size of the file
while (line_count < max_line_count)
{
String current_line = user_input.get(line_count); // Gets the line we're
// dealing with
String tempstr = new String(); // Used for swapping strings
String conditional = new String(); // Holds the condition
// to be checked.
int repeat_num = 0; //The number of times to repeat. Initialized
//to a valid value for error checking
int next_line = 0; //Keeps the next line when dealing with scope
final int throw_error = max_line_count + 1; // Error return value
if (scope > 0) // Checking for valid scope
{
int i;
for (i = 0; i < scope; i++)
{
if (!(current_line.startsWith("\t")))
{
return line_count; // Returning due to out of scope
}
else
{
current_line = current_line.substring(1); // Removing the tab
}
}
if (current_line.startsWith("\t"))
{
System.out.println("ERROR: undefined scope on line "
+ (line_count + 1));
return throw_error;
}
}
/* Parsing the current line for recognizable Syntax */
if (current_line.matches("^repeat [0-9]{1,}$")) // Parsing repeat
{
tempstr = current_line.substring(7); // Grabbing the number
repeat_num = Integer.valueOf(tempstr);
tempstr = current_line.substring(0, 6); // Grabbing the repeat
current_line = tempstr;
}
if(current_line.matches("^if (not )?(gem|home|wall)$")) // Parsing if
{
conditional = current_line.substring(3); // Grabbing condition
tempstr = current_line.substring(0, 2); // Grabbing if
current_line = tempstr;
}
if (current_line.matches("^while (not )?(gem|home|wall)$")) // Parsing while
{
conditional = current_line.substring(6); // Grabbing condition
tempstr = current_line.substring(0, 5); // Grabbing while
current_line = tempstr;
}
/* End Parsing */
current_line = current_line.trim();
switch (current_line)
{ // Controls the logic for each valid command
// If input is something unexpected, it halts execution and
// prints an appropriate error
// Any time an error is encountered, max_line_count + 1 is
// returned, signaling to end execution
// Note: Since line_count is post-incremented, all uses of
// next_line are reduced by 1 to account for the post increment
case "left" :
choiceMade(2);
break;
case "right":
choiceMade(3);
break;
case "go" :
choiceMade(1);
break;
case "repeat":
if ((repeat_num < 1) || (repeat_num > 999))
{ // Checking if the repeat integer is too small or
// too large
System.out.println("ERROR: Repeat value not "
+ "in valid range (1-999) "
+ "on line " + (line_count + 1));
return throw_error;
}
for (int i = 0; i < repeat_num; i++)
{
next_line = doScript((line_count + 1),
(scope + 1), user_input);
if (next_line > max_line_count)
{ // If an error was returned
return throw_error;
}
}
line_count = next_line - 1;
break; // End "Repeat" case
case "if" :
if(conditional.isEmpty())
{ // Checking if the conditional is blank
System.out.println ("ERROR: Expected condition"
+ " after If on line "
+ (line_count + 1));
return throw_error;
}
// Finding the accompanying Else statement
tempstr = "else";
for (int i = 0; i < scope; i++)
{ // Forming tempstr based on our scope
tempstr = "\t" + tempstr;
}
int else_line = line_count + 1;//Line the Else is on
while (! (user_input.get(else_line).matches(tempstr)))
{ // While the next line isn't our Else
else_line++;
if (else_line >= max_line_count)
{ // If we can't find an accompanying Else
System.out.println("ERROR: Accompanying "
+ "Else statement not found for"
+ " If statement on line "
+ (line_count + 1));
return throw_error;
}
}
// End check for accompanying Else
if (handleCondition(conditional))
{ // Successful If case
next_line = doScript((line_count + 1),
(scope + 1), user_input);
}
else
{ // Successful Else case
next_line = doScript((else_line + 1),
(scope + 1), user_input);
}
line_count = next_line - 1;
break;
case "else" : // Only falls in this after a successful If
// This code is used to skip the unnecessary
// Else and all statements within it
tempstr = "\t";
do
{ // As long as the line exceeds our scope
line_count++;
if (line_count >= max_line_count)
{ // If we've reached the end of the file
return line_count;
}
} while (user_input.get(line_count).startsWith(tempstr, scope));
break; // End "If-Else" case
case "while" :
int infinite_counter = 0;
if(conditional.isEmpty())
{ // Checking if the conditional is blank
System.out.println ("ERROR: Expected condition"
+ " on line "
+ (line_count + 1));
return throw_error;
}
int while_line = line_count;
while (handleCondition(conditional))
{
infinite_counter++;
next_line = doScript((while_line + 1),
(scope + 1), user_input);
if (infinite_counter > 100000)
{ // Assuming a loop that iterates over 100K
// times is an infinite loop
System.out.println("ERROR: Infinite loop "
+ "detected in While"
+ " on line "
+ (line_count + 1));
return throw_error;
}
if (next_line > max_line_count)
{ // If an error was returned in this loop
return throw_error;
}
line_count = next_line - 1;
}
break; // End "While" case
default:
System.out.println("ERROR: Unrecognized syntax:");
System.out.println(current_line);
System.out.println("on line " + (line_count + 1));
return throw_error;
}
++line_count;
}
return line_count;
}
| public int doScript(int line_count, int scope, List<String> user_input)
{ // Runs a user defined list of commands. Used recursively.
// line_count is how far into the file we are
// scope is the level of nested commands
// user_input is the string array containing the file
int max_line_count = user_input.size(); // Size of the file
while (line_count < max_line_count)
{
String current_line = user_input.get(line_count); // Gets the line we're
// dealing with
String tempstr = new String(); // Used for swapping strings
String conditional = new String(); // Holds the condition
// to be checked.
int repeat_num = 0; //The number of times to repeat. Initialized
//to a valid value for error checking
int next_line = 0; //Keeps the next line when dealing with scope
final int throw_error = max_line_count + 1; // Error return value
if (scope > 0) // Checking for valid scope
{
int i;
for (i = 0; i < scope; i++)
{
if (!(current_line.startsWith("\t")))
{
return line_count; // Returning due to out of scope
}
else
{
current_line = current_line.substring(1); // Removing the tab
}
}
if (current_line.startsWith("\t"))
{
System.out.println("ERROR: undefined scope on line "
+ (line_count + 1));
return throw_error;
}
}
/* Parsing the current line for recognizable Syntax */
if (current_line.matches("^repeat [0-9]{1,}$")) // Parsing repeat
{
tempstr = current_line.substring(7); // Grabbing the number
repeat_num = Integer.valueOf(tempstr);
tempstr = current_line.substring(0, 6); // Grabbing the repeat
current_line = tempstr;
}
if(current_line.matches("^if (not )?(gem|home|wall)$")) // Parsing if
{
conditional = current_line.substring(3); // Grabbing condition
tempstr = current_line.substring(0, 2); // Grabbing if
current_line = tempstr;
}
if (current_line.matches("^while (not )?(gem|home|wall)$")) // Parsing while
{
conditional = current_line.substring(6); // Grabbing condition
tempstr = current_line.substring(0, 5); // Grabbing while
current_line = tempstr;
}
/* End Parsing */
current_line = current_line.trim();
switch (current_line)
{ // Controls the logic for each valid command
// If input is something unexpected, it halts execution and
// prints an appropriate error
// Any time an error is encountered, max_line_count + 1 is
// returned, signaling to end execution
// Note: Since line_count is post-incremented, all uses of
// next_line are reduced by 1 to account for the post increment
case "left" :
choiceMade(2);
break;
case "right":
choiceMade(3);
break;
case "go" :
choiceMade(1);
break;
case "repeat":
if ((repeat_num < 1) || (repeat_num > 999))
{ // Checking if the repeat integer is too small or
// too large
System.out.println("ERROR: Repeat value not "
+ "in valid range (1-999) "
+ "on line " + (line_count + 1));
return throw_error;
}
for (int i = 0; i < repeat_num; i++)
{
next_line = doScript((line_count + 1),
(scope + 1), user_input);
if (next_line > max_line_count)
{ // If an error was returned
return throw_error;
}
}
line_count = next_line - 1;
break; // End "Repeat" case
case "if" :
if(conditional.isEmpty())
{ // Checking if the conditional is blank
System.out.println ("ERROR: Expected condition"
+ " after If on line "
+ (line_count + 1));
return throw_error;
}
// Finding the accompanying Else statement
tempstr = "else";
for (int i = 0; i < scope; i++)
{ // Forming tempstr based on our scope
tempstr = "\t" + tempstr;
}
int else_line = line_count + 1;//Line the Else is on
while (! (user_input.get(else_line).matches(tempstr)))
{ // While the next line isn't our Else
else_line++;
if (else_line >= max_line_count)
{ // If we can't find an accompanying Else
System.out.println("ERROR: Accompanying "
+ "Else statement not found for"
+ " If statement on line "
+ (line_count + 1));
return throw_error;
}
}
// End check for accompanying Else
if (handleCondition(conditional))
{ // Successful If case
next_line = doScript((line_count + 1),
(scope + 1), user_input);
}
else
{ // Successful Else case
next_line = doScript((else_line + 1),
(scope + 1), user_input);
}
line_count = next_line - 1;
break;
case "else" : // Only falls in this after a successful If
// This code is used to skip the unnecessary
// Else and all statements within it
tempstr = "\t";
do
{ // As long as the line exceeds our scope
line_count++;
if (line_count >= max_line_count)
{ // If we've reached the end of the file
return line_count;
}
} while (user_input.get(line_count).startsWith(tempstr, scope));
break; // End "If-Else" case
case "while" :
int infinite_counter = 0;
if(conditional.isEmpty())
{ // Checking if the conditional is blank
System.out.println ("ERROR: Expected condition"
+ " on line "
+ (line_count + 1));
return throw_error;
}
int while_line = line_count;
while (handleCondition(conditional))
{
infinite_counter++;
next_line = doScript((while_line + 1),
(scope + 1), user_input);
if (infinite_counter > 10000)
{ // Assuming a loop that iterates over 100K
// times is an infinite loop
System.out.println("ERROR: Infinite loop "
+ "detected in While"
+ " on line "
+ (line_count + 1));
return throw_error;
}
if (next_line > max_line_count)
{ // If an error was returned in this loop
return throw_error;
}
line_count = next_line - 1;
}
break; // End "While" case
default:
System.out.println("ERROR: Unrecognized syntax:");
System.out.println(current_line);
System.out.println("on line " + (line_count + 1));
return throw_error;
}
++line_count;
}
return line_count;
}
|
diff --git a/stripes/src/net/sourceforge/stripes/tag/UseActionBeanTagExtraInfo.java b/stripes/src/net/sourceforge/stripes/tag/UseActionBeanTagExtraInfo.java
index 88f4899b..9a6b644d 100644
--- a/stripes/src/net/sourceforge/stripes/tag/UseActionBeanTagExtraInfo.java
+++ b/stripes/src/net/sourceforge/stripes/tag/UseActionBeanTagExtraInfo.java
@@ -1,81 +1,81 @@
/* Copyright 2008 Tim Fennell
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.stripes.tag;
import javax.servlet.jsp.tagext.TagExtraInfo;
import javax.servlet.jsp.tagext.VariableInfo;
import javax.servlet.jsp.tagext.TagData;
import javax.servlet.jsp.tagext.ValidationMessage;
import java.util.Collection;
import java.util.ArrayList;
/**
* Validates that the mutually exclusive attribute pairs of the tag are provided correctly
* and attempts to provide type information to the container for the bean assigned
* to the variable named by the {@code var} or {@code id} attribute. The latter can only be done
* when the {@code beanclass} attribute is used instead of the {@code binding} attribute
* because runtime information is needed to translate {@code binding} into a class name.
*
* @author tfenne
* @since Stripes 1.5
*/
public class UseActionBeanTagExtraInfo extends TagExtraInfo {
private static final VariableInfo[] NO_INFO = new VariableInfo[0];
/**
* Attempts to return type information so that the container can create a
* named variable for the action bean.
*/
@Override public VariableInfo[] getVariableInfo(final TagData tag) {
// We can only provide the type of 'var' if beanclass was used because
// if binding was used we need runtime information!
Object beanclass = tag.getAttribute("beanclass");
if (beanclass != null) {
String var = tag.getAttributeString("var");
- if (var == null) tag.getAttribute("id");
+ if (var == null) var = tag.getAttributeString("id");
// Make sure we have the class name, not the class
if (beanclass instanceof Class) beanclass = ((Class<?>) beanclass).getName();
// Return the variable info
return new VariableInfo[] { new VariableInfo(var, (String) beanclass, true, VariableInfo.AT_BEGIN) };
}
else {
return NO_INFO;
}
}
/**
* Checks to ensure that where the tag supports providing one of two attributes
* that one and only one is provided.
*/
@Override public ValidationMessage[] validate(final TagData tag) {
Collection<ValidationMessage> errors = new ArrayList<ValidationMessage>();
Object beanclass = tag.getAttribute("beanclass");
String binding = tag.getAttributeString("binding");
if (!(beanclass != null ^ binding != null)) {
errors.add(new ValidationMessage(tag.getId(), "Exactly one of 'beanclass' or 'binding' must be supplied."));
}
String var = tag.getAttributeString("var");
String id = tag.getAttributeString("id");
if (!(var != null ^ id != null)) {
errors.add(new ValidationMessage(tag.getId(), "Exactly one of 'var' or 'id' must be supplied."));
}
return errors.toArray(new ValidationMessage[errors.size()]);
}
}
| true | true | @Override public VariableInfo[] getVariableInfo(final TagData tag) {
// We can only provide the type of 'var' if beanclass was used because
// if binding was used we need runtime information!
Object beanclass = tag.getAttribute("beanclass");
if (beanclass != null) {
String var = tag.getAttributeString("var");
if (var == null) tag.getAttribute("id");
// Make sure we have the class name, not the class
if (beanclass instanceof Class) beanclass = ((Class<?>) beanclass).getName();
// Return the variable info
return new VariableInfo[] { new VariableInfo(var, (String) beanclass, true, VariableInfo.AT_BEGIN) };
}
else {
return NO_INFO;
}
}
| @Override public VariableInfo[] getVariableInfo(final TagData tag) {
// We can only provide the type of 'var' if beanclass was used because
// if binding was used we need runtime information!
Object beanclass = tag.getAttribute("beanclass");
if (beanclass != null) {
String var = tag.getAttributeString("var");
if (var == null) var = tag.getAttributeString("id");
// Make sure we have the class name, not the class
if (beanclass instanceof Class) beanclass = ((Class<?>) beanclass).getName();
// Return the variable info
return new VariableInfo[] { new VariableInfo(var, (String) beanclass, true, VariableInfo.AT_BEGIN) };
}
else {
return NO_INFO;
}
}
|
diff --git a/src/net/sf/freecol/client/gui/panel/ReportForeignAffairPanel.java b/src/net/sf/freecol/client/gui/panel/ReportForeignAffairPanel.java
index 6ec38b280..a36d9489d 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportForeignAffairPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportForeignAffairPanel.java
@@ -1,109 +1,109 @@
/**
* Copyright (C) 2002-2007 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.client.gui.panel;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Player.Stance;
import org.w3c.dom.Element;
import net.miginfocom.swing.MigLayout;
/**
* This panel displays the Foreign Affairs Report.
*/
public final class ReportForeignAffairPanel extends ReportPanel {
/**
* The constructor that will add the items to this panel.
*
* @param parent The parent of this panel.
*/
public ReportForeignAffairPanel(Canvas parent) {
super(parent, Messages.message("reportForeignAction.name"));
// Display Panel
reportPanel.removeAll();
reportPanel.setLayout(new GridLayout(0, 2));
Element report = getController().getForeignAffairsReport();
int number = report.getChildNodes().getLength();
for (int i = 0; i < number; i++) {
Element enemyElement = (Element) report.getChildNodes().item(i);
JPanel enemyPanel = new JPanel(new MigLayout("gapy 0", "[][]20[align right]0[]", ""));
enemyPanel.setOpaque(false);
Player enemy = (Player) getGame().getFreeColGameObject(enemyElement.getAttribute("player"));
JLabel coatLabel = new JLabel();
final ImageIcon coatOfArms = getLibrary().getCoatOfArmsImageIcon(enemy.getNation());
if (coatOfArms != null) {
coatLabel.setIcon(coatOfArms);
}
enemyPanel.add(coatLabel, "spany, aligny top");
enemyPanel.add(localizedLabel(enemy.getNationName()), "wrap 12");
enemyPanel.add(new JLabel(Messages.message("report.stance")), "newline");
Stance stance = Enum.valueOf(Stance.class, enemyElement.getAttribute("stance"));
enemyPanel.add(new JLabel(Messages.getStanceAsString(stance)));
enemyPanel.add(new JLabel(Messages.message("report.numberOfColonies")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("numberOfColonies")));
enemyPanel.add(new JLabel(Messages.message("report.numberOfUnits")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("numberOfUnits")));
enemyPanel.add(new JLabel(Messages.message("report.militaryStrength")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("militaryStrength")));
enemyPanel.add(new JLabel(Messages.message("report.navalStrength")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("navalStrength")));
enemyPanel.add(new JLabel(Messages.message("goldTitle")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("gold")));
if (enemyElement.hasAttribute("tax")) {
- enemyPanel.add(new JLabel(Messages.message("menuBar.colopedia.father")), "newline 8");
+ enemyPanel.add(new JLabel(Messages.message("report.continentalCongress.title")), "newline 8");
enemyPanel.add(new JLabel(enemyElement.getAttribute("foundingFathers")));
enemyPanel.add(new JLabel(Messages.message("tax")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("tax")));
enemyPanel.add(new JLabel("%"));
enemyPanel.add(new JLabel(Messages.message("report.sonsOfLiberty")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("SoL")));
enemyPanel.add(new JLabel("%"));
}
reportPanel.add(enemyPanel);
}
reportPanel.doLayout();
}
}
| true | true | public ReportForeignAffairPanel(Canvas parent) {
super(parent, Messages.message("reportForeignAction.name"));
// Display Panel
reportPanel.removeAll();
reportPanel.setLayout(new GridLayout(0, 2));
Element report = getController().getForeignAffairsReport();
int number = report.getChildNodes().getLength();
for (int i = 0; i < number; i++) {
Element enemyElement = (Element) report.getChildNodes().item(i);
JPanel enemyPanel = new JPanel(new MigLayout("gapy 0", "[][]20[align right]0[]", ""));
enemyPanel.setOpaque(false);
Player enemy = (Player) getGame().getFreeColGameObject(enemyElement.getAttribute("player"));
JLabel coatLabel = new JLabel();
final ImageIcon coatOfArms = getLibrary().getCoatOfArmsImageIcon(enemy.getNation());
if (coatOfArms != null) {
coatLabel.setIcon(coatOfArms);
}
enemyPanel.add(coatLabel, "spany, aligny top");
enemyPanel.add(localizedLabel(enemy.getNationName()), "wrap 12");
enemyPanel.add(new JLabel(Messages.message("report.stance")), "newline");
Stance stance = Enum.valueOf(Stance.class, enemyElement.getAttribute("stance"));
enemyPanel.add(new JLabel(Messages.getStanceAsString(stance)));
enemyPanel.add(new JLabel(Messages.message("report.numberOfColonies")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("numberOfColonies")));
enemyPanel.add(new JLabel(Messages.message("report.numberOfUnits")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("numberOfUnits")));
enemyPanel.add(new JLabel(Messages.message("report.militaryStrength")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("militaryStrength")));
enemyPanel.add(new JLabel(Messages.message("report.navalStrength")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("navalStrength")));
enemyPanel.add(new JLabel(Messages.message("goldTitle")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("gold")));
if (enemyElement.hasAttribute("tax")) {
enemyPanel.add(new JLabel(Messages.message("menuBar.colopedia.father")), "newline 8");
enemyPanel.add(new JLabel(enemyElement.getAttribute("foundingFathers")));
enemyPanel.add(new JLabel(Messages.message("tax")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("tax")));
enemyPanel.add(new JLabel("%"));
enemyPanel.add(new JLabel(Messages.message("report.sonsOfLiberty")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("SoL")));
enemyPanel.add(new JLabel("%"));
}
reportPanel.add(enemyPanel);
}
reportPanel.doLayout();
}
| public ReportForeignAffairPanel(Canvas parent) {
super(parent, Messages.message("reportForeignAction.name"));
// Display Panel
reportPanel.removeAll();
reportPanel.setLayout(new GridLayout(0, 2));
Element report = getController().getForeignAffairsReport();
int number = report.getChildNodes().getLength();
for (int i = 0; i < number; i++) {
Element enemyElement = (Element) report.getChildNodes().item(i);
JPanel enemyPanel = new JPanel(new MigLayout("gapy 0", "[][]20[align right]0[]", ""));
enemyPanel.setOpaque(false);
Player enemy = (Player) getGame().getFreeColGameObject(enemyElement.getAttribute("player"));
JLabel coatLabel = new JLabel();
final ImageIcon coatOfArms = getLibrary().getCoatOfArmsImageIcon(enemy.getNation());
if (coatOfArms != null) {
coatLabel.setIcon(coatOfArms);
}
enemyPanel.add(coatLabel, "spany, aligny top");
enemyPanel.add(localizedLabel(enemy.getNationName()), "wrap 12");
enemyPanel.add(new JLabel(Messages.message("report.stance")), "newline");
Stance stance = Enum.valueOf(Stance.class, enemyElement.getAttribute("stance"));
enemyPanel.add(new JLabel(Messages.getStanceAsString(stance)));
enemyPanel.add(new JLabel(Messages.message("report.numberOfColonies")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("numberOfColonies")));
enemyPanel.add(new JLabel(Messages.message("report.numberOfUnits")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("numberOfUnits")));
enemyPanel.add(new JLabel(Messages.message("report.militaryStrength")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("militaryStrength")));
enemyPanel.add(new JLabel(Messages.message("report.navalStrength")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("navalStrength")));
enemyPanel.add(new JLabel(Messages.message("goldTitle")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("gold")));
if (enemyElement.hasAttribute("tax")) {
enemyPanel.add(new JLabel(Messages.message("report.continentalCongress.title")), "newline 8");
enemyPanel.add(new JLabel(enemyElement.getAttribute("foundingFathers")));
enemyPanel.add(new JLabel(Messages.message("tax")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("tax")));
enemyPanel.add(new JLabel("%"));
enemyPanel.add(new JLabel(Messages.message("report.sonsOfLiberty")), "newline");
enemyPanel.add(new JLabel(enemyElement.getAttribute("SoL")));
enemyPanel.add(new JLabel("%"));
}
reportPanel.add(enemyPanel);
}
reportPanel.doLayout();
}
|
diff --git a/src/com/android/camera/FocusManager.java b/src/com/android/camera/FocusManager.java
index ca8d9405..2969da53 100644
--- a/src/com/android/camera/FocusManager.java
+++ b/src/com/android/camera/FocusManager.java
@@ -1,429 +1,428 @@
/*
* Copyright (C) 2011 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.camera;
import com.android.camera.ui.FaceView;
import com.android.camera.ui.FocusIndicator;
import com.android.camera.ui.FocusIndicatorView;
import android.graphics.Rect;
import android.hardware.Camera.Area;
import android.hardware.Camera.Parameters;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
// A class that handles everything about focus in still picture mode.
// This also handles the metering area because it is the same as focus area.
public class FocusManager {
private static final String TAG = "FocusManager";
private static final int RESET_TOUCH_FOCUS = 0;
private static final int FOCUS_BEEP_VOLUME = 100;
private static final int RESET_TOUCH_FOCUS_DELAY = 3000;
private int mState = STATE_IDLE;
private static final int STATE_IDLE = 0; // Focus is not active.
private static final int STATE_FOCUSING = 1; // Focus is in progress.
// Focus is in progress and the camera should take a picture after focus finishes.
private static final int STATE_FOCUSING_SNAP_ON_FINISH = 2;
private static final int STATE_SUCCESS = 3; // Focus finishes and succeeds.
private static final int STATE_FAIL = 4; // Focus finishes and fails.
private boolean mInitialized;
private boolean mFocusAreaSupported;
private ToneGenerator mFocusToneGenerator;
private View mFocusIndicatorRotateLayout;
private FocusIndicatorView mFocusIndicator;
private View mPreviewFrame;
private FaceView mFaceView;
private List<Area> mTapArea; // focus area in driver format
private String mFocusMode;
private String mDefaultFocusMode;
private String mOverrideFocusMode;
private Parameters mParameters;
private ComboPreferences mPreferences;
private Handler mHandler;
Listener mListener;
public interface Listener {
public void autoFocus();
public void cancelAutoFocus();
public boolean capture();
public void startFaceDetection();
public void stopFaceDetection();
public void setFocusParameters();
}
private class MainHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case RESET_TOUCH_FOCUS: {
cancelAutoFocus();
mListener.startFaceDetection();
break;
}
}
}
}
public FocusManager(ComboPreferences preferences, String defaultFocusMode) {
mPreferences = preferences;
mDefaultFocusMode = defaultFocusMode;
mHandler = new MainHandler();
}
// This has to be initialized before initialize().
public void initializeParameters(Parameters parameters) {
mParameters = parameters;
mFocusAreaSupported = (mParameters.getMaxNumFocusAreas() > 0
&& isSupported(Parameters.FOCUS_MODE_AUTO,
mParameters.getSupportedFocusModes()));
}
public void initialize(View focusIndicatorRotate, View previewFrame,
FaceView faceView, Listener listener) {
mFocusIndicatorRotateLayout = focusIndicatorRotate;
mFocusIndicator = (FocusIndicatorView) focusIndicatorRotate.findViewById(
R.id.focus_indicator);
mPreviewFrame = previewFrame;
mFaceView = faceView;
mListener = listener;
if (mParameters != null) {
mInitialized = true;
} else {
Log.e(TAG, "mParameters is not initialized.");
}
}
public void doFocus(boolean pressed) {
if (!mInitialized) return;
if (!(getFocusMode().equals(Parameters.FOCUS_MODE_INFINITY)
|| getFocusMode().equals(Parameters.FOCUS_MODE_FIXED)
|| getFocusMode().equals(Parameters.FOCUS_MODE_EDOF))) {
if (pressed) { // Focus key down.
// Do not focus if touch focus has been triggered.
if (mState != STATE_SUCCESS && mState != STATE_FAIL) {
autoFocus();
}
} else { // Focus key up.
// User releases half-pressed focus key.
if (mState == STATE_FOCUSING || mState == STATE_SUCCESS
|| mState == STATE_FAIL) {
cancelAutoFocus();
}
}
}
}
public void doSnap() {
if (!mInitialized) return;
// If the user has half-pressed the shutter and focus is completed, we
// can take the photo right away. If the focus mode is infinity, we can
// also take the photo.
if (getFocusMode().equals(Parameters.FOCUS_MODE_INFINITY)
|| getFocusMode().equals(Parameters.FOCUS_MODE_FIXED)
|| getFocusMode().equals(Parameters.FOCUS_MODE_EDOF)
|| (mState == STATE_SUCCESS
|| mState == STATE_FAIL)) {
capture();
} else if (mState == STATE_FOCUSING) {
// Half pressing the shutter (i.e. the focus button event) will
// already have requested AF for us, so just request capture on
// focus here.
mState = STATE_FOCUSING_SNAP_ON_FINISH;
} else if (mState == STATE_IDLE) {
// Focus key down event is dropped for some reasons. Just ignore.
}
}
public void onShutter() {
resetTouchFocus();
updateFocusUI();
}
public void onAutoFocus(boolean focused) {
if (mState == STATE_FOCUSING_SNAP_ON_FINISH) {
// Take the picture no matter focus succeeds or fails. No need
// to play the AF sound if we're about to play the shutter
// sound.
if (focused) {
mState = STATE_SUCCESS;
} else {
mState = STATE_FAIL;
}
updateFocusUI();
capture();
} else if (mState == STATE_FOCUSING) {
// This happens when (1) user is half-pressing the focus key or
// (2) touch focus is triggered. Play the focus tone. Do not
// take the picture now.
if (focused) {
mState = STATE_SUCCESS;
if (mFocusToneGenerator != null) {
mFocusToneGenerator.startTone(ToneGenerator.TONE_PROP_BEEP2);
}
} else {
mState = STATE_FAIL;
}
updateFocusUI();
// If this is triggered by touch focus, cancel focus after a
// while.
if (mTapArea != null) {
mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY);
}
} else if (mState == STATE_IDLE) {
// User has released the focus key before focus completes.
// Do nothing.
}
}
public boolean onTouch(MotionEvent e) {
if (!mInitialized || mState == STATE_FOCUSING_SNAP_ON_FINISH) return false;
// Let users be able to cancel previous touch focus.
- if ((mTapArea != null) && (e.getAction() == MotionEvent.ACTION_DOWN)
- && (mState == STATE_FOCUSING || mState == STATE_SUCCESS ||
- mState == STATE_FAIL)) {
+ if ((mTapArea != null) && (mState == STATE_FOCUSING ||
+ mState == STATE_SUCCESS || mState == STATE_FAIL)) {
cancelAutoFocus();
}
// Initialize variables.
int x = Math.round(e.getX());
int y = Math.round(e.getY());
int focusWidth = mFocusIndicatorRotateLayout.getWidth();
int focusHeight = mFocusIndicatorRotateLayout.getHeight();
int previewWidth = mPreviewFrame.getWidth();
int previewHeight = mPreviewFrame.getHeight();
if (mTapArea == null) {
mTapArea = new ArrayList<Area>();
mTapArea.add(new Area(new Rect(), 1));
}
// Convert the coordinates to driver format. The actual focus area is two times bigger than
// UI because a huge indicator looks strange.
int areaWidth = focusWidth * 2;
int areaHeight = focusHeight * 2;
int areaLeft = Util.clamp(x - areaWidth / 2, 0, previewWidth - areaWidth);
int areaTop = Util.clamp(y - areaHeight / 2, 0, previewHeight - areaHeight);
Rect rect = mTapArea.get(0).rect;
convertToFocusArea(areaLeft, areaTop, areaWidth, areaHeight, previewWidth, previewHeight,
mTapArea.get(0).rect);
// Use margin to set the focus indicator to the touched area.
RelativeLayout.LayoutParams p =
(RelativeLayout.LayoutParams) mFocusIndicatorRotateLayout.getLayoutParams();
int left = Util.clamp(x - focusWidth / 2, 0, previewWidth - focusWidth);
int top = Util.clamp(y - focusHeight / 2, 0, previewHeight - focusHeight);
p.setMargins(left, top, 0, 0);
// Disable "center" rule because we no longer want to put it in the center.
int[] rules = p.getRules();
rules[RelativeLayout.CENTER_IN_PARENT] = 0;
mFocusIndicatorRotateLayout.requestLayout();
// Stop face detection because we want to specify focus and metering area.
mListener.stopFaceDetection();
// Set the focus area and metering area.
mListener.setFocusParameters();
if (mFocusAreaSupported && (e.getAction() == MotionEvent.ACTION_UP)) {
autoFocus();
} else { // Just show the indicator in all other cases.
updateFocusUI();
// Reset the metering area in 3 seconds.
mHandler.removeMessages(RESET_TOUCH_FOCUS);
mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY);
}
return true;
}
public void onPreviewStarted() {
mState = STATE_IDLE;
}
public void onPreviewStopped() {
mState = STATE_IDLE;
resetTouchFocus();
// If auto focus was in progress, it would have been canceled.
updateFocusUI();
}
public void onCameraReleased() {
onPreviewStopped();
}
private void autoFocus() {
Log.v(TAG, "Start autofocus.");
mListener.autoFocus();
mState = STATE_FOCUSING;
// Pause the face view because the driver will keep sending face
// callbacks after the focus completes.
if (mFaceView != null) mFaceView.pause();
updateFocusUI();
mHandler.removeMessages(RESET_TOUCH_FOCUS);
}
private void cancelAutoFocus() {
Log.v(TAG, "Cancel autofocus.");
// Reset the tap area before calling mListener.cancelAutofocus.
// Otherwise, focus mode stays at auto and the tap area passed to the
// driver is not reset.
resetTouchFocus();
mListener.cancelAutoFocus();
if (mFaceView != null) mFaceView.resume();
mState = STATE_IDLE;
updateFocusUI();
mHandler.removeMessages(RESET_TOUCH_FOCUS);
}
private void capture() {
if (mListener.capture()) {
mState = STATE_IDLE;
mHandler.removeMessages(RESET_TOUCH_FOCUS);
}
}
public void initializeToneGenerator() {
// Initialize focus tone generator.
try {
mFocusToneGenerator = new ToneGenerator(
AudioManager.STREAM_SYSTEM, FOCUS_BEEP_VOLUME);
} catch (Throwable ex) {
Log.w(TAG, "Exception caught while creating tone generator: ", ex);
mFocusToneGenerator = null;
}
}
public void releaseToneGenerator() {
if (mFocusToneGenerator != null) {
mFocusToneGenerator.release();
mFocusToneGenerator = null;
}
}
// This can only be called after mParameters is initialized.
public String getFocusMode() {
if (mOverrideFocusMode != null) return mOverrideFocusMode;
if (mFocusAreaSupported && mTapArea != null) {
// Always use autofocus in tap-to-focus.
mFocusMode = Parameters.FOCUS_MODE_AUTO;
} else {
// The default is continuous autofocus.
mFocusMode = mPreferences.getString(
CameraSettings.KEY_FOCUS_MODE, mDefaultFocusMode);
}
if (!isSupported(mFocusMode, mParameters.getSupportedFocusModes())) {
// For some reasons, the driver does not support the current
// focus mode. Fall back to auto.
if (isSupported(Parameters.FOCUS_MODE_AUTO,
mParameters.getSupportedFocusModes())) {
mFocusMode = Parameters.FOCUS_MODE_AUTO;
} else {
mFocusMode = mParameters.getFocusMode();
}
}
return mFocusMode;
}
public List<Area> getTapArea() {
return mTapArea;
}
public void updateFocusUI() {
if (!mInitialized) return;
// Set the length of focus indicator according to preview frame size.
int len = Math.min(mPreviewFrame.getWidth(), mPreviewFrame.getHeight()) / 4;
ViewGroup.LayoutParams layout = mFocusIndicatorRotateLayout.getLayoutParams();
layout.width = len;
layout.height = len;
// Show only focus indicator or face indicator.
boolean faceExists = (mFaceView != null && mFaceView.faceExists());
FocusIndicator focusIndicator = (faceExists) ? mFaceView : mFocusIndicator;
if (mState == STATE_IDLE) {
if (mTapArea == null) {
focusIndicator.clear();
} else {
// Users touch on the preview and the indicator represents the
// metering area. Either focus area is not supported or
// autoFocus call is not required.
focusIndicator.showStart();
}
} else if (mState == STATE_FOCUSING || mState == STATE_FOCUSING_SNAP_ON_FINISH) {
focusIndicator.showStart();
} else if (mState == STATE_SUCCESS) {
focusIndicator.showSuccess();
} else if (mState == STATE_FAIL) {
focusIndicator.showFail();
}
}
public void resetTouchFocus() {
if (!mInitialized) return;
// Put focus indicator to the center.
RelativeLayout.LayoutParams p =
(RelativeLayout.LayoutParams) mFocusIndicatorRotateLayout.getLayoutParams();
int[] rules = p.getRules();
rules[RelativeLayout.CENTER_IN_PARENT] = RelativeLayout.TRUE;
p.setMargins(0, 0, 0, 0);
mTapArea = null;
}
// Convert the touch point to the focus area in driver format.
public static void convertToFocusArea(int left, int top, int focusWidth, int focusHeight,
int previewWidth, int previewHeight, Rect rect) {
rect.left = Math.round((float) left / previewWidth * 2000 - 1000);
rect.top = Math.round((float) top / previewHeight * 2000 - 1000);
rect.right = Math.round((float) (left + focusWidth) / previewWidth * 2000 - 1000);
rect.bottom = Math.round((float) (top + focusHeight) / previewHeight * 2000 - 1000);
}
public boolean isFocusCompleted() {
return mState == STATE_SUCCESS || mState == STATE_FAIL;
}
public void removeMessages() {
mHandler.removeMessages(RESET_TOUCH_FOCUS);
}
public void overrideFocusMode(String focusMode) {
mOverrideFocusMode = focusMode;
}
private static boolean isSupported(String value, List<String> supported) {
return supported == null ? false : supported.indexOf(value) >= 0;
}
}
| true | true | public boolean onTouch(MotionEvent e) {
if (!mInitialized || mState == STATE_FOCUSING_SNAP_ON_FINISH) return false;
// Let users be able to cancel previous touch focus.
if ((mTapArea != null) && (e.getAction() == MotionEvent.ACTION_DOWN)
&& (mState == STATE_FOCUSING || mState == STATE_SUCCESS ||
mState == STATE_FAIL)) {
cancelAutoFocus();
}
// Initialize variables.
int x = Math.round(e.getX());
int y = Math.round(e.getY());
int focusWidth = mFocusIndicatorRotateLayout.getWidth();
int focusHeight = mFocusIndicatorRotateLayout.getHeight();
int previewWidth = mPreviewFrame.getWidth();
int previewHeight = mPreviewFrame.getHeight();
if (mTapArea == null) {
mTapArea = new ArrayList<Area>();
mTapArea.add(new Area(new Rect(), 1));
}
// Convert the coordinates to driver format. The actual focus area is two times bigger than
// UI because a huge indicator looks strange.
int areaWidth = focusWidth * 2;
int areaHeight = focusHeight * 2;
int areaLeft = Util.clamp(x - areaWidth / 2, 0, previewWidth - areaWidth);
int areaTop = Util.clamp(y - areaHeight / 2, 0, previewHeight - areaHeight);
Rect rect = mTapArea.get(0).rect;
convertToFocusArea(areaLeft, areaTop, areaWidth, areaHeight, previewWidth, previewHeight,
mTapArea.get(0).rect);
// Use margin to set the focus indicator to the touched area.
RelativeLayout.LayoutParams p =
(RelativeLayout.LayoutParams) mFocusIndicatorRotateLayout.getLayoutParams();
int left = Util.clamp(x - focusWidth / 2, 0, previewWidth - focusWidth);
int top = Util.clamp(y - focusHeight / 2, 0, previewHeight - focusHeight);
p.setMargins(left, top, 0, 0);
// Disable "center" rule because we no longer want to put it in the center.
int[] rules = p.getRules();
rules[RelativeLayout.CENTER_IN_PARENT] = 0;
mFocusIndicatorRotateLayout.requestLayout();
// Stop face detection because we want to specify focus and metering area.
mListener.stopFaceDetection();
// Set the focus area and metering area.
mListener.setFocusParameters();
if (mFocusAreaSupported && (e.getAction() == MotionEvent.ACTION_UP)) {
autoFocus();
} else { // Just show the indicator in all other cases.
updateFocusUI();
// Reset the metering area in 3 seconds.
mHandler.removeMessages(RESET_TOUCH_FOCUS);
mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY);
}
return true;
}
| public boolean onTouch(MotionEvent e) {
if (!mInitialized || mState == STATE_FOCUSING_SNAP_ON_FINISH) return false;
// Let users be able to cancel previous touch focus.
if ((mTapArea != null) && (mState == STATE_FOCUSING ||
mState == STATE_SUCCESS || mState == STATE_FAIL)) {
cancelAutoFocus();
}
// Initialize variables.
int x = Math.round(e.getX());
int y = Math.round(e.getY());
int focusWidth = mFocusIndicatorRotateLayout.getWidth();
int focusHeight = mFocusIndicatorRotateLayout.getHeight();
int previewWidth = mPreviewFrame.getWidth();
int previewHeight = mPreviewFrame.getHeight();
if (mTapArea == null) {
mTapArea = new ArrayList<Area>();
mTapArea.add(new Area(new Rect(), 1));
}
// Convert the coordinates to driver format. The actual focus area is two times bigger than
// UI because a huge indicator looks strange.
int areaWidth = focusWidth * 2;
int areaHeight = focusHeight * 2;
int areaLeft = Util.clamp(x - areaWidth / 2, 0, previewWidth - areaWidth);
int areaTop = Util.clamp(y - areaHeight / 2, 0, previewHeight - areaHeight);
Rect rect = mTapArea.get(0).rect;
convertToFocusArea(areaLeft, areaTop, areaWidth, areaHeight, previewWidth, previewHeight,
mTapArea.get(0).rect);
// Use margin to set the focus indicator to the touched area.
RelativeLayout.LayoutParams p =
(RelativeLayout.LayoutParams) mFocusIndicatorRotateLayout.getLayoutParams();
int left = Util.clamp(x - focusWidth / 2, 0, previewWidth - focusWidth);
int top = Util.clamp(y - focusHeight / 2, 0, previewHeight - focusHeight);
p.setMargins(left, top, 0, 0);
// Disable "center" rule because we no longer want to put it in the center.
int[] rules = p.getRules();
rules[RelativeLayout.CENTER_IN_PARENT] = 0;
mFocusIndicatorRotateLayout.requestLayout();
// Stop face detection because we want to specify focus and metering area.
mListener.stopFaceDetection();
// Set the focus area and metering area.
mListener.setFocusParameters();
if (mFocusAreaSupported && (e.getAction() == MotionEvent.ACTION_UP)) {
autoFocus();
} else { // Just show the indicator in all other cases.
updateFocusUI();
// Reset the metering area in 3 seconds.
mHandler.removeMessages(RESET_TOUCH_FOCUS);
mHandler.sendEmptyMessageDelayed(RESET_TOUCH_FOCUS, RESET_TOUCH_FOCUS_DELAY);
}
return true;
}
|
diff --git a/src/main/java/org/uncertweb/ps/encoding/xml/OMEncoding.java b/src/main/java/org/uncertweb/ps/encoding/xml/OMEncoding.java
index 8a5aa62..c1739d6 100644
--- a/src/main/java/org/uncertweb/ps/encoding/xml/OMEncoding.java
+++ b/src/main/java/org/uncertweb/ps/encoding/xml/OMEncoding.java
@@ -1,108 +1,110 @@
package org.uncertweb.ps.encoding.xml;
import java.io.ByteArrayInputStream;
import java.util.Iterator;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.Namespace;
import org.jdom.filter.Filter;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.uncertweb.api.om.io.XBObservationEncoder;
import org.uncertweb.api.om.io.XBObservationParser;
import org.uncertweb.api.om.observation.AbstractObservation;
import org.uncertweb.api.om.observation.collections.IObservationCollection;
import org.uncertweb.ps.encoding.EncodeException;
import org.uncertweb.ps.encoding.ParseException;
public class OMEncoding extends AbstractXMLEncoding {
public boolean isSupportedClass(Class<?> classOf) {
for (Class<?> interf : classOf.getInterfaces()) {
if (interf.equals(IObservationCollection.class)) {
return true;
}
}
Class<?> superClass = classOf.getSuperclass();
if (superClass != null) {
return superClass.equals(AbstractObservation.class);
}
return false;
}
public Object parse(Element element, Class<?> classOf) throws ParseException {
try {
// FIXME: workaround for broken parser
Iterator<?> fois = element.getDescendants(new Filter() {
private static final long serialVersionUID = 1L;
public boolean matches(Object obj) {
if (obj instanceof Element) {
Element e = (Element)obj;
return e.getName().equals("featureOfInterest");
}
return false;
}
});
while (fois.hasNext()) {
Element e = (Element)fois.next();
- Element shape = e.getChild("SF_SpatialSamplingFeature", Namespace.getNamespace("http://www.opengis.net/samplingSpatial/2.0"))
- .getChild("shape", Namespace.getNamespace("http://www.opengis.net/samplingSpatial/2.0"));
- shape.removeAttribute("type");
+ Element ssf = e.getChild("SF_SpatialSamplingFeature", Namespace.getNamespace("http://www.opengis.net/samplingSpatial/2.0"));
+ if (ssf != null) {
+ Element shape = ssf.getChild("shape", Namespace.getNamespace("http://www.opengis.net/samplingSpatial/2.0"));
+ shape.removeAttribute("type");
+ }
}
// convert to string for external parsing
String om = new XMLOutputter().outputString(element);
XBObservationParser parser = new XBObservationParser();
if (element.getName().endsWith("Collection")) {
return parser.parseObservationCollection(om);
}
else {
return parser.parseObservation(om);
}
}
catch (Exception e) {
throw new ParseException("Couldn't parse O&M: " + e.getMessage(), e);
}
}
public Element encode(Object object) throws EncodeException {
try {
// generate random char
// to ensure we are encoding valid o&m, some instances will have multiple collections in one document
char idPrefix = (char) (System.nanoTime() % 26 + 'a');
// and encode
XBObservationEncoder encoder = new XBObservationEncoder();
String om;
if (object instanceof IObservationCollection) {
om = encoder.encodeObservationCollectionWithId((IObservationCollection) object, String.valueOf(idPrefix));
}
else {
om = encoder.encodeObservationWithId((AbstractObservation) object, String.valueOf(idPrefix));
}
Document document = new SAXBuilder().build(new ByteArrayInputStream(om.getBytes()));
return document.getRootElement();
}
catch (Exception e) {
throw new EncodeException("Couldn't encode O&M: " + e.getMessage(), e);
}
}
public String getNamespace() {
return "http://www.opengis.net/om/2.0";
}
public String getSchemaLocation() {
return "http://52north.org/schema/geostatistics/uncertweb/Profiles/OM/UncertWeb_OM.xsd";
}
public Include getIncludeForClass(Class<?> classOf) {
return new IncludeRef("OM_" + classOf.getSimpleName());
}
}
| true | true | public Object parse(Element element, Class<?> classOf) throws ParseException {
try {
// FIXME: workaround for broken parser
Iterator<?> fois = element.getDescendants(new Filter() {
private static final long serialVersionUID = 1L;
public boolean matches(Object obj) {
if (obj instanceof Element) {
Element e = (Element)obj;
return e.getName().equals("featureOfInterest");
}
return false;
}
});
while (fois.hasNext()) {
Element e = (Element)fois.next();
Element shape = e.getChild("SF_SpatialSamplingFeature", Namespace.getNamespace("http://www.opengis.net/samplingSpatial/2.0"))
.getChild("shape", Namespace.getNamespace("http://www.opengis.net/samplingSpatial/2.0"));
shape.removeAttribute("type");
}
// convert to string for external parsing
String om = new XMLOutputter().outputString(element);
XBObservationParser parser = new XBObservationParser();
if (element.getName().endsWith("Collection")) {
return parser.parseObservationCollection(om);
}
else {
return parser.parseObservation(om);
}
}
catch (Exception e) {
throw new ParseException("Couldn't parse O&M: " + e.getMessage(), e);
}
}
| public Object parse(Element element, Class<?> classOf) throws ParseException {
try {
// FIXME: workaround for broken parser
Iterator<?> fois = element.getDescendants(new Filter() {
private static final long serialVersionUID = 1L;
public boolean matches(Object obj) {
if (obj instanceof Element) {
Element e = (Element)obj;
return e.getName().equals("featureOfInterest");
}
return false;
}
});
while (fois.hasNext()) {
Element e = (Element)fois.next();
Element ssf = e.getChild("SF_SpatialSamplingFeature", Namespace.getNamespace("http://www.opengis.net/samplingSpatial/2.0"));
if (ssf != null) {
Element shape = ssf.getChild("shape", Namespace.getNamespace("http://www.opengis.net/samplingSpatial/2.0"));
shape.removeAttribute("type");
}
}
// convert to string for external parsing
String om = new XMLOutputter().outputString(element);
XBObservationParser parser = new XBObservationParser();
if (element.getName().endsWith("Collection")) {
return parser.parseObservationCollection(om);
}
else {
return parser.parseObservation(om);
}
}
catch (Exception e) {
throw new ParseException("Couldn't parse O&M: " + e.getMessage(), e);
}
}
|
diff --git a/LabBook/source/LObjDictionaryView.java b/LabBook/source/LObjDictionaryView.java
index acc02a9..6ea26db 100644
--- a/LabBook/source/LObjDictionaryView.java
+++ b/LabBook/source/LObjDictionaryView.java
@@ -1,811 +1,812 @@
package org.concord.LabBook;
import waba.ui.*;
import waba.fx.*;
import waba.io.*;
import org.concord.waba.extra.ui.*;
import org.concord.waba.extra.io.*;
import org.concord.waba.extra.event.*;
import org.concord.waba.extra.util.*;
// import org.concord.waba.WFTPClient.*;
/*
class ScreenWriter
implements LinePrinter
{
Graphics g = null;
FontMetrics fm = null;
int lineY = 10;
int lineX = 0;
ScreenWriter(Graphics g, FontMetrics fm)
{
this.g = g;
this.fm = fm;
}
public void print(String s)
{
g.drawText(s, lineX, lineY);
lineX += fm.getTextWidth(s);
// System.out.print(s);
}
public void println(String s)
{
g.drawText(s, lineX, lineY);
lineY += 10;
lineX = 0;
// System.out.println(s);
}
}
*/
public class LObjDictionaryView extends LabObjectView
implements ActionListener, DialogListener, ScrollListener, TreeControlListener
{
final static String beamCatNameOut = "CCBeamOutDB";
final static String beamCatNameIn = "CCBeamInDB";
public boolean viewFromExternal = false;
TreeControl treeControl;
TreeModel treeModel;
RelativeContainer me = new RelativeContainer();
int newIndex = 0;
LObjDictionary dict;
LabObjectPtr dictPtr;
// GridContainer buttons = null;
Container buttons = null;
Button doneButton = new Button("Done");
Button newButton = new Button("New");
Button openButton = new Button("Open");
Choice folderChoice;
Menu editMenu = new Menu("Edit");
boolean editStatus = false;
// String [] fileStrings = {"New..", "Open", "Rename..", "Send via FTP", "FTP settings..",
// "Import..", "Export..", "Delete"};
String [] fileStrings = {"New..", "Open", "Rename..", "Import..", "Export..", "Delete"};
String [] palmFileStrings = {"New..", "Open", "Beam selected", "Rename..", "Delete"};
CCScrollBar scrollBar;
waba.util.Vector pathTree;
/*
String username = "scytacki";
String ftpServer = "4.19.234.31";
String ftpDirectory = ".";
*/
public LObjDictionaryView(ViewContainer vc, LObjDictionary d,
LabBookSession session)
{
super(vc, (LabObject)d, session);
dict = d;
dictPtr = dict.getVisiblePtr();
add(me);
editMenu.add("Cut");
editMenu.add("Copy");
editMenu.add("Paste");
editMenu.add("Properties...");
editMenu.add("Toggle hidden");
editMenu.addActionListener(this);
}
public static String ROOT_TREE_NODE_NAME = "Home";
DictTreeNode rootNode = null;
public void layout(boolean sDone)
{
if(didLayout) return;
didLayout = true;
showDone = sDone;
rootNode = new DictTreeNode(dict.getVisiblePtr(), session, dict.lBook);
treeModel = new TreeModel(rootNode);
treeControl = new TreeControl(treeModel);
treeControl.addTreeControlListener(this);
treeControl.showRoot(false);
folderChoice = new Choice();
if(pathTree == null){
folderChoice.add(ROOT_TREE_NODE_NAME);
}else{
for(int n = 0; n < pathTree.getCount(); n++){
folderChoice.add(pathTree.get(n).toString());
}
}
me.add(folderChoice);
/*
if(showDone){
buttons = new GridContainer(6,1);
buttons.add(doneButton, 5, 0);
} else {
buttons = new GridContainer(5,1);
}
*/
buttons = new Container();
// if(showDone){
// buttons.add(doneButton);
// }
if(!viewFromExternal){
buttons.add(newButton);
buttons.add(openButton);
me.add(buttons);
}
if(scrollBar == null) scrollBar = new CCScrollBar(this);
me.add(scrollBar);
me.add(treeControl);
}
public void setRect(int x, int y, int width, int height)
{
super.setRect(x,y,width,height);
if(!didLayout) layout(false);
int wsb = (waba.sys.Vm.getPlatform().equals("WinCE"))?11:7;
me.setRect(0,0, width, height);
Debug.println("Setting grid size: " + width + " " + height);
if(viewFromExternal){
treeControl.setRect(1,1,width-wsb-2, height-2);
}else{
int buttWidth = 35;
int choiceWidth = 65;
treeControl.setRect(1,19,width-wsb-2, height-20);
folderChoice.setRect(1,1,choiceWidth,17);
int buttonsWidth = width - 2 - choiceWidth - 1;
buttons.setRect(choiceWidth+1,1,buttonsWidth,17);
if(showDone){
// doneButton.setRect(buttonsWidth - 3 - buttWidth ,1,buttWidth,15);
}
int xStart = 1;
newButton.setRect(xStart,1,buttWidth - 10,15);
xStart += (buttWidth + 2 - 10);
openButton.setRect(xStart,1,buttWidth,15);
}
if(scrollBar != null){
waba.fx.Rect rT = treeControl.getRect();
scrollBar.setRect(width-wsb,rT.y,wsb, rT.height);
}
redesignScrollBar();
}
Dialog newDialog = null;
public void onEvent(Event e)
{
if(e.type == ControlEvent.PRESSED){
TreeNode curNode;
TreeNode parent;
LabObject newObj;
if(e.target == newButton){
newSelected();
} else if(e.target == openButton){
openSelected();
} else if(e.target == doneButton){
if(container != null){
container.done(this);
}
}else if(e.target == folderChoice){
if(pathTree != null){
int sel = folderChoice.getSelectedIndex();
if(sel < 0 || sel > pathTree.getCount() - 1) return;
TreeNode node = (TreeNode)pathTree.get(sel);
int numbToDelete = sel;
if(numbToDelete > 0){
for(int i = 0; i < numbToDelete; i++){
pathTree.del(0);
}
}
LabObject obj = rootNode.getObj(node);
redefineFolderChoiceMenu();
if(obj instanceof LObjDictionary){
LObjDictionary d = (LObjDictionary)obj;
if(d.viewType == LObjDictionary.TREE_VIEW){
dict = d;
me.remove(treeControl);
treeModel = new TreeModel(new DictTreeNode(dict.getVisiblePtr(), session, dict.lBook));
treeControl = new TreeControl(treeModel);
treeControl.addTreeControlListener(this);
treeControl.showRoot(false);
me.add(treeControl);
waba.fx.Rect r = getRect();
setRect(r.x,r.y,r.width,r.height);
}else{
showPage(node,false);
}
}else if(node != null){
showPage(node, false);
}
}
}
} else if(e.type == TreeControl.DOUBLE_CLICK){
if(!viewFromExternal) openSelected();
} else if(e.type == ControlEvent.TIMER){
if(timer != null){
removeTimer(timer);
timer = null;
functionOnSelected(dialogFName, yieldID);
}
}
}
public void newSelected()
{
String [] buttons = {"Cancel", "Create"};
newDialog = Dialog.showInputDialog( this, "Create", "Create a new Object",
buttons,Dialog.CHOICE_INP_DIALOG,
getMainView().getCreateNames());
}
public void openSelected(boolean edit)
{
TreeNode curNode;
curNode = treeControl.getSelected();
if(curNode == null || curNode.toString().equals("..empty..")) return;
showPage(curNode, edit);
}
public void openSelected()
{
openSelected(false);
}
public LabObjectPtr insertAtSelected(LabObject obj)
{
TreeNode newNode = rootNode.getNode(obj);
LabObjectPtr newPtr = rootNode.getPtr(newNode);
insertAtSelected(newNode);
return newPtr;
/*
* We shouldn't need this anymore
*/
/* This is a little hack
* a commit just happened so this object
* is not "loaded" any more so if lBook.load()
* is called attempting to get this object it will
* create a second object. So we use a special
* case of reload to handle this.
* this sticks the object back into the "loaded"
* list so it won't get loaded twice
*/
// dict.lBook.reload(obj);
}
public void insertAtSelected(TreeNode node)
{
TreeNode curNode = treeControl.getSelected();
TreeNode parent = treeControl.getSelectedParent();
if(curNode == null){
treeModel.insertNodeInto(node, treeModel.getRoot(), treeModel.getRoot().getChildCount());
} else {
treeModel.insertNodeInto(node, parent, parent.getIndex(curNode)+1);
}
session.checkPoint();
}
public void redesignScrollBar(){
if(scrollBar == null) return;
if(treeControl == null) return;
int allLines = treeControl.getAllLines();
int maxVisLine = treeControl.maxVisLines();
scrollBar.setMinMaxValues(0,allLines - maxVisLine);
scrollBar.setAreaValues(allLines,maxVisLine);
scrollBar.setIncValue(1);
scrollBar.setPageIncValue((int)(0.8f*maxVisLine+0.5f));
scrollBar.setRValueRect();
if(allLines > maxVisLine){
scrollBar.setValue(treeControl.firstLine);
}else{
treeControl.firstLine = 0;
scrollBar.setValue(0);
}
scrollBar.repaint();
}
Dialog rnDialog = null;
public void dialogClosed(DialogEvent e)
{
String command = e.getActionCommand();
if(e.getSource() == newDialog){
if(command.equals("Create")){
String objType = (String)e.getInfo();
getMainView().createObj(objType, this);
}
} else if((rnDialog != null) && (e.getSource() == rnDialog)){
if(command.equals("Ok")){
// This is a bug
TreeNode selObj = treeControl.getSelected();
if(selObj == null){
dict.setName((String)e.getInfo());
return;
}
LabObject obj = rootNode.getObj(selObj);
if(obj != null){
obj.setName((String)e.getInfo());
obj.store();
session.checkPoint();
}
treeControl.reparse();
treeControl.repaint();
}
} else if(e.getSource() == propDialog){
// We should release the propDialog's session
// and checkpoint our's
session.checkPoint();
treeControl.reparse();
treeControl.repaint();
} else if(e.getSource() == confirmDialog){
if(command.equals(confirmYesStr)){
functionOnSelected(dialogFName, yieldID);
}
confirmDialog = null;
}
}
TreeNode clipboardNode = null;
public void actionPerformed(ActionEvent e)
{
String command;
Debug.println("Got action: " + e.getActionCommand());
functionOnSelected(e.getActionCommand(), 0);
}
String dialogFName = null;
Timer timer = null;
int yieldID = 0;
public void yield(String fName, int id)
{
yieldID = id;
dialogFName = fName;
timer = addTimer(50);
}
public void functionOnSelected(String fName, int yieldID)
{
TreeNode curNode = treeControl.getSelected();
DictTreeNode parent = (DictTreeNode)treeControl.getSelectedParent();
if(fName.equals("Cut")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
clipboardNode = curNode;
treeModel.removeNodeFromParent(curNode, parent);
} else if(fName.equals("Copy")){
if(yieldID == 0){
- showWaitDialog("Copying selected");
+ showWaitDialog("Please wait...| Copying object");
yield(fName, 1);
} else {
LabObjectPtr curPtr = DictTreeNode.getPtr(curNode);
LabObjectPtr copyPtr = dict.lBook.copy(curPtr);
if(copyPtr.objType == DefaultFactory.DICTIONARY){
clipboardNode = new DictTreeNode(copyPtr, session, dict.lBook);
} else {
clipboardNode = (TreeNode)copyPtr;
}
hideWaitDialog();
}
} else if(fName.equals("Paste")){
if(clipboardNode != null){
- insertAtSelected(clipboardNode);
+ insertAtSelected(clipboardNode);
+ clipboardNode = null;
}
} else if(fName.equals("Properties...")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
showProperties(rootNode.getObj(curNode));
} else if(fName.equals("Toggle hidden")){
LObjDictionary.globalHide = !LObjDictionary.globalHide;
if(container != null) container.reload(this);
} else if(fName.equals("New..")){
newSelected();
} else if(fName.equals("Open")){
openSelected();
} else if(fName.equals("Beam selected")){
Catalog ccBeam = new Catalog("CCBeam.cCCB.appl", Catalog.READ_ONLY);
if(ccBeam.isOpen()){
ccBeam.close();
} else {
// This user doesn't have CCBeam installed
// if we could we should try to intall it for them
Dialog.showMessageDialog(null, "Beam Error",
"You need to install CCBeam.",
"Ok", Dialog.INFO_DIALOG);
return;
}
if(parent == null) return;
if(yieldID == 0){
- showWaitDialog("Preparing to beam selected");
+ showWaitDialog("Please wait...| Preparing to beam object");
yield(fName, 1);
return;
} else {
LabObject obj = parent.getObj(curNode);
LabBookCatalog lbCat = new LabBookCatalog(beamCatNameOut);
dict.lBook.export(obj, lbCat);
lbCat.save();
lbCat.close();
hideWaitDialog();
waba.sys.Vm.exec("CCBeam", beamCatNameOut + "," +
beamCatNameIn + "," +
"CCProbe," +
obj.getName(), 0, true);
Catalog beamCat = new Catalog(beamCatNameOut + ".LaBk.DATA", Catalog.READ_WRITE);
if(beamCat.isOpen()){
beamCat.delete();
}
}
} else if(fName.equals("Receive")){
if(yieldID == 0){
- showWaitDialog("Importing received beam");
+ showWaitDialog("Please Wait...| Importing received beam");
yield(fName, 1);
return;
} else {
LabBookCatalog bmCat = new LabBookCatalog(beamCatNameIn);
LabObject newObj = dict.lBook.importDB(bmCat);
bmCat.close();
if(newObj != null){
TreeNode newNode = rootNode.getNode(newObj);
insertAtSelected(newNode);
}
Catalog beamCat = new Catalog(beamCatNameIn + ".LaBk.DATA", Catalog.READ_WRITE);
if(beamCat.isOpen()){
beamCat.delete();
}
hideWaitDialog();
return;
}
} else if(fName.equals("Rename..")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
String [] buttons = {"Cancel", "Ok"};
rnDialog = Dialog.showInputDialog(this, "Rename Object",
"New Name: ",
buttons,Dialog.EDIT_INP_DIALOG,null,
curNode.toString());
} else if(fName.equals("Send via FTP")){
/*
TreeNode curNode = treeControl.getSelected();
DictTreeNode parent = (DictTreeNode)treeControl.getSelectedParent();
if(parent == null) return;
LabObject obj = parent.getObj(curNode);
LabBookFile lbFile = new LabBookFile("LabObj-" + username);
dict.lBook.export(obj, lbFile);
lbFile.save();
lbFile.close();
ftpSend("LabObj-" + username);
File objFile = new File("LabObj-" + username, File.DONT_OPEN);
if(objFile.exists()){
objFile.delete();
}
*/
} else if(fName.equals("FTP settings..")){
} else if(fName.equals("Import..")){
FileDialog fd = FileDialog.getFileDialog(FileDialog.FILE_LOAD, null);
fd.show();
LabBookDB imDB = LObjDatabaseRef.getDatabase(fd.getFilePath());
if(imDB == null) return;
LabObject newObj = dict.lBook.importDB(imDB);
imDB.close();
if(newObj != null){
TreeNode newNode = rootNode.getNode(newObj);
insertAtSelected(newNode);
}
} else if(fName.equals("Export..")){
if(waba.sys.Vm.getPlatform().equals("PalmOS")){
dict.lBook.export(null, null);
} else {
if(parent == null) return;
LabObject obj = parent.getObj(curNode);
FileDialog fd = FileDialog.getFileDialog(FileDialog.FILE_SAVE, null);
String fileName = null;
if(fd != null){
fd.setFile(obj.getName());
fd.show();
fileName = fd.getFilePath();
} else {
fileName = "LabObj-export";
}
LabBookFile lbFile = new LabBookFile(fileName);
dict.lBook.export(obj, lbFile);
lbFile.save();
lbFile.close();
}
} else if(fName.equals("Delete")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
if(yieldID == 0){
showConfirmDialog("Are you sure you| " +
"want to delete:| " +
curNode.toString(),
"Delete");
this.dialogFName = fName;
this.yieldID = 1;
return;
} else {
treeModel.removeNodeFromParent(curNode, parent);
}
}
}
Dialog waitDialog = null;
Dialog confirmDialog = null;
String confirmYesStr = null;
public void showWaitDialog(String message)
{
waitDialog = Dialog.showMessageDialog(null, "Please Wait..",
message,
"Cancel", Dialog.INFO_DIALOG);
}
public void hideWaitDialog()
{
if(waitDialog != null) waitDialog.hide();
waitDialog = null;
}
public void showConfirmDialog(String message, String yesButton)
{
String [] buttons = {yesButton, "Cancel"};
confirmYesStr = yesButton;
confirmDialog = Dialog.showConfirmDialog(this, "Confirmation", message,
buttons, Dialog.QUEST_DIALOG);
}
public void checkForBeam()
{
// First see if we've got a bogus out db sitting around
Catalog beamCat = new Catalog(beamCatNameOut + ".LaBk.DATA", Catalog.READ_ONLY);
if(beamCat.isOpen()){
// cross our fingers and hope this helps.
// if we are here it means we crashed during export
// this means the LabBook was left open and so was
// this database. I don't know if deleting it will help
beamCat.delete();
}
beamCat = new Catalog(beamCatNameIn + ".LaBk.DATA", Catalog.READ_ONLY);
if(!beamCat.isOpen()){
return;
} else {
beamCat.close();
}
functionOnSelected("Receive", 0);
}
public void ftpSend(String fileName)
{
/*
ScreenWriter sWriter = new ScreenWriter(createGraphics(), getFontMetrics(MainWindow.defaultFont));
// connect and test supplying port no.
FTPClient ftp = new FTPClient(ftpServer, 21, sWriter);
byte [] testBuf = { (byte)'t', (byte)'e', (byte)'s', (byte)'t',
(byte)'\r', (byte)'\n',};
int errorCode = ftp.getError();
if(errorCode != 0){
sWriter.println("opening error num: " + errorCode);
return;
}
if(!ftp.login(username, password)){
sWriter.println("login error num: " + ftp.getError() +
" str: " + ftp.getErrorStr());
return;
}
// do binary by default
ftp.setType(FTPTransferType.BINARY);
// change dir
ftp.chdir(ftpDirectory);
// put a local file to remote host
ftp.put(fileName, fileName);
ftp.quit();
*/
}
public void showPage(TreeNode curNode, boolean edit)
{
LabObject obj = null;
obj = rootNode.getObj(curNode);
if(obj instanceof LObjDictionary &&
((LObjDictionary)obj).viewType == LObjDictionary.TREE_VIEW){
if(pathTree == null){
pathTree = new waba.util.Vector();
}
TreeLine selLine = treeControl.getSelectedLine();
int currIndex = 0;
if(pathTree.getCount() > 0) pathTree.del(0);
while(selLine != null){
TreeNode node = selLine.getNode();
if(node != null){
pathTree.insert(currIndex++,node);
}
selLine = selLine.getLineParent();
}
pathTree.insert(0,curNode);
redefineFolderChoiceMenu();
// folderChoice.repaint();
LObjDictionary d = (LObjDictionary)obj;
dict = d;
me.remove(treeControl);
treeModel = new TreeModel(new DictTreeNode(dict.getVisiblePtr(), session, dict.lBook));
treeControl = new TreeControl(treeModel);
treeControl.addTreeControlListener(this);
treeControl.showRoot(false);
me.add(treeControl);
waba.fx.Rect r = getRect();
setRect(r.x,r.y,r.width,r.height);
return;
}
DictTreeNode parent = (DictTreeNode)treeControl.getSelectedParent();
if(parent == null) parent = rootNode;
getMainView().showFullWindowObj(edit, parent.getDict(), rootNode.getPtr(curNode));
if(session != null) session.release();
}
public void updateWindow()
{
// release everything
session.release();
// reload our main dictionary
dict = (LObjDictionary)session.load(dictPtr);
setLabObject((LabObject)dict);
// we should refresh the display
treeControl.reparse();
treeControl.repaint();
}
public void redefineFolderChoiceMenu(){
if(folderChoice != null) me.remove(folderChoice);
folderChoice = new Choice();
if(pathTree == null){
folderChoice.add(ROOT_TREE_NODE_NAME);
}else{
for(int n = 0; n < pathTree.getCount(); n++){
folderChoice.add(pathTree.get(n).toString());
}
}
me.add(folderChoice);
}
ViewDialog propDialog = null;
public void showProperties(LabObject obj)
{
if(obj == null) return;
LabObjectView propView = obj.getPropertyView(null, session);
if(propView == null) return;
MainWindow mw = MainWindow.getMainWindow();
if(!(mw instanceof ExtraMainWindow)) return;
ViewDialog vDialog = new ViewDialog((ExtraMainWindow)mw, this, "Properties", propView);
propDialog = vDialog;
vDialog.setRect(0,0,150,150);
vDialog.show();
}
boolean addedMenus = false;
public void setShowMenus(boolean state)
{
if(!showMenus && state){
// our container wants us to show our menus
showMenus = true;
addMenus();
} else if(showMenus && !state){
// out container wants us to remove our menus
showMenus = false;
if(addedMenus) delMenus();
}
}
public void addMenus()
{
if(waba.sys.Vm.getPlatform().equals("PalmOS")){
fileStrings = palmFileStrings;
}
if(editMenu != null) getMainView().addMenu(this, editMenu);
getMainView().addFileMenuItems(fileStrings, this);
addedMenus = true;
}
public void delMenus()
{
if(editMenu != null) getMainView().delMenu(this,editMenu);
getMainView().removeFileMenuItems(fileStrings, this);
addedMenus = false;
}
public MainView getMainView()
{
if(container != null) return container.getMainView();
return null;
}
public void close()
{
if(scrollBar != null) scrollBar.close();
super.close();
// Commit ???
// Store ??
}
public void scrollValueChanged(ScrollEvent se){
if(se.target != scrollBar) return;
int value = se.getScrollValue();
treeControl.firstLine = value;
treeControl.repaint();
}
public void treeControlChanged(TreeControlEvent ev){
redesignScrollBar();
}
/*
public void onPaint(waba.fx.Graphics g){
if(g == null) return;
g.fillRect(0,0,width,height);
}
*/
}
| false | true | public void functionOnSelected(String fName, int yieldID)
{
TreeNode curNode = treeControl.getSelected();
DictTreeNode parent = (DictTreeNode)treeControl.getSelectedParent();
if(fName.equals("Cut")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
clipboardNode = curNode;
treeModel.removeNodeFromParent(curNode, parent);
} else if(fName.equals("Copy")){
if(yieldID == 0){
showWaitDialog("Copying selected");
yield(fName, 1);
} else {
LabObjectPtr curPtr = DictTreeNode.getPtr(curNode);
LabObjectPtr copyPtr = dict.lBook.copy(curPtr);
if(copyPtr.objType == DefaultFactory.DICTIONARY){
clipboardNode = new DictTreeNode(copyPtr, session, dict.lBook);
} else {
clipboardNode = (TreeNode)copyPtr;
}
hideWaitDialog();
}
} else if(fName.equals("Paste")){
if(clipboardNode != null){
insertAtSelected(clipboardNode);
}
} else if(fName.equals("Properties...")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
showProperties(rootNode.getObj(curNode));
} else if(fName.equals("Toggle hidden")){
LObjDictionary.globalHide = !LObjDictionary.globalHide;
if(container != null) container.reload(this);
} else if(fName.equals("New..")){
newSelected();
} else if(fName.equals("Open")){
openSelected();
} else if(fName.equals("Beam selected")){
Catalog ccBeam = new Catalog("CCBeam.cCCB.appl", Catalog.READ_ONLY);
if(ccBeam.isOpen()){
ccBeam.close();
} else {
// This user doesn't have CCBeam installed
// if we could we should try to intall it for them
Dialog.showMessageDialog(null, "Beam Error",
"You need to install CCBeam.",
"Ok", Dialog.INFO_DIALOG);
return;
}
if(parent == null) return;
if(yieldID == 0){
showWaitDialog("Preparing to beam selected");
yield(fName, 1);
return;
} else {
LabObject obj = parent.getObj(curNode);
LabBookCatalog lbCat = new LabBookCatalog(beamCatNameOut);
dict.lBook.export(obj, lbCat);
lbCat.save();
lbCat.close();
hideWaitDialog();
waba.sys.Vm.exec("CCBeam", beamCatNameOut + "," +
beamCatNameIn + "," +
"CCProbe," +
obj.getName(), 0, true);
Catalog beamCat = new Catalog(beamCatNameOut + ".LaBk.DATA", Catalog.READ_WRITE);
if(beamCat.isOpen()){
beamCat.delete();
}
}
} else if(fName.equals("Receive")){
if(yieldID == 0){
showWaitDialog("Importing received beam");
yield(fName, 1);
return;
} else {
LabBookCatalog bmCat = new LabBookCatalog(beamCatNameIn);
LabObject newObj = dict.lBook.importDB(bmCat);
bmCat.close();
if(newObj != null){
TreeNode newNode = rootNode.getNode(newObj);
insertAtSelected(newNode);
}
Catalog beamCat = new Catalog(beamCatNameIn + ".LaBk.DATA", Catalog.READ_WRITE);
if(beamCat.isOpen()){
beamCat.delete();
}
hideWaitDialog();
return;
}
} else if(fName.equals("Rename..")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
String [] buttons = {"Cancel", "Ok"};
rnDialog = Dialog.showInputDialog(this, "Rename Object",
"New Name: ",
buttons,Dialog.EDIT_INP_DIALOG,null,
curNode.toString());
} else if(fName.equals("Send via FTP")){
/*
TreeNode curNode = treeControl.getSelected();
DictTreeNode parent = (DictTreeNode)treeControl.getSelectedParent();
if(parent == null) return;
LabObject obj = parent.getObj(curNode);
LabBookFile lbFile = new LabBookFile("LabObj-" + username);
dict.lBook.export(obj, lbFile);
lbFile.save();
lbFile.close();
ftpSend("LabObj-" + username);
File objFile = new File("LabObj-" + username, File.DONT_OPEN);
if(objFile.exists()){
objFile.delete();
}
*/
} else if(fName.equals("FTP settings..")){
} else if(fName.equals("Import..")){
FileDialog fd = FileDialog.getFileDialog(FileDialog.FILE_LOAD, null);
fd.show();
LabBookDB imDB = LObjDatabaseRef.getDatabase(fd.getFilePath());
if(imDB == null) return;
LabObject newObj = dict.lBook.importDB(imDB);
imDB.close();
if(newObj != null){
TreeNode newNode = rootNode.getNode(newObj);
insertAtSelected(newNode);
}
} else if(fName.equals("Export..")){
if(waba.sys.Vm.getPlatform().equals("PalmOS")){
dict.lBook.export(null, null);
} else {
if(parent == null) return;
LabObject obj = parent.getObj(curNode);
FileDialog fd = FileDialog.getFileDialog(FileDialog.FILE_SAVE, null);
String fileName = null;
if(fd != null){
fd.setFile(obj.getName());
fd.show();
fileName = fd.getFilePath();
} else {
fileName = "LabObj-export";
}
LabBookFile lbFile = new LabBookFile(fileName);
dict.lBook.export(obj, lbFile);
lbFile.save();
lbFile.close();
}
} else if(fName.equals("Delete")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
if(yieldID == 0){
showConfirmDialog("Are you sure you| " +
"want to delete:| " +
curNode.toString(),
"Delete");
this.dialogFName = fName;
this.yieldID = 1;
return;
} else {
treeModel.removeNodeFromParent(curNode, parent);
}
}
}
| public void functionOnSelected(String fName, int yieldID)
{
TreeNode curNode = treeControl.getSelected();
DictTreeNode parent = (DictTreeNode)treeControl.getSelectedParent();
if(fName.equals("Cut")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
clipboardNode = curNode;
treeModel.removeNodeFromParent(curNode, parent);
} else if(fName.equals("Copy")){
if(yieldID == 0){
showWaitDialog("Please wait...| Copying object");
yield(fName, 1);
} else {
LabObjectPtr curPtr = DictTreeNode.getPtr(curNode);
LabObjectPtr copyPtr = dict.lBook.copy(curPtr);
if(copyPtr.objType == DefaultFactory.DICTIONARY){
clipboardNode = new DictTreeNode(copyPtr, session, dict.lBook);
} else {
clipboardNode = (TreeNode)copyPtr;
}
hideWaitDialog();
}
} else if(fName.equals("Paste")){
if(clipboardNode != null){
insertAtSelected(clipboardNode);
clipboardNode = null;
}
} else if(fName.equals("Properties...")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
showProperties(rootNode.getObj(curNode));
} else if(fName.equals("Toggle hidden")){
LObjDictionary.globalHide = !LObjDictionary.globalHide;
if(container != null) container.reload(this);
} else if(fName.equals("New..")){
newSelected();
} else if(fName.equals("Open")){
openSelected();
} else if(fName.equals("Beam selected")){
Catalog ccBeam = new Catalog("CCBeam.cCCB.appl", Catalog.READ_ONLY);
if(ccBeam.isOpen()){
ccBeam.close();
} else {
// This user doesn't have CCBeam installed
// if we could we should try to intall it for them
Dialog.showMessageDialog(null, "Beam Error",
"You need to install CCBeam.",
"Ok", Dialog.INFO_DIALOG);
return;
}
if(parent == null) return;
if(yieldID == 0){
showWaitDialog("Please wait...| Preparing to beam object");
yield(fName, 1);
return;
} else {
LabObject obj = parent.getObj(curNode);
LabBookCatalog lbCat = new LabBookCatalog(beamCatNameOut);
dict.lBook.export(obj, lbCat);
lbCat.save();
lbCat.close();
hideWaitDialog();
waba.sys.Vm.exec("CCBeam", beamCatNameOut + "," +
beamCatNameIn + "," +
"CCProbe," +
obj.getName(), 0, true);
Catalog beamCat = new Catalog(beamCatNameOut + ".LaBk.DATA", Catalog.READ_WRITE);
if(beamCat.isOpen()){
beamCat.delete();
}
}
} else if(fName.equals("Receive")){
if(yieldID == 0){
showWaitDialog("Please Wait...| Importing received beam");
yield(fName, 1);
return;
} else {
LabBookCatalog bmCat = new LabBookCatalog(beamCatNameIn);
LabObject newObj = dict.lBook.importDB(bmCat);
bmCat.close();
if(newObj != null){
TreeNode newNode = rootNode.getNode(newObj);
insertAtSelected(newNode);
}
Catalog beamCat = new Catalog(beamCatNameIn + ".LaBk.DATA", Catalog.READ_WRITE);
if(beamCat.isOpen()){
beamCat.delete();
}
hideWaitDialog();
return;
}
} else if(fName.equals("Rename..")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
String [] buttons = {"Cancel", "Ok"};
rnDialog = Dialog.showInputDialog(this, "Rename Object",
"New Name: ",
buttons,Dialog.EDIT_INP_DIALOG,null,
curNode.toString());
} else if(fName.equals("Send via FTP")){
/*
TreeNode curNode = treeControl.getSelected();
DictTreeNode parent = (DictTreeNode)treeControl.getSelectedParent();
if(parent == null) return;
LabObject obj = parent.getObj(curNode);
LabBookFile lbFile = new LabBookFile("LabObj-" + username);
dict.lBook.export(obj, lbFile);
lbFile.save();
lbFile.close();
ftpSend("LabObj-" + username);
File objFile = new File("LabObj-" + username, File.DONT_OPEN);
if(objFile.exists()){
objFile.delete();
}
*/
} else if(fName.equals("FTP settings..")){
} else if(fName.equals("Import..")){
FileDialog fd = FileDialog.getFileDialog(FileDialog.FILE_LOAD, null);
fd.show();
LabBookDB imDB = LObjDatabaseRef.getDatabase(fd.getFilePath());
if(imDB == null) return;
LabObject newObj = dict.lBook.importDB(imDB);
imDB.close();
if(newObj != null){
TreeNode newNode = rootNode.getNode(newObj);
insertAtSelected(newNode);
}
} else if(fName.equals("Export..")){
if(waba.sys.Vm.getPlatform().equals("PalmOS")){
dict.lBook.export(null, null);
} else {
if(parent == null) return;
LabObject obj = parent.getObj(curNode);
FileDialog fd = FileDialog.getFileDialog(FileDialog.FILE_SAVE, null);
String fileName = null;
if(fd != null){
fd.setFile(obj.getName());
fd.show();
fileName = fd.getFilePath();
} else {
fileName = "LabObj-export";
}
LabBookFile lbFile = new LabBookFile(fileName);
dict.lBook.export(obj, lbFile);
lbFile.save();
lbFile.close();
}
} else if(fName.equals("Delete")){
if(curNode == null || curNode.toString().equals("..empty..")) return;
if(yieldID == 0){
showConfirmDialog("Are you sure you| " +
"want to delete:| " +
curNode.toString(),
"Delete");
this.dialogFName = fName;
this.yieldID = 1;
return;
} else {
treeModel.removeNodeFromParent(curNode, parent);
}
}
}
|
diff --git a/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java b/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java
index d9e6d95..bd66af8 100644
--- a/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java
+++ b/common/com/github/soniex2/endermoney/trading/tileentity/TileEntityCreativeItemTrader.java
@@ -1,241 +1,240 @@
package com.github.soniex2.endermoney.trading.tileentity;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import com.github.soniex2.endermoney.core.EnderCoin;
import com.github.soniex2.endermoney.core.EnderMoney;
import com.github.soniex2.endermoney.trading.TradeError;
import com.github.soniex2.endermoney.trading.base.AbstractTraderTileEntity;
import com.github.soniex2.endermoney.trading.helper.item.ItemStackMapKey;
public class TileEntityCreativeItemTrader extends AbstractTraderTileEntity {
public TileEntityCreativeItemTrader() {
super(18);
}
public ItemStack[] getTradeInputs() {
ItemStack[] tradeInputs = new ItemStack[9];
for (int i = 0; i < 9; i++) {
tradeInputs[i] = ItemStack.copyItemStack(inv[i]);
}
return tradeInputs;
}
public ItemStack[] getTradeOutputs() {
ItemStack[] tradeOutputs = new ItemStack[9];
for (int i = 0; i < 9; i++) {
tradeOutputs[i] = ItemStack.copyItemStack(inv[i + 9]);
}
return tradeOutputs;
}
public boolean doTrade(IInventory fakeInv, int inputMinSlot, int inputMaxSlot,
int outputMinSlot, int outputMaxSlot) throws TradeError {
if (fakeInv == null) { throw new TradeError(1, "Invalid inventory",
new NullPointerException()); }
HashMap<ItemStackMapKey, Integer> tradeInputs = new HashMap<ItemStackMapKey, Integer>();
BigInteger moneyRequired = BigInteger.ZERO;
for (ItemStack i : getTradeInputs()) {
if (i == null) {
continue;
}
if (i.getItem() == EnderMoney.coin) {
moneyRequired = moneyRequired.add(BigInteger.valueOf(
EnderCoin.getValueFromItemStack(i)).multiply(
BigInteger.valueOf(i.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(i);
if (tradeInputs.containsKey(index)) {
tradeInputs.put(index, i.stackSize + tradeInputs.get(index));
} else {
tradeInputs.put(index, i.stackSize);
}
}
HashMap<ItemStackMapKey, Integer> tradeInput = new HashMap<ItemStackMapKey, Integer>();
BigInteger money = BigInteger.ZERO;
for (int i = inputMinSlot; i <= inputMaxSlot; i++) {
ItemStack is = fakeInv.getStackInSlot(i);
if (is == null) {
continue;
}
if (is.getItem() == EnderMoney.coin) {
- moneyRequired = moneyRequired.add(BigInteger.valueOf(
- EnderCoin.getValueFromItemStack(is)).multiply(
+ money = money.add(BigInteger.valueOf(EnderCoin.getValueFromItemStack(is)).multiply(
BigInteger.valueOf(is.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(is);
if (tradeInput.containsKey(index)) {
tradeInput.put(index, is.stackSize + tradeInput.get(index));
} else {
tradeInput.put(index, is.stackSize);
}
}
if (money.compareTo(moneyRequired) < 0) { return false; }
BigInteger newMoney = money.subtract(moneyRequired);
Set<Entry<ItemStackMapKey, Integer>> itemsRequired = tradeInputs.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> i = itemsRequired.iterator();
HashMap<ItemStackMapKey, Integer> newInput = new HashMap<ItemStackMapKey, Integer>();
while (i.hasNext()) {
Entry<ItemStackMapKey, Integer> entry = i.next();
ItemStackMapKey item = entry.getKey();
Integer amount = entry.getValue();
Integer available = tradeInput.get(item);
if (available == null) { return false; }
if (available < amount) { return false; }
if (available - amount == 0) {
continue;
}
newInput.put(item, available - amount);
}
if (newMoney.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
BigInteger[] coinCount = newMoney
.divideAndRemainder(BigInteger.valueOf(Long.MAX_VALUE));
int a = coinCount[0].intValue();
long b = coinCount[1].longValue();
ItemStack is1 = ((EnderCoin) EnderMoney.coin).getItemStack(Long.MAX_VALUE, 1);
ItemStack is2 = ((EnderCoin) EnderMoney.coin).getItemStack(b, 1);
ItemStackMapKey index1 = new ItemStackMapKey(is1);
ItemStackMapKey index2 = new ItemStackMapKey(is2);
newInput.put(index1, a);
newInput.put(index2, 1);
}
ItemStack[] tradeOutputs = getTradeOutputs();
// TODO put commented out code below somewhere else
/*
* int[] something = new int[tradeOutputs.length];
* int[][] lookAt = new int[][] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 },
* { -1, 0, 0 },
* { 0, -1, 0 }, { 0, 0, -1 } };
* for (int a = 0; a < lookAt.length; a++) {
* TileEntity tileEntity = this.worldObj.getBlockTileEntity(this.xCoord
* + lookAt[a][0],
* this.yCoord + lookAt[a][1], this.zCoord + lookAt[a][2]);
* if (tileEntity == null) continue;
* if (tileEntity instanceof IInventory) {
* IInventory iinv = (IInventory) tileEntity;
* for (int b = 0; b < iinv.getSizeInventory(); b++) {
* ItemStack is = iinv.getStackInSlot(b);
* if (is == null) continue;
* for (int c = 0; c < tradeOutputs.length; c++) {
* if (tradeOutputs[c] == null) continue;
* if (tradeOutputs[c].isItemEqual(is) &&
* ItemStack.areItemStackTagsEqual(tradeOutputs[c], is)) {
* something[c] += is.stackSize;
* }
* }
* }
* }
* }
*/
ItemStack[] oldOutInv = new ItemStack[outputMaxSlot - outputMinSlot + 1];
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
oldOutInv[a - outputMinSlot] = ItemStack.copyItemStack(fakeInv.getStackInSlot(a));
}
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
ItemStack is = fakeInv.getStackInSlot(a);
for (int b = 0; b < tradeOutputs.length; b++) {
if (is != null && tradeOutputs[b] != null && is.isItemEqual(tradeOutputs[b])
&& ItemStack.areItemStackTagsEqual(is, tradeOutputs[b])) {
if (is.isStackable()) {
if (is.stackSize < is.getMaxStackSize()) {
if (is.stackSize + tradeOutputs[b].stackSize > is.getMaxStackSize()) {
int newStackSize = tradeOutputs[b].stackSize + is.stackSize;
if (newStackSize > is.getMaxStackSize()) {
newStackSize = newStackSize - is.getMaxStackSize();
}
tradeOutputs[b].stackSize = newStackSize;
is.stackSize = is.getMaxStackSize();
} else {
is.stackSize = is.stackSize + tradeOutputs[b].stackSize;
tradeOutputs[b] = null;
}
}
}
} else if (is == null && tradeOutputs[b] != null) {
fakeInv.setInventorySlotContents(a, tradeOutputs[b]);
is = fakeInv.getStackInSlot(a);
tradeOutputs[b] = null;
}
if (tradeOutputs[b] != null && tradeOutputs[b].stackSize <= 0) {
tradeOutputs[b] = null;
}
}
}
for (int a = 0; a < tradeOutputs.length; a++) {
if (tradeOutputs[a] != null) {
for (int b = 0; b < oldOutInv.length; b++) {
fakeInv.setInventorySlotContents(b + outputMinSlot, oldOutInv[b]);
}
throw new TradeError(0, "Couldn't complete trade: Out of inventory space");
}
}
for (int _i = inputMinSlot; _i < inputMaxSlot; _i++) {
fakeInv.setInventorySlotContents(_i, null);
}
Set<Entry<ItemStackMapKey, Integer>> input = newInput.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> it = input.iterator();
int slot = inputMinSlot;
while (it.hasNext()) {
if (slot >= inputMaxSlot) { throw new TradeError(0,
"Couldn't complete trade: Out of inventory space"); }
if (fakeInv.getStackInSlot(slot) != null) {
slot++;
continue;
}
Entry<ItemStackMapKey, Integer> entry = it.next();
ItemStackMapKey itemData = entry.getKey();
ItemStack item = new ItemStack(itemData.itemID, 1, itemData.damage);
item.stackTagCompound = (NBTTagCompound) itemData.getTag();
Integer amount = entry.getValue();
if (amount == 0) { // shouldn't happen but who knows...
continue;
}
int stacks = amount / item.getMaxStackSize();
int extra = amount % item.getMaxStackSize();
ItemStack newItem = item.copy();
newItem.stackSize = item.getMaxStackSize();
for (int n = slot; n < slot + stacks; n++) {
fakeInv.setInventorySlotContents(n, newItem);
}
slot += stacks;
newItem = item.copy();
newItem.stackSize = extra;
fakeInv.setInventorySlotContents(slot, newItem);
slot++;
}
return true;
}
@Override
public String getInvName() {
return "endermoney.traders.item";
}
@Override
public boolean isInvNameLocalized() {
return false;
}
@Override
public void openChest() {
}
@Override
public void closeChest() {
}
}
| true | true | public boolean doTrade(IInventory fakeInv, int inputMinSlot, int inputMaxSlot,
int outputMinSlot, int outputMaxSlot) throws TradeError {
if (fakeInv == null) { throw new TradeError(1, "Invalid inventory",
new NullPointerException()); }
HashMap<ItemStackMapKey, Integer> tradeInputs = new HashMap<ItemStackMapKey, Integer>();
BigInteger moneyRequired = BigInteger.ZERO;
for (ItemStack i : getTradeInputs()) {
if (i == null) {
continue;
}
if (i.getItem() == EnderMoney.coin) {
moneyRequired = moneyRequired.add(BigInteger.valueOf(
EnderCoin.getValueFromItemStack(i)).multiply(
BigInteger.valueOf(i.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(i);
if (tradeInputs.containsKey(index)) {
tradeInputs.put(index, i.stackSize + tradeInputs.get(index));
} else {
tradeInputs.put(index, i.stackSize);
}
}
HashMap<ItemStackMapKey, Integer> tradeInput = new HashMap<ItemStackMapKey, Integer>();
BigInteger money = BigInteger.ZERO;
for (int i = inputMinSlot; i <= inputMaxSlot; i++) {
ItemStack is = fakeInv.getStackInSlot(i);
if (is == null) {
continue;
}
if (is.getItem() == EnderMoney.coin) {
moneyRequired = moneyRequired.add(BigInteger.valueOf(
EnderCoin.getValueFromItemStack(is)).multiply(
BigInteger.valueOf(is.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(is);
if (tradeInput.containsKey(index)) {
tradeInput.put(index, is.stackSize + tradeInput.get(index));
} else {
tradeInput.put(index, is.stackSize);
}
}
if (money.compareTo(moneyRequired) < 0) { return false; }
BigInteger newMoney = money.subtract(moneyRequired);
Set<Entry<ItemStackMapKey, Integer>> itemsRequired = tradeInputs.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> i = itemsRequired.iterator();
HashMap<ItemStackMapKey, Integer> newInput = new HashMap<ItemStackMapKey, Integer>();
while (i.hasNext()) {
Entry<ItemStackMapKey, Integer> entry = i.next();
ItemStackMapKey item = entry.getKey();
Integer amount = entry.getValue();
Integer available = tradeInput.get(item);
if (available == null) { return false; }
if (available < amount) { return false; }
if (available - amount == 0) {
continue;
}
newInput.put(item, available - amount);
}
if (newMoney.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
BigInteger[] coinCount = newMoney
.divideAndRemainder(BigInteger.valueOf(Long.MAX_VALUE));
int a = coinCount[0].intValue();
long b = coinCount[1].longValue();
ItemStack is1 = ((EnderCoin) EnderMoney.coin).getItemStack(Long.MAX_VALUE, 1);
ItemStack is2 = ((EnderCoin) EnderMoney.coin).getItemStack(b, 1);
ItemStackMapKey index1 = new ItemStackMapKey(is1);
ItemStackMapKey index2 = new ItemStackMapKey(is2);
newInput.put(index1, a);
newInput.put(index2, 1);
}
ItemStack[] tradeOutputs = getTradeOutputs();
// TODO put commented out code below somewhere else
/*
* int[] something = new int[tradeOutputs.length];
* int[][] lookAt = new int[][] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 },
* { -1, 0, 0 },
* { 0, -1, 0 }, { 0, 0, -1 } };
* for (int a = 0; a < lookAt.length; a++) {
* TileEntity tileEntity = this.worldObj.getBlockTileEntity(this.xCoord
* + lookAt[a][0],
* this.yCoord + lookAt[a][1], this.zCoord + lookAt[a][2]);
* if (tileEntity == null) continue;
* if (tileEntity instanceof IInventory) {
* IInventory iinv = (IInventory) tileEntity;
* for (int b = 0; b < iinv.getSizeInventory(); b++) {
* ItemStack is = iinv.getStackInSlot(b);
* if (is == null) continue;
* for (int c = 0; c < tradeOutputs.length; c++) {
* if (tradeOutputs[c] == null) continue;
* if (tradeOutputs[c].isItemEqual(is) &&
* ItemStack.areItemStackTagsEqual(tradeOutputs[c], is)) {
* something[c] += is.stackSize;
* }
* }
* }
* }
* }
*/
ItemStack[] oldOutInv = new ItemStack[outputMaxSlot - outputMinSlot + 1];
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
oldOutInv[a - outputMinSlot] = ItemStack.copyItemStack(fakeInv.getStackInSlot(a));
}
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
ItemStack is = fakeInv.getStackInSlot(a);
for (int b = 0; b < tradeOutputs.length; b++) {
if (is != null && tradeOutputs[b] != null && is.isItemEqual(tradeOutputs[b])
&& ItemStack.areItemStackTagsEqual(is, tradeOutputs[b])) {
if (is.isStackable()) {
if (is.stackSize < is.getMaxStackSize()) {
if (is.stackSize + tradeOutputs[b].stackSize > is.getMaxStackSize()) {
int newStackSize = tradeOutputs[b].stackSize + is.stackSize;
if (newStackSize > is.getMaxStackSize()) {
newStackSize = newStackSize - is.getMaxStackSize();
}
tradeOutputs[b].stackSize = newStackSize;
is.stackSize = is.getMaxStackSize();
} else {
is.stackSize = is.stackSize + tradeOutputs[b].stackSize;
tradeOutputs[b] = null;
}
}
}
} else if (is == null && tradeOutputs[b] != null) {
fakeInv.setInventorySlotContents(a, tradeOutputs[b]);
is = fakeInv.getStackInSlot(a);
tradeOutputs[b] = null;
}
if (tradeOutputs[b] != null && tradeOutputs[b].stackSize <= 0) {
tradeOutputs[b] = null;
}
}
}
for (int a = 0; a < tradeOutputs.length; a++) {
if (tradeOutputs[a] != null) {
for (int b = 0; b < oldOutInv.length; b++) {
fakeInv.setInventorySlotContents(b + outputMinSlot, oldOutInv[b]);
}
throw new TradeError(0, "Couldn't complete trade: Out of inventory space");
}
}
for (int _i = inputMinSlot; _i < inputMaxSlot; _i++) {
fakeInv.setInventorySlotContents(_i, null);
}
Set<Entry<ItemStackMapKey, Integer>> input = newInput.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> it = input.iterator();
int slot = inputMinSlot;
while (it.hasNext()) {
if (slot >= inputMaxSlot) { throw new TradeError(0,
"Couldn't complete trade: Out of inventory space"); }
if (fakeInv.getStackInSlot(slot) != null) {
slot++;
continue;
}
Entry<ItemStackMapKey, Integer> entry = it.next();
ItemStackMapKey itemData = entry.getKey();
ItemStack item = new ItemStack(itemData.itemID, 1, itemData.damage);
item.stackTagCompound = (NBTTagCompound) itemData.getTag();
Integer amount = entry.getValue();
if (amount == 0) { // shouldn't happen but who knows...
continue;
}
int stacks = amount / item.getMaxStackSize();
int extra = amount % item.getMaxStackSize();
ItemStack newItem = item.copy();
newItem.stackSize = item.getMaxStackSize();
for (int n = slot; n < slot + stacks; n++) {
fakeInv.setInventorySlotContents(n, newItem);
}
slot += stacks;
newItem = item.copy();
newItem.stackSize = extra;
fakeInv.setInventorySlotContents(slot, newItem);
slot++;
}
return true;
}
| public boolean doTrade(IInventory fakeInv, int inputMinSlot, int inputMaxSlot,
int outputMinSlot, int outputMaxSlot) throws TradeError {
if (fakeInv == null) { throw new TradeError(1, "Invalid inventory",
new NullPointerException()); }
HashMap<ItemStackMapKey, Integer> tradeInputs = new HashMap<ItemStackMapKey, Integer>();
BigInteger moneyRequired = BigInteger.ZERO;
for (ItemStack i : getTradeInputs()) {
if (i == null) {
continue;
}
if (i.getItem() == EnderMoney.coin) {
moneyRequired = moneyRequired.add(BigInteger.valueOf(
EnderCoin.getValueFromItemStack(i)).multiply(
BigInteger.valueOf(i.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(i);
if (tradeInputs.containsKey(index)) {
tradeInputs.put(index, i.stackSize + tradeInputs.get(index));
} else {
tradeInputs.put(index, i.stackSize);
}
}
HashMap<ItemStackMapKey, Integer> tradeInput = new HashMap<ItemStackMapKey, Integer>();
BigInteger money = BigInteger.ZERO;
for (int i = inputMinSlot; i <= inputMaxSlot; i++) {
ItemStack is = fakeInv.getStackInSlot(i);
if (is == null) {
continue;
}
if (is.getItem() == EnderMoney.coin) {
money = money.add(BigInteger.valueOf(EnderCoin.getValueFromItemStack(is)).multiply(
BigInteger.valueOf(is.stackSize)));
continue;
}
ItemStackMapKey index = new ItemStackMapKey(is);
if (tradeInput.containsKey(index)) {
tradeInput.put(index, is.stackSize + tradeInput.get(index));
} else {
tradeInput.put(index, is.stackSize);
}
}
if (money.compareTo(moneyRequired) < 0) { return false; }
BigInteger newMoney = money.subtract(moneyRequired);
Set<Entry<ItemStackMapKey, Integer>> itemsRequired = tradeInputs.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> i = itemsRequired.iterator();
HashMap<ItemStackMapKey, Integer> newInput = new HashMap<ItemStackMapKey, Integer>();
while (i.hasNext()) {
Entry<ItemStackMapKey, Integer> entry = i.next();
ItemStackMapKey item = entry.getKey();
Integer amount = entry.getValue();
Integer available = tradeInput.get(item);
if (available == null) { return false; }
if (available < amount) { return false; }
if (available - amount == 0) {
continue;
}
newInput.put(item, available - amount);
}
if (newMoney.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0) {
BigInteger[] coinCount = newMoney
.divideAndRemainder(BigInteger.valueOf(Long.MAX_VALUE));
int a = coinCount[0].intValue();
long b = coinCount[1].longValue();
ItemStack is1 = ((EnderCoin) EnderMoney.coin).getItemStack(Long.MAX_VALUE, 1);
ItemStack is2 = ((EnderCoin) EnderMoney.coin).getItemStack(b, 1);
ItemStackMapKey index1 = new ItemStackMapKey(is1);
ItemStackMapKey index2 = new ItemStackMapKey(is2);
newInput.put(index1, a);
newInput.put(index2, 1);
}
ItemStack[] tradeOutputs = getTradeOutputs();
// TODO put commented out code below somewhere else
/*
* int[] something = new int[tradeOutputs.length];
* int[][] lookAt = new int[][] { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 },
* { -1, 0, 0 },
* { 0, -1, 0 }, { 0, 0, -1 } };
* for (int a = 0; a < lookAt.length; a++) {
* TileEntity tileEntity = this.worldObj.getBlockTileEntity(this.xCoord
* + lookAt[a][0],
* this.yCoord + lookAt[a][1], this.zCoord + lookAt[a][2]);
* if (tileEntity == null) continue;
* if (tileEntity instanceof IInventory) {
* IInventory iinv = (IInventory) tileEntity;
* for (int b = 0; b < iinv.getSizeInventory(); b++) {
* ItemStack is = iinv.getStackInSlot(b);
* if (is == null) continue;
* for (int c = 0; c < tradeOutputs.length; c++) {
* if (tradeOutputs[c] == null) continue;
* if (tradeOutputs[c].isItemEqual(is) &&
* ItemStack.areItemStackTagsEqual(tradeOutputs[c], is)) {
* something[c] += is.stackSize;
* }
* }
* }
* }
* }
*/
ItemStack[] oldOutInv = new ItemStack[outputMaxSlot - outputMinSlot + 1];
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
oldOutInv[a - outputMinSlot] = ItemStack.copyItemStack(fakeInv.getStackInSlot(a));
}
for (int a = outputMinSlot; a <= outputMaxSlot; a++) {
ItemStack is = fakeInv.getStackInSlot(a);
for (int b = 0; b < tradeOutputs.length; b++) {
if (is != null && tradeOutputs[b] != null && is.isItemEqual(tradeOutputs[b])
&& ItemStack.areItemStackTagsEqual(is, tradeOutputs[b])) {
if (is.isStackable()) {
if (is.stackSize < is.getMaxStackSize()) {
if (is.stackSize + tradeOutputs[b].stackSize > is.getMaxStackSize()) {
int newStackSize = tradeOutputs[b].stackSize + is.stackSize;
if (newStackSize > is.getMaxStackSize()) {
newStackSize = newStackSize - is.getMaxStackSize();
}
tradeOutputs[b].stackSize = newStackSize;
is.stackSize = is.getMaxStackSize();
} else {
is.stackSize = is.stackSize + tradeOutputs[b].stackSize;
tradeOutputs[b] = null;
}
}
}
} else if (is == null && tradeOutputs[b] != null) {
fakeInv.setInventorySlotContents(a, tradeOutputs[b]);
is = fakeInv.getStackInSlot(a);
tradeOutputs[b] = null;
}
if (tradeOutputs[b] != null && tradeOutputs[b].stackSize <= 0) {
tradeOutputs[b] = null;
}
}
}
for (int a = 0; a < tradeOutputs.length; a++) {
if (tradeOutputs[a] != null) {
for (int b = 0; b < oldOutInv.length; b++) {
fakeInv.setInventorySlotContents(b + outputMinSlot, oldOutInv[b]);
}
throw new TradeError(0, "Couldn't complete trade: Out of inventory space");
}
}
for (int _i = inputMinSlot; _i < inputMaxSlot; _i++) {
fakeInv.setInventorySlotContents(_i, null);
}
Set<Entry<ItemStackMapKey, Integer>> input = newInput.entrySet();
Iterator<Entry<ItemStackMapKey, Integer>> it = input.iterator();
int slot = inputMinSlot;
while (it.hasNext()) {
if (slot >= inputMaxSlot) { throw new TradeError(0,
"Couldn't complete trade: Out of inventory space"); }
if (fakeInv.getStackInSlot(slot) != null) {
slot++;
continue;
}
Entry<ItemStackMapKey, Integer> entry = it.next();
ItemStackMapKey itemData = entry.getKey();
ItemStack item = new ItemStack(itemData.itemID, 1, itemData.damage);
item.stackTagCompound = (NBTTagCompound) itemData.getTag();
Integer amount = entry.getValue();
if (amount == 0) { // shouldn't happen but who knows...
continue;
}
int stacks = amount / item.getMaxStackSize();
int extra = amount % item.getMaxStackSize();
ItemStack newItem = item.copy();
newItem.stackSize = item.getMaxStackSize();
for (int n = slot; n < slot + stacks; n++) {
fakeInv.setInventorySlotContents(n, newItem);
}
slot += stacks;
newItem = item.copy();
newItem.stackSize = extra;
fakeInv.setInventorySlotContents(slot, newItem);
slot++;
}
return true;
}
|
diff --git a/pixmind/src/com/pix/mind/levels/Level16.java b/pixmind/src/com/pix/mind/levels/Level16.java
index e102f54..38e208c 100644
--- a/pixmind/src/com/pix/mind/levels/Level16.java
+++ b/pixmind/src/com/pix/mind/levels/Level16.java
@@ -1,161 +1,161 @@
package com.pix.mind.levels;
import com.badlogic.gdx.graphics.Color;
import com.pix.mind.PixMindGame;
import com.pix.mind.actors.PlatformActivatorActor;
import com.pix.mind.actors.StaticPlatformActor;
import com.pix.mind.world.PixMindWorldRenderer;
public class Level16 extends PixMindLevel {
public String levelTitle = "Level21";
PixMindGame game;
private static final int nActiveColors = 3;
public Level16(PixMindGame game) {
super(game, 950, 1235, 1350, 6, 13.5f, nActiveColors);
this.game = game;
levelNumber = 16;
}
@Override
public void show() {
super.show();
super.setNextLevel(game.getLevel17());
super.setActiveLevel(this);
// platform Actors and Activator Actors List
// Creating All Static Platforms
float platW = 1f;
float platH = 0.1f;
float deltaX = 0;
float deltaY = 0;
// Active colors
// Box2D platforms
// Add to platform list
// Black StaticPlatforms
// Coloured StaticPlatforms
// 1 = Blue
// 2 = red
// 3 = Green
// 4 = Orange
// from top to bottom
// upper 4 small
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 11 + deltaY, platW/4, platH, Color.ORANGE, false));
// upper 1 small
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 10 + deltaY, platW/4, platH, Color.BLUE, false));
// upper 2 small
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 9.2f + deltaY, platW/4, platH, Color.RED, false));
// middle big 3
box2D.getPlatformList().add(
- new StaticPlatformActor(box2D.getWorld(), 7f + deltaX, 9 + deltaY, platW * 2, platH, Color.GREEN, false));
+ new StaticPlatformActor(box2D.getWorld(), 6f + deltaX, 9 + deltaY, platW * 2, platH, Color.GREEN, false));
// middle small 1 first
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 8.2f + deltaY, platW/4, platH, Color.BLUE, false));
// middle small 1 first inside
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 7f + deltaY, platW/4, platH/2, Color.BLUE, false));
// middle medium 2
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 7f + deltaY, platW, platH, Color.RED, false));
// middle small 1 between 2 and 4
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 6f + deltaY, platW/4, platH, Color.BLUE, false));
// middle small 1 second inside
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5.8f + deltaX, 5f + deltaY, platW/4, platH/2, Color.BLUE, false));
// middle small 4 second cover
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 6.5f + deltaX, 5f + deltaY, platW, platH, Color.ORANGE, false));
// middle small 1 between 4 and 3
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 4f + deltaY, platW/4, platH, Color.BLUE, false));
// bottom medium 3
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 3f + deltaY, platW, platH, Color.GREEN, false));
// bottom small 1 inside
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 3f + deltaY, platW/4, platH/2, Color.BLUE, false));
// bottom small 1 middle
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 2f + deltaY, platW/4, platH, Color.BLUE, false));
// bottom small 1 middle
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 1f + deltaY, platW/4, platH, Color.BLUE, false));
// bottom thin 4 bottom
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 2.2f + deltaY, platW, platH/2, Color.ORANGE, false));
// bottom thin 2 bottom
// box2D.getPlatformList().add(
// new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 2f + deltaY, platW, platH/2, Color.RED, false));
// bottom thin 1 bottom
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 1.8f + deltaY, platW, platH/2, Color.BLUE, false));
// Creating All Activator
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 4f + deltaX, 12.0f + deltaY, Color.BLACK, true));
// 3 top
box2D.getActivatorList().add(
- new PlatformActivatorActor(box2D.getWorld(), 5f + deltaX, 12.0f + deltaY, Color.GREEN, false));
+ new PlatformActivatorActor(box2D.getWorld(), 6f + deltaX, 12.0f + deltaY, Color.GREEN, false));
// 2 upper
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 3f + deltaX, 9.2f + deltaY, Color.RED, false));
// 4 middle
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 6f + deltaX, 6f + deltaY, Color.ORANGE, false));
// 3 middle left
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 4f + deltaX, 4.0f + deltaY, Color.GREEN, false));
// 1 bottom
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 4f + deltaX, 1.5f + deltaY, Color.BLUE, false));
// Add activators to Stage
for (PlatformActivatorActor Sskin : box2D.getActivatorList()) {
scene2D.getGroupStage().addActor(Sskin);
}
// Add platforms to Stage
for (StaticPlatformActor Sskin : box2D.getPlatformList()) {
scene2D.getGroupStage().addActor(Sskin);
}
// Rendering the game
worldRenderer = new PixMindWorldRenderer(scene2D, box2D, gui);
}
@Override
public void render(float delta) {
super.render(delta);
}
@Override
public void resize(int width, int height) {
super.resize(width, height);
}
@Override
public void hide() {
super.hide();
}
@Override
public void pause() {
super.pause();
}
@Override
public void resume() {
super.resume();
}
@Override
public void dispose() {
}
}
| false | true | public void show() {
super.show();
super.setNextLevel(game.getLevel17());
super.setActiveLevel(this);
// platform Actors and Activator Actors List
// Creating All Static Platforms
float platW = 1f;
float platH = 0.1f;
float deltaX = 0;
float deltaY = 0;
// Active colors
// Box2D platforms
// Add to platform list
// Black StaticPlatforms
// Coloured StaticPlatforms
// 1 = Blue
// 2 = red
// 3 = Green
// 4 = Orange
// from top to bottom
// upper 4 small
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 11 + deltaY, platW/4, platH, Color.ORANGE, false));
// upper 1 small
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 10 + deltaY, platW/4, platH, Color.BLUE, false));
// upper 2 small
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 9.2f + deltaY, platW/4, platH, Color.RED, false));
// middle big 3
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 7f + deltaX, 9 + deltaY, platW * 2, platH, Color.GREEN, false));
// middle small 1 first
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 8.2f + deltaY, platW/4, platH, Color.BLUE, false));
// middle small 1 first inside
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 7f + deltaY, platW/4, platH/2, Color.BLUE, false));
// middle medium 2
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 7f + deltaY, platW, platH, Color.RED, false));
// middle small 1 between 2 and 4
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 6f + deltaY, platW/4, platH, Color.BLUE, false));
// middle small 1 second inside
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5.8f + deltaX, 5f + deltaY, platW/4, platH/2, Color.BLUE, false));
// middle small 4 second cover
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 6.5f + deltaX, 5f + deltaY, platW, platH, Color.ORANGE, false));
// middle small 1 between 4 and 3
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 4f + deltaY, platW/4, platH, Color.BLUE, false));
// bottom medium 3
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 3f + deltaY, platW, platH, Color.GREEN, false));
// bottom small 1 inside
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 3f + deltaY, platW/4, platH/2, Color.BLUE, false));
// bottom small 1 middle
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 2f + deltaY, platW/4, platH, Color.BLUE, false));
// bottom small 1 middle
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 1f + deltaY, platW/4, platH, Color.BLUE, false));
// bottom thin 4 bottom
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 2.2f + deltaY, platW, platH/2, Color.ORANGE, false));
// bottom thin 2 bottom
// box2D.getPlatformList().add(
// new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 2f + deltaY, platW, platH/2, Color.RED, false));
// bottom thin 1 bottom
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 1.8f + deltaY, platW, platH/2, Color.BLUE, false));
// Creating All Activator
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 4f + deltaX, 12.0f + deltaY, Color.BLACK, true));
// 3 top
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 5f + deltaX, 12.0f + deltaY, Color.GREEN, false));
// 2 upper
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 3f + deltaX, 9.2f + deltaY, Color.RED, false));
// 4 middle
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 6f + deltaX, 6f + deltaY, Color.ORANGE, false));
// 3 middle left
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 4f + deltaX, 4.0f + deltaY, Color.GREEN, false));
// 1 bottom
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 4f + deltaX, 1.5f + deltaY, Color.BLUE, false));
// Add activators to Stage
for (PlatformActivatorActor Sskin : box2D.getActivatorList()) {
scene2D.getGroupStage().addActor(Sskin);
}
// Add platforms to Stage
for (StaticPlatformActor Sskin : box2D.getPlatformList()) {
scene2D.getGroupStage().addActor(Sskin);
}
// Rendering the game
worldRenderer = new PixMindWorldRenderer(scene2D, box2D, gui);
}
| public void show() {
super.show();
super.setNextLevel(game.getLevel17());
super.setActiveLevel(this);
// platform Actors and Activator Actors List
// Creating All Static Platforms
float platW = 1f;
float platH = 0.1f;
float deltaX = 0;
float deltaY = 0;
// Active colors
// Box2D platforms
// Add to platform list
// Black StaticPlatforms
// Coloured StaticPlatforms
// 1 = Blue
// 2 = red
// 3 = Green
// 4 = Orange
// from top to bottom
// upper 4 small
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 11 + deltaY, platW/4, platH, Color.ORANGE, false));
// upper 1 small
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 10 + deltaY, platW/4, platH, Color.BLUE, false));
// upper 2 small
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 9.2f + deltaY, platW/4, platH, Color.RED, false));
// middle big 3
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 6f + deltaX, 9 + deltaY, platW * 2, platH, Color.GREEN, false));
// middle small 1 first
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 8.2f + deltaY, platW/4, platH, Color.BLUE, false));
// middle small 1 first inside
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 7f + deltaY, platW/4, platH/2, Color.BLUE, false));
// middle medium 2
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 7f + deltaY, platW, platH, Color.RED, false));
// middle small 1 between 2 and 4
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 6f + deltaY, platW/4, platH, Color.BLUE, false));
// middle small 1 second inside
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5.8f + deltaX, 5f + deltaY, platW/4, platH/2, Color.BLUE, false));
// middle small 4 second cover
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 6.5f + deltaX, 5f + deltaY, platW, platH, Color.ORANGE, false));
// middle small 1 between 4 and 3
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 4f + deltaY, platW/4, platH, Color.BLUE, false));
// bottom medium 3
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 3f + deltaY, platW, platH, Color.GREEN, false));
// bottom small 1 inside
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 3f + deltaY, platW/4, platH/2, Color.BLUE, false));
// bottom small 1 middle
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 5f + deltaX, 2f + deltaY, platW/4, platH, Color.BLUE, false));
// bottom small 1 middle
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 4f + deltaX, 1f + deltaY, platW/4, platH, Color.BLUE, false));
// bottom thin 4 bottom
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 2.2f + deltaY, platW, platH/2, Color.ORANGE, false));
// bottom thin 2 bottom
// box2D.getPlatformList().add(
// new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 2f + deltaY, platW, platH/2, Color.RED, false));
// bottom thin 1 bottom
box2D.getPlatformList().add(
new StaticPlatformActor(box2D.getWorld(), 3.5f + deltaX, 1.8f + deltaY, platW, platH/2, Color.BLUE, false));
// Creating All Activator
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 4f + deltaX, 12.0f + deltaY, Color.BLACK, true));
// 3 top
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 6f + deltaX, 12.0f + deltaY, Color.GREEN, false));
// 2 upper
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 3f + deltaX, 9.2f + deltaY, Color.RED, false));
// 4 middle
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 6f + deltaX, 6f + deltaY, Color.ORANGE, false));
// 3 middle left
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 4f + deltaX, 4.0f + deltaY, Color.GREEN, false));
// 1 bottom
box2D.getActivatorList().add(
new PlatformActivatorActor(box2D.getWorld(), 4f + deltaX, 1.5f + deltaY, Color.BLUE, false));
// Add activators to Stage
for (PlatformActivatorActor Sskin : box2D.getActivatorList()) {
scene2D.getGroupStage().addActor(Sskin);
}
// Add platforms to Stage
for (StaticPlatformActor Sskin : box2D.getPlatformList()) {
scene2D.getGroupStage().addActor(Sskin);
}
// Rendering the game
worldRenderer = new PixMindWorldRenderer(scene2D, box2D, gui);
}
|
diff --git a/src/java/net/niconomicon/tile/source/app/sharing/server/jetty/JettyImageServerServlet.java b/src/java/net/niconomicon/tile/source/app/sharing/server/jetty/JettyImageServerServlet.java
index 8443a53..2d79196 100644
--- a/src/java/net/niconomicon/tile/source/app/sharing/server/jetty/JettyImageServerServlet.java
+++ b/src/java/net/niconomicon/tile/source/app/sharing/server/jetty/JettyImageServerServlet.java
@@ -1,164 +1,164 @@
/**
*
*/
package net.niconomicon.tile.source.app.sharing.server.jetty;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.niconomicon.tile.source.app.Ref;
/**
* @author niko
*
*/
public class JettyImageServerServlet extends HttpServlet {
Map<String, String> imaginaryMap;
Set<String> knownImages;
File css;
public JettyImageServerServlet() {
knownImages = new HashSet<String>();
String cssLocation = "net/niconomicon/tile/source/app/sharing/server/jetty/index.css";
URL url = this.getClass().getClassLoader().getResource(cssLocation);
css = new File(url.getFile());
}
public void addImages(Collection<String> documents) {
knownImages.clear();
knownImages.addAll(documents);
Map<String, String> refs = Ref.generateIndexFromFileNames(knownImages);
// for caching
Ref.extractThumbsAndMiniToTmpFile(refs);
imaginaryMap = refs;
}
/* (non-Javadoc)
* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String request = req.getRequestURI();
System.out.println("URI : " + request);
if (request.equals("/" + Ref.sharing_jsonRef) || request.equals(Ref.URI_jsonRef)) {
String k = "/" + Ref.sharing_jsonRef;
- System.out.println("should be returning the Displayable Feed [" + imaginaryMap.get(request).length() + "]");
+ //System.out.println("should be returning the Displayable Feed [" + imaginaryMap.get(k).length() + "]");
try {
sendString(imaginaryMap.get(k), resp);
return;
} catch (Exception ex) {
resp.sendError(500, "The server encountered an error while trying to send the content for request [" + request + "]");
return;
}
}
if (request.compareTo("/index.css") == 0) {
- System.out.println("should be returning the css.");
+ //System.out.println("should be returning the css.");
try {
sendCSS(resp);
return;
} catch (Exception ex) {
resp.sendError(500, "The server encountered an error while trying to send the requested content for request [" + request + "]");
return;
}
}
if (request.equals("/") || request.equals(Ref.URI_htmlRef)) {
request = Ref.URI_htmlRef;
- System.out.println("should be returning the html list [" + imaginaryMap.get(request).length() + "]");
+ //System.out.println("should be returning the html list [" + imaginaryMap.get(request).length() + "]");
try {
String resolvedAddressItem = Ref.app_handle_item + req.getScheme() + "://" + req.getLocalAddr() + ":" + req.getLocalPort();
String resolvedAddressList = Ref.app_handle_list + req.getScheme() + "://" + req.getLocalAddr() + ":" + req.getLocalPort();
System.out.println("resolved Address item : " + resolvedAddressItem);
System.out.println("resolved Address list : " + resolvedAddressList);
String htmlListing = imaginaryMap.get(request).replaceAll(Ref.app_handle_item, resolvedAddressItem);
htmlListing = htmlListing.replaceAll(Ref.app_handle_list, resolvedAddressList);
sendString(htmlListing, resp);
return;
} catch (Exception ex) {
resp.sendError(500, "The server encountered an error while trying to send the requested content for request [" + request + "]");
return;
}
}
if (null == imaginaryMap || !imaginaryMap.containsKey(request) || imaginaryMap.get(request) == null) {
resp.sendError(404, "The server could not find or get access to [" + request + "]");
return;
}
String string = imaginaryMap.get(request);
System.out.println("String from the imaginary map : [" + string + "]");
File f = new File(string);
if (f.exists()) {
try {
sendFile(f, resp);
} catch (Exception ex) {
resp.sendError(
500,
"The server encountered an error while trying to send the requested file [ " + f.getName() + "] for request [" + request + "]");
return;
}
} else {
resp.sendError(404, "The server could not find or get access to [" + f.getName() + "]");
return;
}
}
public static void sendString(String s, HttpServletResponse response) throws Exception {
byte[] bytes = s.getBytes();
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLength(bytes.length);
response.getOutputStream().write(bytes);
response.flushBuffer();
}
public static void sendFile(File f, HttpServletResponse response) throws Exception {
long len = f.length();
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLength((int) len);
int bufferSize = response.getBufferSize();
byte[] buff = new byte[bufferSize];
InputStream in;
in = new FileInputStream(f);
int nread;
while ((nread = in.read(buff)) > 0) {
response.getOutputStream().write(buff, 0, nread);
}
in.close();
response.getOutputStream().flush();
}
public void sendCSS(HttpServletResponse response) throws Exception {
long len = css.length();
response.setStatus(HttpServletResponse.SC_OK);
response.setContentLength((int) len);
int bufferSize = response.getBufferSize();
byte[] buff = new byte[bufferSize];
InputStream in;
in = new FileInputStream(css);
int nread;
while ((nread = in.read(buff)) > 0) {
response.getOutputStream().write(buff, 0, nread);
}
in.close();
response.getOutputStream().flush();
}
}
| false | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String request = req.getRequestURI();
System.out.println("URI : " + request);
if (request.equals("/" + Ref.sharing_jsonRef) || request.equals(Ref.URI_jsonRef)) {
String k = "/" + Ref.sharing_jsonRef;
System.out.println("should be returning the Displayable Feed [" + imaginaryMap.get(request).length() + "]");
try {
sendString(imaginaryMap.get(k), resp);
return;
} catch (Exception ex) {
resp.sendError(500, "The server encountered an error while trying to send the content for request [" + request + "]");
return;
}
}
if (request.compareTo("/index.css") == 0) {
System.out.println("should be returning the css.");
try {
sendCSS(resp);
return;
} catch (Exception ex) {
resp.sendError(500, "The server encountered an error while trying to send the requested content for request [" + request + "]");
return;
}
}
if (request.equals("/") || request.equals(Ref.URI_htmlRef)) {
request = Ref.URI_htmlRef;
System.out.println("should be returning the html list [" + imaginaryMap.get(request).length() + "]");
try {
String resolvedAddressItem = Ref.app_handle_item + req.getScheme() + "://" + req.getLocalAddr() + ":" + req.getLocalPort();
String resolvedAddressList = Ref.app_handle_list + req.getScheme() + "://" + req.getLocalAddr() + ":" + req.getLocalPort();
System.out.println("resolved Address item : " + resolvedAddressItem);
System.out.println("resolved Address list : " + resolvedAddressList);
String htmlListing = imaginaryMap.get(request).replaceAll(Ref.app_handle_item, resolvedAddressItem);
htmlListing = htmlListing.replaceAll(Ref.app_handle_list, resolvedAddressList);
sendString(htmlListing, resp);
return;
} catch (Exception ex) {
resp.sendError(500, "The server encountered an error while trying to send the requested content for request [" + request + "]");
return;
}
}
if (null == imaginaryMap || !imaginaryMap.containsKey(request) || imaginaryMap.get(request) == null) {
resp.sendError(404, "The server could not find or get access to [" + request + "]");
return;
}
String string = imaginaryMap.get(request);
System.out.println("String from the imaginary map : [" + string + "]");
File f = new File(string);
if (f.exists()) {
try {
sendFile(f, resp);
} catch (Exception ex) {
resp.sendError(
500,
"The server encountered an error while trying to send the requested file [ " + f.getName() + "] for request [" + request + "]");
return;
}
} else {
resp.sendError(404, "The server could not find or get access to [" + f.getName() + "]");
return;
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String request = req.getRequestURI();
System.out.println("URI : " + request);
if (request.equals("/" + Ref.sharing_jsonRef) || request.equals(Ref.URI_jsonRef)) {
String k = "/" + Ref.sharing_jsonRef;
//System.out.println("should be returning the Displayable Feed [" + imaginaryMap.get(k).length() + "]");
try {
sendString(imaginaryMap.get(k), resp);
return;
} catch (Exception ex) {
resp.sendError(500, "The server encountered an error while trying to send the content for request [" + request + "]");
return;
}
}
if (request.compareTo("/index.css") == 0) {
//System.out.println("should be returning the css.");
try {
sendCSS(resp);
return;
} catch (Exception ex) {
resp.sendError(500, "The server encountered an error while trying to send the requested content for request [" + request + "]");
return;
}
}
if (request.equals("/") || request.equals(Ref.URI_htmlRef)) {
request = Ref.URI_htmlRef;
//System.out.println("should be returning the html list [" + imaginaryMap.get(request).length() + "]");
try {
String resolvedAddressItem = Ref.app_handle_item + req.getScheme() + "://" + req.getLocalAddr() + ":" + req.getLocalPort();
String resolvedAddressList = Ref.app_handle_list + req.getScheme() + "://" + req.getLocalAddr() + ":" + req.getLocalPort();
System.out.println("resolved Address item : " + resolvedAddressItem);
System.out.println("resolved Address list : " + resolvedAddressList);
String htmlListing = imaginaryMap.get(request).replaceAll(Ref.app_handle_item, resolvedAddressItem);
htmlListing = htmlListing.replaceAll(Ref.app_handle_list, resolvedAddressList);
sendString(htmlListing, resp);
return;
} catch (Exception ex) {
resp.sendError(500, "The server encountered an error while trying to send the requested content for request [" + request + "]");
return;
}
}
if (null == imaginaryMap || !imaginaryMap.containsKey(request) || imaginaryMap.get(request) == null) {
resp.sendError(404, "The server could not find or get access to [" + request + "]");
return;
}
String string = imaginaryMap.get(request);
System.out.println("String from the imaginary map : [" + string + "]");
File f = new File(string);
if (f.exists()) {
try {
sendFile(f, resp);
} catch (Exception ex) {
resp.sendError(
500,
"The server encountered an error while trying to send the requested file [ " + f.getName() + "] for request [" + request + "]");
return;
}
} else {
resp.sendError(404, "The server could not find or get access to [" + f.getName() + "]");
return;
}
}
|
diff --git a/Servers/JavaServer/src/db/PreparedStatementWrapper.java b/Servers/JavaServer/src/db/PreparedStatementWrapper.java
index cf5c8c5d..faea9409 100644
--- a/Servers/JavaServer/src/db/PreparedStatementWrapper.java
+++ b/Servers/JavaServer/src/db/PreparedStatementWrapper.java
@@ -1,635 +1,638 @@
package db;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.TreeMap;
import java.util.Map;
/**
* A wrapper around <code>java.sql.PreparedStatement<code> class that can store the bind variables and can regenerate the SQL query.
* @author sekhri
*/
public class PreparedStatementWrapper implements PreparedStatement {
private PreparedStatement embedded;
private Connection conn;
private String sql;
private Map bindParams;
/**
* Constructs a PreparedStatementWrapper object that inherits from <code>java.sql.PreparedStatement</code>. This constructor initializes a private <code>java.sql.PreparedStatement, java.sql.Connection, java.util.TreeMap</code> that stores bind variables and <code>java.lang.String</code> that store the sql query.
*/
PreparedStatementWrapper(PreparedStatement ps, Connection c, String s) {
embedded = ps;
conn = c;
sql = s;
bindParams = new TreeMap();
}
/**
* A method that simply calls private method toString(String sql) with stored sql query in private variable sql.
* @return a <code>java.lang.String</code> that conatins the SQL query that is executed by the driver
*/
public String toString() {
return toString(sql);
}
/**
* A method that convert the bind variable into a well formed printable query. The format of the printable query can be user defined and be changed.
* @return a <code>java.lang.String</code> that conatins the SQL query that is executed by the driver
*/
private String toString(String sql) {
String logStr = sql;
int i = 1;
while (logStr.indexOf('?') >= 0) {
- logStr = logStr.replaceFirst("\\?", "'" + bindParams.get(new Integer(i++)).toString() + "'");
+ Object obj = bindParams.get(new Integer(i++));
+ String value="";
+ if ( obj != null ) value = obj.toString();
+ logStr = logStr.replaceFirst("\\?", "'" + value + "'");
}
return logStr;
//System.out.println("QUERY is "+ logStr);
}
/**
* {@inheritDoc}
*/
public int executeUpdate() throws SQLException {
return embedded.executeUpdate();
}
/**
* {@inheritDoc}
*/
public void addBatch() throws SQLException {
embedded.addBatch();
}
/**
* {@inheritDoc}
*/
public void clearParameters() throws SQLException {
embedded.clearParameters();
bindParams.clear();
}
/**
* {@inheritDoc}
*/
public boolean execute() throws SQLException {
return embedded.execute();
}
/**
* {@inheritDoc}
*/
public void setByte(int parameterIndex, byte x) throws SQLException {
embedded.setByte(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), new Byte(x));
}
/**
* {@inheritDoc}
*/
public void setDouble(int parameterIndex, double x) throws SQLException {
embedded.setDouble(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), new Double(x));
}
/**
* {@inheritDoc}
*/
public void setFloat(int parameterIndex, float x) throws SQLException {
embedded.setFloat(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), new Float(x));
}
/**
* {@inheritDoc}
*/
public void setInt(int parameterIndex, int x) throws SQLException {
embedded.setInt(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), new Integer(x));
}
/**
* {@inheritDoc}
*/
public void setNull(int parameterIndex, int sqlType) throws SQLException {
embedded.setNull(parameterIndex, sqlType);
bindParams.put(new Integer(parameterIndex), null);
}
/**
* {@inheritDoc}
*/
public void setLong(int parameterIndex, long x) throws SQLException {
embedded.setLong(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), new Long(x));
}
/**
* {@inheritDoc}
*/
public void setShort(int parameterIndex, short x) throws SQLException {
embedded.setShort(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), new Short(x));
}
/**
* {@inheritDoc}
*/
public void setBoolean(int parameterIndex, boolean x) throws SQLException {
embedded.setBoolean(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), new Boolean(x));
}
/**
* {@inheritDoc}
*/
public void setBytes(int parameterIndex, byte[] x) throws SQLException {
embedded.setBytes(parameterIndex, x);
// Should this be:
// bindParams.put(new Integer(parameterIndex), Arrays.asList(x));
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {
embedded.setAsciiStream(parameterIndex, x, length);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
embedded.setBinaryStream(parameterIndex, x, length);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {
embedded.setUnicodeStream(parameterIndex, x, length);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
embedded.setCharacterStream(parameterIndex, reader, length);
bindParams.put(new Integer(parameterIndex), reader);
}
/**
* {@inheritDoc}
*/
public void setObject(int parameterIndex, Object x) throws SQLException {
embedded.setObject(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
embedded.setObject(parameterIndex, x, targetSqlType);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException {
embedded.setObject(parameterIndex, x, targetSqlType, scale);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setNull(int paramIndex, int sqlType, String typeName)
throws SQLException {
embedded.setNull(paramIndex, sqlType, typeName);
bindParams.put(new Integer(paramIndex), null);
}
/**
* {@inheritDoc}
*/
public void setString(int parameterIndex, String x) throws SQLException {
embedded.setString(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setBigDecimal(int parameterIndex, BigDecimal x)
throws SQLException {
embedded.setBigDecimal(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setURL(int parameterIndex, URL x) throws SQLException {
embedded.setURL(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setArray(int i, Array x) throws SQLException {
embedded.setArray(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setBlob(int i, Blob x) throws SQLException {
embedded.setBlob(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setClob(int i, Clob x) throws SQLException {
embedded.setClob(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public void setDate(int parameterIndex, Date x) throws SQLException {
embedded.setDate(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public ParameterMetaData getParameterMetaData() throws SQLException {
return embedded.getParameterMetaData();
}
/**
* {@inheritDoc}
*/
public void setRef(int i, Ref x) throws SQLException {
embedded.setRef(i, x);
bindParams.put(new Integer(i), x);
}
/**
* {@inheritDoc}
*/
public ResultSet executeQuery() throws SQLException {
return embedded.executeQuery();
}
/**
* {@inheritDoc}
*/
public ResultSetMetaData getMetaData() throws SQLException {
return embedded.getMetaData();
}
/**
* {@inheritDoc}
*/
public void setTime(int parameterIndex, Time x) throws SQLException {
embedded.setTime(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {
embedded.setTimestamp(parameterIndex, x);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
embedded.setDate(parameterIndex, x, cal);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {
embedded.setTime(parameterIndex, x, cal);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {
embedded.setTimestamp(parameterIndex, x, cal);
bindParams.put(new Integer(parameterIndex), x);
}
/**
* {@inheritDoc}
*/
public int getFetchDirection() throws SQLException {
return embedded.getFetchDirection();
}
/**
* {@inheritDoc}
*/
public int getFetchSize() throws SQLException {
return embedded.getFetchSize();
}
/**
* {@inheritDoc}
*/
public int getMaxFieldSize() throws SQLException {
return embedded.getMaxFieldSize();
}
/**
* {@inheritDoc}
*/
public int getMaxRows() throws SQLException {
return embedded.getMaxRows();
}
/**
* {@inheritDoc}
*/
public int getQueryTimeout() throws SQLException {
return embedded.getQueryTimeout();
}
/**
* {@inheritDoc}
*/
public int getResultSetConcurrency() throws SQLException {
return embedded.getResultSetConcurrency();
}
/**
* {@inheritDoc}
*/
public int getResultSetHoldability() throws SQLException {
return embedded.getResultSetHoldability();
}
/**
* {@inheritDoc}
*/
public int getResultSetType() throws SQLException {
return embedded.getResultSetType();
}
/**
* {@inheritDoc}
*/
public int getUpdateCount() throws SQLException {
return embedded.getUpdateCount();
}
/**
* {@inheritDoc}
*/
public void cancel() throws SQLException {
embedded.cancel();
}
/**
* {@inheritDoc}
*/
public void clearBatch() throws SQLException {
embedded.clearBatch();
}
/**
* {@inheritDoc}
*/
public void clearWarnings() throws SQLException {
embedded.clearWarnings();
}
/**
* {@inheritDoc}
*/
public void close() throws SQLException {
embedded.close();
}
/**
* {@inheritDoc}
*/
public boolean getMoreResults() throws SQLException {
return embedded.getMoreResults();
}
/**
* {@inheritDoc}
*/
public int[] executeBatch() throws SQLException {
return embedded.executeBatch();
}
/**
* {@inheritDoc}
*/
public void setFetchDirection(int direction) throws SQLException {
embedded.setFetchDirection(direction);
}
/**
* {@inheritDoc}
*/
public void setFetchSize(int rows) throws SQLException {
embedded.setFetchSize(rows);
}
/**
* {@inheritDoc}
*/
public void setMaxFieldSize(int max) throws SQLException {
embedded.setMaxFieldSize(max);
}
/**
* {@inheritDoc}
*/
public void setMaxRows(int max) throws SQLException {
embedded.setMaxRows(max);
}
/**
* {@inheritDoc}
*/
public void setQueryTimeout(int seconds) throws SQLException {
embedded.setQueryTimeout(seconds);
}
/**
* {@inheritDoc}
*/
public boolean getMoreResults(int current) throws SQLException {
return embedded.getMoreResults(current);
}
/**
* {@inheritDoc}
*/
public void setEscapeProcessing(boolean enable) throws SQLException {
embedded.setEscapeProcessing(enable);
}
/**
* {@inheritDoc}
*/
public int executeUpdate(String sql) throws SQLException {
return embedded.executeUpdate(sql);
}
/**
* {@inheritDoc}
*/
public void addBatch(String sql) throws SQLException {
embedded.addBatch(sql);
}
/**
* {@inheritDoc}
*/
public void setCursorName(String name) throws SQLException {
embedded.setCursorName(name);
}
/**
* {@inheritDoc}
*/
public boolean execute(String sql) throws SQLException {
return embedded.execute(sql);
}
/**
* {@inheritDoc}
*/
public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
return embedded.executeUpdate(sql, autoGeneratedKeys);
}
/**
* {@inheritDoc}
*/
public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
return embedded.execute(sql, autoGeneratedKeys);
}
/**
* {@inheritDoc}
*/
public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
return embedded.executeUpdate(sql, columnIndexes);
}
/**
* {@inheritDoc}
*/
public boolean execute(String sql, int[] columnIndexes) throws SQLException {
return embedded.execute(sql, columnIndexes);
}
/**
* {@inheritDoc}
*/
public Connection getConnection() throws SQLException {
return conn;
}
/**
* {@inheritDoc}
*/
public ResultSet getGeneratedKeys() throws SQLException {
return embedded.getGeneratedKeys();
}
/**
* {@inheritDoc}
*/
public ResultSet getResultSet() throws SQLException {
return embedded.getResultSet();
}
/**
* {@inheritDoc}
*/
public SQLWarning getWarnings() throws SQLException {
return embedded.getWarnings();
}
/**
* {@inheritDoc}
*/
public int executeUpdate(String sql, String[] columnNames) throws SQLException {
return embedded.executeUpdate(sql, columnNames);
}
/**
* {@inheritDoc}
*/
public boolean execute(String sql, String[] columnNames) throws SQLException {
return embedded.execute(sql, columnNames);
}
/**
* {@inheritDoc}
*/
public ResultSet executeQuery(String sql) throws SQLException {
return embedded.executeQuery(sql);
}
/*protected void finalize() throws Exception {
ResultSet rs = this.getResultSet();
if (rs != null) {
rs.close();
}
this.close();
try {
super.finalize();
} catch (Exception e) {
}
}*/
}
| true | true | private String toString(String sql) {
String logStr = sql;
int i = 1;
while (logStr.indexOf('?') >= 0) {
logStr = logStr.replaceFirst("\\?", "'" + bindParams.get(new Integer(i++)).toString() + "'");
}
return logStr;
//System.out.println("QUERY is "+ logStr);
}
| private String toString(String sql) {
String logStr = sql;
int i = 1;
while (logStr.indexOf('?') >= 0) {
Object obj = bindParams.get(new Integer(i++));
String value="";
if ( obj != null ) value = obj.toString();
logStr = logStr.replaceFirst("\\?", "'" + value + "'");
}
return logStr;
//System.out.println("QUERY is "+ logStr);
}
|
diff --git a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java
index 2ea7d2e3a..a0da4cd64 100644
--- a/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java
+++ b/org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/AjLookupEnvironment.java
@@ -1,1437 +1,1442 @@
/* *******************************************************************
* Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
* 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:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.ajdt.internal.compiler.lookup;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collection;
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 org.aspectj.ajdt.internal.compiler.ast.AspectDeclaration;
import org.aspectj.ajdt.internal.compiler.ast.PointcutDeclaration;
import org.aspectj.asm.AsmManager;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.WeaveMessage;
import org.aspectj.bridge.context.CompilationAndWeavingContext;
import org.aspectj.bridge.context.ContextToken;
import org.aspectj.org.eclipse.jdt.core.compiler.CharOperation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.Annotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.NormalAnnotation;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.QualifiedTypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.SingleTypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeDeclaration;
import org.aspectj.org.eclipse.jdt.internal.compiler.ast.TypeReference;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.AccessRestriction;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.IBinaryType;
import org.aspectj.org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.aspectj.org.eclipse.jdt.internal.compiler.impl.ITypeRequestor;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.BinaryTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ClassScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LocalTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.MethodBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.PackageBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ParameterizedTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.ReferenceBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.SourceTypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TagBits;
import org.aspectj.org.eclipse.jdt.internal.compiler.lookup.TypeBinding;
import org.aspectj.org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
import org.aspectj.weaver.AnnotationAJ;
import org.aspectj.weaver.ConcreteTypeMunger;
import org.aspectj.weaver.ReferenceType;
import org.aspectj.weaver.ReferenceTypeDelegate;
import org.aspectj.weaver.ResolvedMember;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.UnresolvedType;
import org.aspectj.weaver.WeaverMessages;
import org.aspectj.weaver.WeaverStateInfo;
import org.aspectj.weaver.World;
import org.aspectj.weaver.bcel.BcelAnnotation;
import org.aspectj.weaver.bcel.BcelObjectType;
import org.aspectj.weaver.bcel.FakeAnnotation;
import org.aspectj.weaver.bcel.LazyClassGen;
import org.aspectj.weaver.patterns.DeclareAnnotation;
import org.aspectj.weaver.patterns.DeclareParents;
/**
* Overrides the default eclipse LookupEnvironment for two purposes.
*
* 1. To provide some additional phases to <code>completeTypeBindings</code> that weave declare parents and inter-type declarations
* at the correct time.
*
* 2. To intercept the loading of new binary types to ensure the they will have declare parents and inter-type declarations woven
* when appropriate.
*
* @author Jim Hugunin
*/
public class AjLookupEnvironment extends LookupEnvironment implements AnonymousClassCreationListener {
public EclipseFactory factory = null;
// private boolean builtInterTypesAndPerClauses = false;
private final List pendingTypesToWeave = new ArrayList();
// Q: What are dangerousInterfaces?
// A: An interface is considered dangerous if an ITD has been made upon it
// and that ITD
// requires the top most implementors of the interface to be woven *and yet*
// the aspect
// responsible for the ITD is not in the 'world'.
// Q: Err, how can that happen?
// A: When a type is on the inpath, it is 'processed' when completing type
// bindings. At this
// point we look at any type mungers it was affected by previously (stored
// in the weaver
// state info attribute). Effectively we are working with a type munger and
// yet may not have its
// originating aspect in the world. This is a problem if, for example, the
// aspect supplied
// a 'body' for a method targetting an interface - since the top most
// implementors should
// be woven by the munger from the aspect. When this happens we store the
// interface name here
// in the map - if we later process a type that is the topMostImplementor of
// a dangerous
// interface then we put out an error message.
/**
* interfaces targetted by ITDs that have to be implemented by accessing the topMostImplementor of the interface, yet the aspect
* where the ITD originated is not in the world
*/
private final Map dangerousInterfaces = new HashMap();
public AjLookupEnvironment(ITypeRequestor typeRequestor, CompilerOptions options, ProblemReporter problemReporter,
INameEnvironment nameEnvironment) {
super(typeRequestor, options, problemReporter, nameEnvironment);
}
// ??? duplicates some of super's code
public void completeTypeBindings() {
AsmManager.setCompletingTypeBindings(true);
ContextToken completeTypeBindingsToken = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.COMPLETING_TYPE_BINDINGS, "");
// builtInterTypesAndPerClauses = false;
// pendingTypesToWeave = new ArrayList();
stepCompleted = BUILD_TYPE_HIERARCHY;
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CHECK_AND_SET_IMPORTS,
units[i].compilationResult.fileName);
units[i].scope.checkAndSetImports();
CompilationAndWeavingContext.leavingPhase(tok);
}
stepCompleted = CHECK_AND_SET_IMPORTS;
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.CONNECTING_TYPE_HIERARCHY,
units[i].compilationResult.fileName);
units[i].scope.connectTypeHierarchy();
CompilationAndWeavingContext.leavingPhase(tok);
}
stepCompleted = CONNECT_TYPE_HIERARCHY;
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.BUILDING_FIELDS_AND_METHODS,
units[i].compilationResult.fileName);
// units[i].scope.checkParameterizedTypes(); do this check a little
// later, after ITDs applied to stbs
units[i].scope.buildFieldsAndMethods();
CompilationAndWeavingContext.leavingPhase(tok);
}
// would like to gather up all TypeDeclarations at this point and put
// them in the factory
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
factory.addSourceTypeBinding(b[j], units[i]);
}
}
// We won't find out about anonymous types until later though, so
// register to be
// told about them when they turn up.
AnonymousClassPublisher.aspectOf().setAnonymousClassCreationListener(this);
// need to build inter-type declarations for all AspectDeclarations at
// this point
// this MUST be done in order from super-types to subtypes
List typesToProcess = new ArrayList();
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
CompilationUnitScope cus = units[i].scope;
SourceTypeBinding[] stbs = cus.topLevelTypes;
for (int j = 0; j < stbs.length; j++) {
SourceTypeBinding stb = stbs[j];
typesToProcess.add(stb);
}
}
factory.getWorld().getCrosscuttingMembersSet().reset();
while (typesToProcess.size() > 0) {
// removes types from the list as they are processed...
collectAllITDsAndDeclares((SourceTypeBinding) typesToProcess.get(0), typesToProcess);
}
factory.finishTypeMungers();
// now do weaving
Collection typeMungers = factory.getTypeMungers();
Collection declareParents = factory.getDeclareParents();
Collection declareAnnotationOnTypes = factory.getDeclareAnnotationOnTypes();
doPendingWeaves();
// We now have some list of types to process, and we are about to apply
// the type mungers.
// There can be situations where the order of types passed to the
// compiler causes the
// output from the compiler to vary - THIS IS BAD. For example, if we
// have class A
// and class B extends A. Also, an aspect that 'declare parents: A+
// implements Serializable'
// then depending on whether we see A first, we may or may not make B
// serializable.
// The fix is to process them in the right order, ensuring that for a
// type we process its
// supertypes and superinterfaces first. This algorithm may have
// problems with:
// - partial hierarchies (e.g. suppose types A,B,C are in a hierarchy
// and A and C are to be woven but not B)
// - weaving that brings new types in for processing (see
// pendingTypesToWeave.add() calls) after we thought
// we had the full list.
//
// but these aren't common cases (he bravely said...)
boolean typeProcessingOrderIsImportant = declareParents.size() > 0 || declareAnnotationOnTypes.size() > 0; // DECAT
if (typeProcessingOrderIsImportant) {
typesToProcess = new ArrayList();
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
CompilationUnitScope cus = units[i].scope;
SourceTypeBinding[] stbs = cus.topLevelTypes;
for (int j = 0; j < stbs.length; j++) {
SourceTypeBinding stb = stbs[j];
typesToProcess.add(stb);
}
}
while (typesToProcess.size() > 0) {
// A side effect of weaveIntertypes() is that the processed type
// is removed from the collection
weaveIntertypes(typesToProcess, (SourceTypeBinding) typesToProcess.get(0), typeMungers, declareParents,
declareAnnotationOnTypes);
}
} else {
// Order isn't important
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
// System.err.println("Working on "+new
// String(units[i].getFileName()));
weaveInterTypeDeclarations(units[i].scope, typeMungers, declareParents, declareAnnotationOnTypes);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
units[i].scope.checkParameterizedTypes();
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.RESOLVING_POINTCUT_DECLARATIONS, b[j].sourceName);
resolvePointcutDeclarations(b[j].scope);
CompilationAndWeavingContext.leavingPhase(tok);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
SourceTypeBinding[] b = units[i].scope.topLevelTypes;
for (int j = 0; j < b.length; j++) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.ADDING_DECLARE_WARNINGS_AND_ERRORS, b[j].sourceName);
addAdviceLikeDeclares(b[j].scope);
CompilationAndWeavingContext.leavingPhase(tok);
}
}
for (int i = lastCompletedUnitIndex + 1; i <= lastUnitIndex; i++) {
units[i] = null; // release unnecessary reference to the parsed unit
}
stepCompleted = BUILD_FIELDS_AND_METHODS;
lastCompletedUnitIndex = lastUnitIndex;
AsmManager.setCompletingTypeBindings(false);
factory.getWorld().getCrosscuttingMembersSet().verify();
CompilationAndWeavingContext.leavingPhase(completeTypeBindingsToken);
}
// /**
// * For any given sourcetypebinding, this method checks that if it is a
// parameterized aspect that
// * the type parameters specified for any supertypes meet the bounds for
// the generic type
// * variables.
// */
// private void verifyAnyTypeParametersMeetBounds(SourceTypeBinding
// sourceType) {
// ResolvedType onType = factory.fromEclipse(sourceType);
// if (onType.isAspect()) {
// ResolvedType superType = factory.fromEclipse(sourceType.superclass);
// // Don't need to check if it was used in its RAW form or isnt generic
// if (superType.isGenericType() || superType.isParameterizedType()) {
// TypeVariable[] typeVariables = superType.getTypeVariables();
// UnresolvedType[] typeParams = superType.getTypeParameters();
// if (typeVariables!=null && typeParams!=null) {
// for (int i = 0; i < typeVariables.length; i++) {
// boolean ok =
// typeVariables[i].canBeBoundTo(typeParams[i].resolve(factory.getWorld()));
// if (!ok) { // the supplied parameter violates the bounds
// // Type {0} does not meet the specification for type parameter {1} ({2})
// in generic type {3}
// String msg =
// WeaverMessages.format(
// WeaverMessages.VIOLATES_TYPE_VARIABLE_BOUNDS,
// typeParams[i],
// new Integer(i+1),
// typeVariables[i].getDisplayName(),
// superType.getGenericType().getName());
// factory.getWorld().getMessageHandler().handleMessage(MessageUtil.error(msg
// ,onType.getSourceLocation()));
// }
// }
// }
// }
// }
// }
public void doSupertypesFirst(ReferenceBinding rb, Collection yetToProcess) {
if (rb instanceof SourceTypeBinding) {
if (yetToProcess.contains(rb)) {
collectAllITDsAndDeclares((SourceTypeBinding) rb, yetToProcess);
}
} else if (rb instanceof ParameterizedTypeBinding) {
// If its a PTB we need to pull the SourceTypeBinding out of it.
ParameterizedTypeBinding ptb = (ParameterizedTypeBinding) rb;
if (ptb.type instanceof SourceTypeBinding && yetToProcess.contains(ptb.type)) {
collectAllITDsAndDeclares((SourceTypeBinding) ptb.type, yetToProcess);
}
}
}
/**
* Find all the ITDs and Declares, but it is important we do this from the supertypes down to the subtypes.
*
* @param sourceType
* @param yetToProcess
*/
private void collectAllITDsAndDeclares(SourceTypeBinding sourceType, Collection yetToProcess) {
// Look at the supertype first
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.COLLECTING_ITDS_AND_DECLARES,
sourceType.sourceName);
yetToProcess.remove(sourceType);
// look out our direct supertype
doSupertypesFirst(sourceType.superclass(), yetToProcess);
// now check our membertypes (pr119570)
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
SourceTypeBinding rb = (SourceTypeBinding) memberTypes[i];
if (!rb.superclass().equals(sourceType)) {
doSupertypesFirst(rb.superclass(), yetToProcess);
}
}
buildInterTypeAndPerClause(sourceType.scope);
addCrosscuttingStructures(sourceType.scope);
CompilationAndWeavingContext.leavingPhase(tok);
}
/**
* Weave the parents and intertype decls into a given type. This method looks at the supertype and superinterfaces for the
* specified type and recurses to weave those first if they are in the full list of types we are going to process during this
* compile... it stops recursing the first time it hits a type we aren't going to process during this compile. This could cause
* problems if you supply 'pieces' of a hierarchy, i.e. the bottom and the top, but not the middle - but what the hell are you
* doing if you do that?
*/
private void weaveIntertypes(List typesToProcess, SourceTypeBinding typeToWeave, Collection typeMungers,
Collection declareParents, Collection declareAnnotationOnTypes) {
// Look at the supertype first
ReferenceBinding superType = typeToWeave.superclass();
if (typesToProcess.contains(superType) && superType instanceof SourceTypeBinding) {
// System.err.println("Recursing to supertype "+new
// String(superType.getFileName()));
weaveIntertypes(typesToProcess, (SourceTypeBinding) superType, typeMungers, declareParents, declareAnnotationOnTypes);
}
// Then look at the superinterface list
ReferenceBinding[] interfaceTypes = typeToWeave.superInterfaces();
for (int i = 0; i < interfaceTypes.length; i++) {
ReferenceBinding binding = interfaceTypes[i];
if (typesToProcess.contains(binding) && binding instanceof SourceTypeBinding) {
// System.err.println("Recursing to superinterface "+new
// String(binding.getFileName()));
weaveIntertypes(typesToProcess, (SourceTypeBinding) binding, typeMungers, declareParents, declareAnnotationOnTypes);
}
}
weaveInterTypeDeclarations(typeToWeave, typeMungers, declareParents, declareAnnotationOnTypes, false);
typesToProcess.remove(typeToWeave);
}
private void doPendingWeaves() {
for (Iterator i = pendingTypesToWeave.iterator(); i.hasNext();) {
SourceTypeBinding t = (SourceTypeBinding) i.next();
ContextToken tok = CompilationAndWeavingContext.enteringPhase(
CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS, t.sourceName);
weaveInterTypeDeclarations(t);
CompilationAndWeavingContext.leavingPhase(tok);
}
pendingTypesToWeave.clear();
}
private void addAdviceLikeDeclares(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
if (dec instanceof AspectDeclaration) {
ResolvedType typeX = factory.fromEclipse(dec.binding);
factory.getWorld().getCrosscuttingMembersSet().addAdviceLikeDeclares(typeX);
}
SourceTypeBinding sourceType = s.referenceContext.binding;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addAdviceLikeDeclares(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private void addCrosscuttingStructures(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
if (dec instanceof AspectDeclaration) {
ResolvedType typeX = factory.fromEclipse(dec.binding);
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX, false);
if (typeX.getSuperclass().isAspect() && !typeX.getSuperclass().isExposedToWeaver()) {
factory.getWorld().getCrosscuttingMembersSet().addOrReplaceAspect(typeX.getSuperclass(), false);
}
}
SourceTypeBinding sourceType = s.referenceContext.binding;
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
addCrosscuttingStructures(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private void resolvePointcutDeclarations(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
SourceTypeBinding sourceType = s.referenceContext.binding;
boolean hasPointcuts = false;
AbstractMethodDeclaration[] methods = dec.methods;
boolean initializedMethods = false;
if (methods != null) {
for (int i = 0; i < methods.length; i++) {
if (methods[i] instanceof PointcutDeclaration) {
hasPointcuts = true;
if (!initializedMethods) {
sourceType.methods(); // force initialization
initializedMethods = true;
}
((PointcutDeclaration) methods[i]).resolvePointcut(s);
}
}
}
if (hasPointcuts || dec instanceof AspectDeclaration || couldBeAnnotationStyleAspectDeclaration(dec)) {
ReferenceType name = (ReferenceType) factory.fromEclipse(sourceType);
EclipseSourceType eclipseSourceType = (EclipseSourceType) name.getDelegate();
eclipseSourceType.checkPointcutDeclarations();
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
resolvePointcutDeclarations(((SourceTypeBinding) memberTypes[i]).scope);
}
}
/**
* Return true if the declaration has @Aspect annotation. Called 'couldBe' rather than 'is' because someone else may have
* defined an annotation called Aspect - we can't verify the full name (including package name) because it may not have been
* resolved just yet and rather going through expensive resolution when we dont have to, this gives us a cheap check that tells
* us whether to bother.
*/
private boolean couldBeAnnotationStyleAspectDeclaration(TypeDeclaration dec) {
Annotation[] annotations = dec.annotations;
boolean couldBeAtAspect = false;
if (annotations != null) {
for (int i = 0; i < annotations.length && !couldBeAtAspect; i++) {
if (annotations[i].toString().equals("@Aspect")) {
couldBeAtAspect = true;
}
}
}
return couldBeAtAspect;
}
private void buildInterTypeAndPerClause(ClassScope s) {
TypeDeclaration dec = s.referenceContext;
if (dec instanceof AspectDeclaration) {
((AspectDeclaration) dec).buildInterTypeAndPerClause(s);
}
SourceTypeBinding sourceType = s.referenceContext.binding;
// test classes don't extend aspects
if (sourceType.superclass != null) {
ResolvedType parent = factory.fromEclipse(sourceType.superclass);
if (parent.isAspect() && !isAspect(dec)) {
factory.showMessage(IMessage.ERROR, "class \'" + new String(sourceType.sourceName) + "\' can not extend aspect \'"
+ parent.getName() + "\'", factory.fromEclipse(sourceType).getSourceLocation(), null);
}
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
buildInterTypeAndPerClause(((SourceTypeBinding) memberTypes[i]).scope);
}
}
private boolean isAspect(TypeDeclaration decl) {
if ((decl instanceof AspectDeclaration)) {
return true;
} else if (decl.annotations == null) {
return false;
} else {
for (int i = 0; i < decl.annotations.length; i++) {
Annotation ann = decl.annotations[i];
if (ann.type instanceof SingleTypeReference) {
if (CharOperation.equals("Aspect".toCharArray(), ((SingleTypeReference) ann.type).token)) {
return true;
}
} else if (ann.type instanceof QualifiedTypeReference) {
QualifiedTypeReference qtr = (QualifiedTypeReference) ann.type;
if (qtr.tokens.length != 5) {
return false;
}
if (!CharOperation.equals("org".toCharArray(), qtr.tokens[0])) {
return false;
}
if (!CharOperation.equals("aspectj".toCharArray(), qtr.tokens[1])) {
return false;
}
if (!CharOperation.equals("lang".toCharArray(), qtr.tokens[2])) {
return false;
}
if (!CharOperation.equals("annotation".toCharArray(), qtr.tokens[3])) {
return false;
}
if (!CharOperation.equals("Aspect".toCharArray(), qtr.tokens[4])) {
return false;
}
return true;
}
}
}
return false;
}
private void weaveInterTypeDeclarations(CompilationUnitScope unit, Collection typeMungers, Collection declareParents,
Collection declareAnnotationOnTypes) {
for (int i = 0, length = unit.topLevelTypes.length; i < length; i++) {
weaveInterTypeDeclarations(unit.topLevelTypes[i], typeMungers, declareParents, declareAnnotationOnTypes, false);
}
}
private void weaveInterTypeDeclarations(SourceTypeBinding sourceType) {
if (!factory.areTypeMungersFinished()) {
if (!pendingTypesToWeave.contains(sourceType)) {
pendingTypesToWeave.add(sourceType);
}
} else {
weaveInterTypeDeclarations(sourceType, factory.getTypeMungers(), factory.getDeclareParents(), factory
.getDeclareAnnotationOnTypes(), true);
}
}
private void weaveInterTypeDeclarations(SourceTypeBinding sourceType, Collection typeMungers, Collection declareParents,
Collection declareAnnotationOnTypes, boolean skipInners) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.WEAVING_INTERTYPE_DECLARATIONS,
sourceType.sourceName);
ResolvedType onType = factory.fromEclipse(sourceType);
// AMC we shouldn't need this when generic sigs are fixed??
if (onType.isRawType()) {
onType = onType.getGenericType();
}
WeaverStateInfo info = onType.getWeaverState();
// this test isnt quite right - there will be a case where we fail to
// flag a problem
// with a 'dangerous interface' because the type is reweavable when we
// should have
// because the type wasn't going to be rewoven... if that happens, we
// should perhaps
// move this test and dangerous interface processing to the end of this
// method and
// make it conditional on whether any of the typeMungers passed into
// here actually
// matched this type.
if (info != null && !info.isOldStyle() && !info.isReweavable()) {
processTypeMungersFromExistingWeaverState(sourceType, onType);
CompilationAndWeavingContext.leavingPhase(tok);
return;
}
// Check if the type we are looking at is the topMostImplementor of a
// dangerous interface -
// report a problem if it is.
for (Iterator i = dangerousInterfaces.entrySet().iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
ResolvedType interfaceType = (ResolvedType) entry.getKey();
if (onType.isTopmostImplementor(interfaceType)) {
factory.showMessage(IMessage.ERROR, onType + ": " + entry.getValue(), onType.getSourceLocation(), null);
}
}
boolean needOldStyleWarning = (info != null && info.isOldStyle());
onType.clearInterTypeMungers();
// FIXME asc perf Could optimize here, after processing the expected set
// of types we may bring
// binary types that are not exposed to the weaver, there is no need to
// attempt declare parents
// or declare annotation really - unless we want to report the
// not-exposed to weaver
// messages...
List decpToRepeat = new ArrayList();
List decaToRepeat = new ArrayList();
boolean anyNewParents = false;
boolean anyNewAnnotations = false;
// first pass
// try and apply all decps - if they match, then great. If they don't
// then
// check if they are starred-annotation patterns. If they are not
// starred
// annotation patterns then they might match later...remember that...
for (Iterator i = declareParents.iterator(); i.hasNext();) {
DeclareParents decp = (DeclareParents) i.next();
if (!decp.isMixin()) {
boolean didSomething = doDeclareParents(decp, sourceType);
if (didSomething) {
anyNewParents = true;
} else {
if (!decp.getChild().isStarAnnotation()) {
decpToRepeat.add(decp);
}
}
}
}
for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) {
DeclareAnnotation deca = (DeclareAnnotation) i.next();
boolean didSomething = doDeclareAnnotations(deca, sourceType, true);
if (didSomething) {
anyNewAnnotations = true;
} else {
if (!deca.getTypePattern().isStar()) {
decaToRepeat.add(deca);
}
}
}
// now lets loop over and over until we have done all we can
while ((anyNewAnnotations || anyNewParents) && (!decpToRepeat.isEmpty() || !decaToRepeat.isEmpty())) {
anyNewParents = anyNewAnnotations = false;
List forRemoval = new ArrayList();
for (Iterator i = decpToRepeat.iterator(); i.hasNext();) {
DeclareParents decp = (DeclareParents) i.next();
boolean didSomething = doDeclareParents(decp, sourceType);
if (didSomething) {
anyNewParents = true;
forRemoval.add(decp);
}
}
decpToRepeat.removeAll(forRemoval);
forRemoval.clear();
for (Iterator i = declareAnnotationOnTypes.iterator(); i.hasNext();) {
DeclareAnnotation deca = (DeclareAnnotation) i.next();
boolean didSomething = doDeclareAnnotations(deca, sourceType, false);
if (didSomething) {
anyNewAnnotations = true;
forRemoval.add(deca);
}
}
decaToRepeat.removeAll(forRemoval);
}
for (Iterator i = typeMungers.iterator(); i.hasNext();) {
EclipseTypeMunger munger = (EclipseTypeMunger) i.next();
if (munger.matches(onType)) {
if (needOldStyleWarning) {
factory.showMessage(IMessage.WARNING, "The class for " + onType
+ " should be recompiled with ajc-1.1.1 for best results", onType.getSourceLocation(), null);
needOldStyleWarning = false;
}
onType.addInterTypeMunger(munger, true);
}
}
onType.checkInterTypeMungers();
for (Iterator i = onType.getInterTypeMungers().iterator(); i.hasNext();) {
EclipseTypeMunger munger = (EclipseTypeMunger) i.next();
munger.munge(sourceType, onType);
}
// Call if you would like to do source weaving of declare
// @method/@constructor
// at source time... no need to do this as it can't impact anything, but
// left here for
// future generations to enjoy. Method source is commented out at the
// end of this module
// doDeclareAnnotationOnMethods();
// Call if you would like to do source weaving of declare @field
// at source time... no need to do this as it can't impact anything, but
// left here for
// future generations to enjoy. Method source is commented out at the
// end of this module
// doDeclareAnnotationOnFields();
if (skipInners) {
CompilationAndWeavingContext.leavingPhase(tok);
return;
}
ReferenceBinding[] memberTypes = sourceType.memberTypes;
for (int i = 0, length = memberTypes.length; i < length; i++) {
if (memberTypes[i] instanceof SourceTypeBinding) {
weaveInterTypeDeclarations((SourceTypeBinding) memberTypes[i], typeMungers, declareParents,
declareAnnotationOnTypes, false);
}
}
CompilationAndWeavingContext.leavingPhase(tok);
}
/**
* Called when we discover we are weaving intertype declarations on some type that has an existing 'WeaverStateInfo' object -
* this is typically some previously woven type that has been passed on the inpath.
*
* sourceType and onType are the 'same type' - the former is the 'Eclipse' version and the latter is the 'Weaver' version.
*/
private void processTypeMungersFromExistingWeaverState(SourceTypeBinding sourceType, ResolvedType onType) {
Collection previouslyAppliedMungers = onType.getWeaverState().getTypeMungers(onType);
for (Iterator i = previouslyAppliedMungers.iterator(); i.hasNext();) {
ConcreteTypeMunger m = (ConcreteTypeMunger) i.next();
EclipseTypeMunger munger = factory.makeEclipseTypeMunger(m);
if (munger.munge(sourceType, onType)) {
if (onType.isInterface() && munger.getMunger().needsAccessToTopmostImplementor()) {
if (!onType.getWorld().getCrosscuttingMembersSet().containsAspect(munger.getAspectType())) {
dangerousInterfaces
.put(onType, "implementors of " + onType + " must be woven by " + munger.getAspectType());
}
}
}
}
}
private boolean doDeclareParents(DeclareParents declareParents, SourceTypeBinding sourceType) {
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_PARENTS,
sourceType.sourceName);
ResolvedType resolvedSourceType = factory.fromEclipse(sourceType);
List newParents = declareParents.findMatchingNewParents(resolvedSourceType, false);
if (!newParents.isEmpty()) {
for (Iterator i = newParents.iterator(); i.hasNext();) {
ResolvedType parent = (ResolvedType) i.next();
if (dangerousInterfaces.containsKey(parent)) {
ResolvedType onType = factory.fromEclipse(sourceType);
factory.showMessage(IMessage.ERROR, onType + ": " + dangerousInterfaces.get(parent),
onType.getSourceLocation(), null);
}
if (Modifier.isFinal(parent.getModifiers())) {
factory.showMessage(IMessage.ERROR, "cannot extend final class " + parent.getClassName(), declareParents
.getSourceLocation(), null);
} else {
// do not actually do it if the type isn't exposed - this
// will correctly reported as a problem elsewhere
if (!resolvedSourceType.isExposedToWeaver()) {
return false;
}
// AsmRelationshipProvider.getDefault().
// addDeclareParentsRelationship
// (declareParents.getSourceLocation(),
// factory.fromEclipse(sourceType), newParents);
addParent(sourceType, parent);
}
}
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
private String stringifyTargets(long bits) {
if ((bits & TagBits.AnnotationTargetMASK) == 0) {
return "";
}
Set s = new HashSet();
if ((bits & TagBits.AnnotationForAnnotationType) != 0) {
s.add("ANNOTATION_TYPE");
}
if ((bits & TagBits.AnnotationForConstructor) != 0) {
s.add("CONSTRUCTOR");
}
if ((bits & TagBits.AnnotationForField) != 0) {
s.add("FIELD");
}
if ((bits & TagBits.AnnotationForLocalVariable) != 0) {
s.add("LOCAL_VARIABLE");
}
if ((bits & TagBits.AnnotationForMethod) != 0) {
s.add("METHOD");
}
if ((bits & TagBits.AnnotationForPackage) != 0) {
s.add("PACKAGE");
}
if ((bits & TagBits.AnnotationForParameter) != 0) {
s.add("PARAMETER");
}
if ((bits & TagBits.AnnotationForType) != 0) {
s.add("TYPE");
}
StringBuffer sb = new StringBuffer();
sb.append("{");
for (Iterator iter = s.iterator(); iter.hasNext();) {
String element = (String) iter.next();
sb.append(element);
if (iter.hasNext()) {
sb.append(",");
}
}
sb.append("}");
return sb.toString();
}
private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) {
ResolvedType rtx = factory.fromEclipse(sourceType);
if (!decA.matches(rtx)) {
return false;
}
if (!rtx.isExposedToWeaver()) {
return false;
}
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS,
sourceType.sourceName);
// Get the annotation specified in the declare
UnresolvedType aspectType = decA.getAspect();
if (aspectType instanceof ReferenceType) {
ReferenceType rt = (ReferenceType) aspectType;
if (rt.isParameterizedType() || rt.isRawType()) {
aspectType = rt.getGenericType();
}
}
TypeBinding tb = factory.makeTypeBinding(aspectType);
// Hideousness follows:
// There are multiple situations to consider here and they relate to the
// combinations of
// where the annotation is coming from and where the annotation is going
// to be put:
//
// 1. Straight full build, all from source - the annotation is from a
// dec@type and
// is being put on some type. Both types are real SourceTypeBindings.
// WORKS
// 2. Incremental build, changing the affected type - the annotation is
// from a
// dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and
// the
// affected type is a real SourceTypeBinding. Mostly works (pr128665)
// 3. ?
SourceTypeBinding stb = (SourceTypeBinding) tb;
Annotation[] toAdd = null;
long abits = 0;
// Might have to retrieve the annotation through BCEL and construct an
// eclipse one for it.
if (stb instanceof BinaryTypeBinding) {
ReferenceType rt = (ReferenceType) factory.fromEclipse(stb);
ResolvedMember[] methods = rt.getDeclaredMethods();
ResolvedMember decaMethod = null;
String nameToLookFor = decA.getAnnotationMethod();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(nameToLookFor)) {
decaMethod = methods[i];
break;
}
}
if (decaMethod != null) { // could assert this ...
AnnotationAJ[] axs = decaMethod.getAnnotations();
if (axs != null) { // another error has occurred, dont crash here because of it
toAdd = new Annotation[1];
toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory);
// BUG BUG BUG - We dont test these abits are correct, in fact
// we'll be very lucky if they are.
// What does that mean? It means on an incremental compile you
// might get away with an
// annotation that isn't allowed on a type being put on a type.
if (toAdd[0].resolvedType != null) {
abits = toAdd[0].resolvedType.getAnnotationTagBits();
}
}
}
} else if (stb != null) {
// much nicer, its a real SourceTypeBinding so we can stay in
// eclipse land
// if (decA.getAnnotationMethod() != null) {
MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray());
abits = mbs[0].getAnnotationTagBits(); // ensure resolved
TypeDeclaration typeDecl = ((SourceTypeBinding) mbs[0].declaringClass).scope.referenceContext;
AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]);
toAdd = methodDecl.annotations; // this is what to add
toAdd[0] = createAnnotationCopy(toAdd[0]);
if (toAdd[0].resolvedType != null) {
abits = toAdd[0].resolvedType.getAnnotationTagBits();
// }
}
}
// This happens if there is another error in the code - that should be reported separately
if (toAdd == null || toAdd[0] == null || toAdd[0].type == null) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
if (sourceType instanceof BinaryTypeBinding) {
// In this case we can't access the source type binding to add a new
// annotation, so let's put something
// on the weaver type temporarily
ResolvedType theTargetType = factory.fromEclipse(sourceType);
TypeBinding theAnnotationType = toAdd[0].resolvedType;
+ // The annotation type may be null if it could not be resolved (eg. the relevant import has not been added yet)
+ // In this case an error will be put out about the annotation but not if we crash here
+ if (theAnnotationType == null) {
+ return false;
+ }
String sig = new String(theAnnotationType.signature());
UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig);
String name = bcelAnnotationType.getName();
if (theTargetType.hasAnnotation(bcelAnnotationType)) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
// FIXME asc tidy up this code that duplicates whats below!
// Simple checks on the bits
boolean giveupnow = false;
if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) {
// error will have been already reported
giveupnow = true;
} else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
|| (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
if (reportProblems) {
if (decA.isExactPattern()) {
factory.showMessage(IMessage.ERROR, WeaverMessages.format(
WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
stringifyTargets(abits)), decA.getSourceLocation(), null);
}
// dont put out the lint - the weaving process will do
// that
// else {
// if (factory.getWorld().getLint().
// invalidTargetForAnnotation.isEnabled()) {
// factory.getWorld().getLint().invalidTargetForAnnotation
// .signal(new
// String[]{rtx.getName(),toAdd[0].type.toString(),
// stringifyTargets
// (abits)},decA.getSourceLocation(),null);
// }
// }
}
giveupnow = true;
}
}
if (giveupnow) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig,
(abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld()));
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations;
if (currentAnnotations != null) {
for (int i = 0; i < currentAnnotations.length; i++) {
Annotation annotation = currentAnnotations[i];
String a = CharOperation.toString(annotation.type.getTypeName());
String b = CharOperation.toString(toAdd[0].type.getTypeName());
// FIXME asc we have a lint for attempting to add an annotation
// twice to a method,
// we could put it out here *if* we can resolve the problem of
// errors coming out
// multiple times if we have cause to loop through here
if (a.equals(b)) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
}
}
if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) {
// this means it specifies something other than annotation or
// normal type - error will have been already reported,
// just resolution process above
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
|| (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
if (reportProblems) {
if (decA.isExactPattern()) {
factory.showMessage(IMessage.ERROR, WeaverMessages.format(
WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
stringifyTargets(abits)), decA.getSourceLocation(), null);
}
// dont put out the lint - the weaving process will do that
// else {
// if
// (factory.getWorld().getLint().invalidTargetForAnnotation
// .isEnabled()) {
// factory.getWorld().getLint().invalidTargetForAnnotation.
// signal(new
// String[]{rtx.getName(),toAdd[0].type.toString(),
// stringifyTargets(abits)},decA.getSourceLocation(),null);
// }
// }
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
}
// Build a new array of annotations
// remember the current set (rememberAnnotations only does something the
// first time it is called for a type)
sourceType.scope.referenceContext.rememberAnnotations();
// AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(
// decA.getSourceLocation(), rtx.getSourceLocation());
Annotation abefore[] = sourceType.scope.referenceContext.annotations;
Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)];
System.arraycopy(toAdd, 0, newset, 0, toAdd.length);
if (abefore != null) {
System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length);
}
sourceType.scope.referenceContext.annotations = newset;
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
/**
* Transform an annotation from its AJ form to an eclipse form. We *DONT* care about the values of the annotation. that is
* because it is only being stuck on a type during type completion to allow for other constructs (decps, decas) that might be
* looking for it - when the class actually gets to disk it wont have this new annotation on it and during weave time we will do
* the right thing copying across values too.
*/
private static Annotation createAnnotationFromBcelAnnotation(AnnotationAJ annX, int pos, EclipseFactory factory) {
String name = annX.getTypeName();
TypeBinding tb = factory.makeTypeBinding(annX.getType());
// String theName = annX.getSignature().getBaseName();
char[][] typeName = CharOperation.splitOn('.', name.replace('$', '.').toCharArray()); // pr149293 - not bulletproof...
long[] positions = new long[typeName.length];
for (int i = 0; i < positions.length; i++) {
positions[i] = pos;
}
TypeReference annType = new QualifiedTypeReference(typeName, positions);
NormalAnnotation ann = new NormalAnnotation(annType, pos);
ann.resolvedType = tb; // yuck - is this OK in all cases?
// We don't need membervalues...
// Expression pcExpr = new
// StringLiteral(pointcutExpression.toCharArray(),pos,pos);
// MemberValuePair[] mvps = new MemberValuePair[2];
// mvps[0] = new MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
// Expression argNamesExpr = new
// StringLiteral(argNames.toCharArray(),pos,pos);
// mvps[1] = new
// MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
// ann.memberValuePairs = mvps;
return ann;
}
/**
* Create a copy of an annotation, not deep but deep enough so we don't copy across fields that will get us into trouble like
* 'recipient'
*/
private static Annotation createAnnotationCopy(Annotation ann) {
NormalAnnotation ann2 = new NormalAnnotation(ann.type, ann.sourceStart);
ann2.memberValuePairs = ann.memberValuePairs();
ann2.resolvedType = ann.resolvedType;
ann2.bits = ann.bits;
return ann2;
// String name = annX.getTypeName();
// TypeBinding tb = factory.makeTypeBinding(annX.getSignature());
// String theName = annX.getSignature().getBaseName();
// char[][] typeName =
// CharOperation.splitOn('.',name.replace('$','.').toCharArray());
// //pr149293 - not bulletproof...
// long[] positions = new long[typeName.length];
// for (int i = 0; i < positions.length; i++) positions[i]=pos;
// TypeReference annType = new
// QualifiedTypeReference(typeName,positions);
// NormalAnnotation ann = new NormalAnnotation(annType,pos);
// ann.resolvedType=tb; // yuck - is this OK in all cases?
// // We don't need membervalues...
// // Expression pcExpr = new
// StringLiteral(pointcutExpression.toCharArray(),pos,pos);
// // MemberValuePair[] mvps = new MemberValuePair[2];
// // mvps[0] = new
// MemberValuePair("value".toCharArray(),pos,pos,pcExpr);
// // Expression argNamesExpr = new
// StringLiteral(argNames.toCharArray(),pos,pos);
// // mvps[1] = new
// MemberValuePair("argNames".toCharArray(),pos,pos,argNamesExpr);
// // ann.memberValuePairs = mvps;
// return ann;
}
private boolean isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(long abits) {
return (abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0;
}
private void reportDeclareParentsMessage(WeaveMessage.WeaveMessageKind wmk, SourceTypeBinding sourceType, ResolvedType parent) {
if (!factory.getWorld().getMessageHandler().isIgnoring(IMessage.WEAVEINFO)) {
String filename = new String(sourceType.getFileName());
int takefrom = filename.lastIndexOf('/');
if (takefrom == -1) {
takefrom = filename.lastIndexOf('\\');
}
filename = filename.substring(takefrom + 1);
factory.getWorld().getMessageHandler().handleMessage(
WeaveMessage.constructWeavingMessage(wmk, new String[] { CharOperation.toString(sourceType.compoundName),
filename, parent.getClassName(), getShortname(parent.getSourceLocation().getSourceFile().getPath()) }));
}
}
private String getShortname(String path) {
int takefrom = path.lastIndexOf('/');
if (takefrom == -1) {
takefrom = path.lastIndexOf('\\');
}
return path.substring(takefrom + 1);
}
private void addParent(SourceTypeBinding sourceType, ResolvedType parent) {
ReferenceBinding parentBinding = (ReferenceBinding) factory.makeTypeBinding(parent);
if (parentBinding == null) {
return; // The parent is missing, it will be reported elsewhere.
}
sourceType.rememberTypeHierarchy();
if (parentBinding.isClass()) {
sourceType.superclass = parentBinding;
// this used to be true, but I think I've fixed it now, decp is done
// at weave time!
// TAG: WeavingMessage DECLARE PARENTS: EXTENDS
// Compiler restriction: Can't do EXTENDS at weave time
// So, only see this message if doing a source compilation
// reportDeclareParentsMessage(WeaveMessage.
// WEAVEMESSAGE_DECLAREPARENTSEXTENDS,sourceType,parent);
} else {
ReferenceBinding[] oldI = sourceType.superInterfaces;
ReferenceBinding[] newI;
if (oldI == null) {
newI = new ReferenceBinding[1];
newI[0] = parentBinding;
} else {
int n = oldI.length;
newI = new ReferenceBinding[n + 1];
System.arraycopy(oldI, 0, newI, 0, n);
newI[n] = parentBinding;
}
sourceType.superInterfaces = newI;
// warnOnAddedInterface(factory.fromEclipse(sourceType),parent); //
// now reported at weave time...
// this used to be true, but I think I've fixed it now, decp is done
// at weave time!
// TAG: WeavingMessage DECLARE PARENTS: IMPLEMENTS
// This message will come out of BcelTypeMunger.munge if doing a
// binary weave
// reportDeclareParentsMessage(WeaveMessage.
// WEAVEMESSAGE_DECLAREPARENTSIMPLEMENTS,sourceType,parent);
}
// also add it to the bcel delegate if there is one
if (sourceType instanceof BinaryTypeBinding) {
ResolvedType onType = factory.fromEclipse(sourceType);
ReferenceType rt = (ReferenceType) onType;
ReferenceTypeDelegate rtd = rt.getDelegate();
if (rtd instanceof BcelObjectType) {
rt.addParent(parent);
// ((BcelObjectType) rtd).addParent(parent);
}
}
}
public void warnOnAddedInterface(ResolvedType type, ResolvedType parent) {
World world = factory.getWorld();
ResolvedType serializable = world.getCoreType(UnresolvedType.SERIALIZABLE);
if (serializable.isAssignableFrom(type) && !serializable.isAssignableFrom(parent)
&& !LazyClassGen.hasSerialVersionUIDField(type)) {
world.getLint().needsSerialVersionUIDField.signal(new String[] { type.getName().toString(),
"added interface " + parent.getName().toString() }, null, null);
}
}
private final List pendingTypesToFinish = new ArrayList();
boolean inBinaryTypeCreationAndWeaving = false;
boolean processingTheQueue = false;
public BinaryTypeBinding createBinaryTypeFrom(IBinaryType binaryType, PackageBinding packageBinding,
boolean needFieldsAndMethods, AccessRestriction accessRestriction) {
if (inBinaryTypeCreationAndWeaving) {
BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction);
pendingTypesToFinish.add(ret);
return ret;
}
inBinaryTypeCreationAndWeaving = true;
try {
BinaryTypeBinding ret = super.createBinaryTypeFrom(binaryType, packageBinding, needFieldsAndMethods, accessRestriction);
factory.getWorld().validateType(factory.fromBinding(ret));
// if you need the bytes to pass to validate, here they
// are:((ClassFileReader)binaryType).getReferenceBytes()
weaveInterTypeDeclarations(ret);
return ret;
} finally {
inBinaryTypeCreationAndWeaving = false;
// Start processing the list...
if (pendingTypesToFinish.size() > 0) {
processingTheQueue = true;
while (!pendingTypesToFinish.isEmpty()) {
BinaryTypeBinding nextVictim = (BinaryTypeBinding) pendingTypesToFinish.remove(0);
// During this call we may recurse into this method and add
// more entries to the pendingTypesToFinish list.
weaveInterTypeDeclarations(nextVictim);
}
processingTheQueue = false;
}
}
}
/**
* Callback driven when the compiler detects an anonymous type during block resolution. We need to add it to the weaver so that
* we don't trip up later.
*
* @param aBinding
*/
public void anonymousTypeBindingCreated(LocalTypeBinding aBinding) {
factory.addSourceTypeBinding(aBinding, null);
}
}
// commented out, supplied as info on how to manipulate annotations in an
// eclipse world
//
// public void doDeclareAnnotationOnMethods() {
// Do the declare annotation on fields/methods/ctors
// Collection daoms = factory.getDeclareAnnotationOnMethods();
// if (daoms!=null && daoms.size()>0 && !(sourceType instanceof
// BinaryTypeBinding)) {
// System.err.println("Going through the methods on "+sourceType.debugName()+
// " looking for DECA matches");
// // We better take a look through them...
// for (Iterator iter = daoms.iterator(); iter.hasNext();) {
// DeclareAnnotation element = (DeclareAnnotation) iter.next();
// System.err.println("Looking for anything that might match "+element+" on "+
// sourceType.debugName()+" "+getType(sourceType.
// compoundName).debugName()+" "+(sourceType instanceof BinaryTypeBinding));
//
// ReferenceBinding rbb = getType(sourceType.compoundName);
// // fix me if we ever uncomment this code... should iterate the other way
// round, over the methods then over the decas
// sourceType.methods();
// MethodBinding sourceMbs[] = sourceType.methods;
// for (int i = 0; i < sourceMbs.length; i++) {
// MethodBinding sourceMb = sourceMbs[i];
// MethodBinding mbbbb =
// ((SourceTypeBinding)rbb).getExactMethod(sourceMb.selector
// ,sourceMb.parameters);
// boolean isCtor = sourceMb.selector[0]=='<';
//
// if ((element.isDeclareAtConstuctor() ^ !isCtor)) {
// System.err.println("Checking "+sourceMb+" ... declaringclass="+sourceMb.
// declaringClass.debugName()+" rbb="+rbb.debugName()+" "+
// sourceMb.declaringClass.equals(rbb));
//
// ResolvedMember rm = null;
// rm = EclipseFactory.makeResolvedMember(mbbbb);
// if (element.matches(rm,factory.getWorld())) {
// System.err.println("MATCH");
//
// // Determine the set of annotations that are currently on the method
// ReferenceBinding rb = getType(sourceType.compoundName);
// // TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
// MethodBinding mb =
// ((SourceTypeBinding)rb).getExactMethod(sourceMb.selector,sourceMb
// .parameters);
// //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
// TypeDeclaration typeDecl =
// ((SourceTypeBinding)sourceMb.declaringClass).scope.referenceContext;
// AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
// Annotation[] currentlyHas = methodDecl.annotations; // this is what to add
// //abits = toAdd[0].resolvedType.getAnnotationTagBits();
//
// // Determine the annotations to add to that method
// TypeBinding tb = factory.makeTypeBinding(element.getAspect());
// MethodBinding[] aspectMbs =
// ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod
// ().toCharArray());
// long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
// TypeDeclaration typeDecl2 =
// ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
// AbstractMethodDeclaration methodDecl2 =
// typeDecl2.declarationOf(aspectMbs[0]);
// Annotation[] toAdd = methodDecl2.annotations; // this is what to add
// // abits = toAdd[0].resolvedType.getAnnotationTagBits();
// System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd);
//
// // fix me? should check if it already has the annotation
// //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
// Annotation[] newset = new
// Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
// System.arraycopy(toAdd,0,newset,0,toAdd.length);
// if (currentlyHas!=null) {
// System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
// }
// methodDecl.annotations = newset;
// System.err.println("New set on "+CharOperation.charToString(sourceMb.selector)
// +" is "+newset);
// } else
// System.err.println("NO MATCH");
// }
// }
// }
// }
// }
// commented out, supplied as info on how to manipulate annotations in an
// eclipse world
//
// public void doDeclareAnnotationOnFields() {
// Collection daofs = factory.getDeclareAnnotationOnFields();
// if (daofs!=null && daofs.size()>0 && !(sourceType instanceof
// BinaryTypeBinding)) {
// System.err.println("Going through the fields on "+sourceType.debugName()+
// " looking for DECA matches");
// // We better take a look through them...
// for (Iterator iter = daofs.iterator(); iter.hasNext();) {
// DeclareAnnotation element = (DeclareAnnotation) iter.next();
// System.err.println("Processing deca "+element+" on "+sourceType.debugName()+
// " "+getType(sourceType.compoundName).debugName()+" "
// +(sourceType instanceof BinaryTypeBinding));
//
// ReferenceBinding rbb = getType(sourceType.compoundName);
// // fix me? should iterate the other way round, over the methods then over the
// decas
// sourceType.fields(); // resolve the bloody things
// FieldBinding sourceFbs[] = sourceType.fields;
// for (int i = 0; i < sourceFbs.length; i++) {
// FieldBinding sourceFb = sourceFbs[i];
// //FieldBinding fbbbb =
// ((SourceTypeBinding)rbb).getgetExactMethod(sourceMb.selector
// ,sourceMb.parameters);
//
// System.err.println("Checking "+sourceFb+" ... declaringclass="+sourceFb.
// declaringClass.debugName()+" rbb="+rbb.debugName());
//
// ResolvedMember rm = null;
// rm = EclipseFactory.makeResolvedMember(sourceFb);
// if (element.matches(rm,factory.getWorld())) {
// System.err.println("MATCH");
//
// // Determine the set of annotations that are currently on the field
// ReferenceBinding rb = getType(sourceType.compoundName);
// // TypeBinding tb = factory.makeTypeBinding(decA.getAspect());
// FieldBinding fb = ((SourceTypeBinding)rb).getField(sourceFb.name,true);
// //long abits = mbs[0].getAnnotationTagBits(); // ensure resolved
// TypeDeclaration typeDecl =
// ((SourceTypeBinding)sourceFb.declaringClass).scope.referenceContext;
// FieldDeclaration fd = typeDecl.declarationOf(sourceFb);
// //AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(sourceMb);
// Annotation[] currentlyHas = fd.annotations; // this is what to add
// //abits = toAdd[0].resolvedType.getAnnotationTagBits();
//
// // Determine the annotations to add to that method
// TypeBinding tb = factory.makeTypeBinding(element.getAspect());
// MethodBinding[] aspectMbs =
// ((SourceTypeBinding)tb).getMethods(element.getAnnotationMethod
// ().toCharArray());
// long abits = aspectMbs[0].getAnnotationTagBits(); // ensure resolved
// TypeDeclaration typeDecl2 =
// ((SourceTypeBinding)aspectMbs[0].declaringClass).scope.referenceContext;
// AbstractMethodDeclaration methodDecl2 =
// typeDecl2.declarationOf(aspectMbs[0]);
// Annotation[] toAdd = methodDecl2.annotations; // this is what to add
// // abits = toAdd[0].resolvedType.getAnnotationTagBits();
// System.err.println("Has: "+currentlyHas+" toAdd: "+toAdd);
//
// // fix me? check if it already has the annotation
//
//
// //Annotation abefore[] = sourceType.scope.referenceContext.annotations;
// Annotation[] newset = new
// Annotation[(currentlyHas==null?0:currentlyHas.length)+1];
// System.arraycopy(toAdd,0,newset,0,toAdd.length);
// if (currentlyHas!=null) {
// System.arraycopy(currentlyHas,0,newset,1,currentlyHas.length);
// }
// fd.annotations = newset;
// System.err.println("New set on "+CharOperation.charToString(sourceFb.name)+
// " is "+newset);
// } else
// System.err.println("NO MATCH");
// }
//
// }
// }
| true | true | private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) {
ResolvedType rtx = factory.fromEclipse(sourceType);
if (!decA.matches(rtx)) {
return false;
}
if (!rtx.isExposedToWeaver()) {
return false;
}
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS,
sourceType.sourceName);
// Get the annotation specified in the declare
UnresolvedType aspectType = decA.getAspect();
if (aspectType instanceof ReferenceType) {
ReferenceType rt = (ReferenceType) aspectType;
if (rt.isParameterizedType() || rt.isRawType()) {
aspectType = rt.getGenericType();
}
}
TypeBinding tb = factory.makeTypeBinding(aspectType);
// Hideousness follows:
// There are multiple situations to consider here and they relate to the
// combinations of
// where the annotation is coming from and where the annotation is going
// to be put:
//
// 1. Straight full build, all from source - the annotation is from a
// dec@type and
// is being put on some type. Both types are real SourceTypeBindings.
// WORKS
// 2. Incremental build, changing the affected type - the annotation is
// from a
// dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and
// the
// affected type is a real SourceTypeBinding. Mostly works (pr128665)
// 3. ?
SourceTypeBinding stb = (SourceTypeBinding) tb;
Annotation[] toAdd = null;
long abits = 0;
// Might have to retrieve the annotation through BCEL and construct an
// eclipse one for it.
if (stb instanceof BinaryTypeBinding) {
ReferenceType rt = (ReferenceType) factory.fromEclipse(stb);
ResolvedMember[] methods = rt.getDeclaredMethods();
ResolvedMember decaMethod = null;
String nameToLookFor = decA.getAnnotationMethod();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(nameToLookFor)) {
decaMethod = methods[i];
break;
}
}
if (decaMethod != null) { // could assert this ...
AnnotationAJ[] axs = decaMethod.getAnnotations();
if (axs != null) { // another error has occurred, dont crash here because of it
toAdd = new Annotation[1];
toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory);
// BUG BUG BUG - We dont test these abits are correct, in fact
// we'll be very lucky if they are.
// What does that mean? It means on an incremental compile you
// might get away with an
// annotation that isn't allowed on a type being put on a type.
if (toAdd[0].resolvedType != null) {
abits = toAdd[0].resolvedType.getAnnotationTagBits();
}
}
}
} else if (stb != null) {
// much nicer, its a real SourceTypeBinding so we can stay in
// eclipse land
// if (decA.getAnnotationMethod() != null) {
MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray());
abits = mbs[0].getAnnotationTagBits(); // ensure resolved
TypeDeclaration typeDecl = ((SourceTypeBinding) mbs[0].declaringClass).scope.referenceContext;
AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]);
toAdd = methodDecl.annotations; // this is what to add
toAdd[0] = createAnnotationCopy(toAdd[0]);
if (toAdd[0].resolvedType != null) {
abits = toAdd[0].resolvedType.getAnnotationTagBits();
// }
}
}
// This happens if there is another error in the code - that should be reported separately
if (toAdd == null || toAdd[0] == null || toAdd[0].type == null) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
if (sourceType instanceof BinaryTypeBinding) {
// In this case we can't access the source type binding to add a new
// annotation, so let's put something
// on the weaver type temporarily
ResolvedType theTargetType = factory.fromEclipse(sourceType);
TypeBinding theAnnotationType = toAdd[0].resolvedType;
String sig = new String(theAnnotationType.signature());
UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig);
String name = bcelAnnotationType.getName();
if (theTargetType.hasAnnotation(bcelAnnotationType)) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
// FIXME asc tidy up this code that duplicates whats below!
// Simple checks on the bits
boolean giveupnow = false;
if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) {
// error will have been already reported
giveupnow = true;
} else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
|| (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
if (reportProblems) {
if (decA.isExactPattern()) {
factory.showMessage(IMessage.ERROR, WeaverMessages.format(
WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
stringifyTargets(abits)), decA.getSourceLocation(), null);
}
// dont put out the lint - the weaving process will do
// that
// else {
// if (factory.getWorld().getLint().
// invalidTargetForAnnotation.isEnabled()) {
// factory.getWorld().getLint().invalidTargetForAnnotation
// .signal(new
// String[]{rtx.getName(),toAdd[0].type.toString(),
// stringifyTargets
// (abits)},decA.getSourceLocation(),null);
// }
// }
}
giveupnow = true;
}
}
if (giveupnow) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig,
(abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld()));
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations;
if (currentAnnotations != null) {
for (int i = 0; i < currentAnnotations.length; i++) {
Annotation annotation = currentAnnotations[i];
String a = CharOperation.toString(annotation.type.getTypeName());
String b = CharOperation.toString(toAdd[0].type.getTypeName());
// FIXME asc we have a lint for attempting to add an annotation
// twice to a method,
// we could put it out here *if* we can resolve the problem of
// errors coming out
// multiple times if we have cause to loop through here
if (a.equals(b)) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
}
}
if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) {
// this means it specifies something other than annotation or
// normal type - error will have been already reported,
// just resolution process above
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
|| (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
if (reportProblems) {
if (decA.isExactPattern()) {
factory.showMessage(IMessage.ERROR, WeaverMessages.format(
WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
stringifyTargets(abits)), decA.getSourceLocation(), null);
}
// dont put out the lint - the weaving process will do that
// else {
// if
// (factory.getWorld().getLint().invalidTargetForAnnotation
// .isEnabled()) {
// factory.getWorld().getLint().invalidTargetForAnnotation.
// signal(new
// String[]{rtx.getName(),toAdd[0].type.toString(),
// stringifyTargets(abits)},decA.getSourceLocation(),null);
// }
// }
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
}
// Build a new array of annotations
// remember the current set (rememberAnnotations only does something the
// first time it is called for a type)
sourceType.scope.referenceContext.rememberAnnotations();
// AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(
// decA.getSourceLocation(), rtx.getSourceLocation());
Annotation abefore[] = sourceType.scope.referenceContext.annotations;
Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)];
System.arraycopy(toAdd, 0, newset, 0, toAdd.length);
if (abefore != null) {
System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length);
}
sourceType.scope.referenceContext.annotations = newset;
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
| private boolean doDeclareAnnotations(DeclareAnnotation decA, SourceTypeBinding sourceType, boolean reportProblems) {
ResolvedType rtx = factory.fromEclipse(sourceType);
if (!decA.matches(rtx)) {
return false;
}
if (!rtx.isExposedToWeaver()) {
return false;
}
ContextToken tok = CompilationAndWeavingContext.enteringPhase(CompilationAndWeavingContext.PROCESSING_DECLARE_ANNOTATIONS,
sourceType.sourceName);
// Get the annotation specified in the declare
UnresolvedType aspectType = decA.getAspect();
if (aspectType instanceof ReferenceType) {
ReferenceType rt = (ReferenceType) aspectType;
if (rt.isParameterizedType() || rt.isRawType()) {
aspectType = rt.getGenericType();
}
}
TypeBinding tb = factory.makeTypeBinding(aspectType);
// Hideousness follows:
// There are multiple situations to consider here and they relate to the
// combinations of
// where the annotation is coming from and where the annotation is going
// to be put:
//
// 1. Straight full build, all from source - the annotation is from a
// dec@type and
// is being put on some type. Both types are real SourceTypeBindings.
// WORKS
// 2. Incremental build, changing the affected type - the annotation is
// from a
// dec@type in a BinaryTypeBinding (so has to be accessed via bcel) and
// the
// affected type is a real SourceTypeBinding. Mostly works (pr128665)
// 3. ?
SourceTypeBinding stb = (SourceTypeBinding) tb;
Annotation[] toAdd = null;
long abits = 0;
// Might have to retrieve the annotation through BCEL and construct an
// eclipse one for it.
if (stb instanceof BinaryTypeBinding) {
ReferenceType rt = (ReferenceType) factory.fromEclipse(stb);
ResolvedMember[] methods = rt.getDeclaredMethods();
ResolvedMember decaMethod = null;
String nameToLookFor = decA.getAnnotationMethod();
for (int i = 0; i < methods.length; i++) {
if (methods[i].getName().equals(nameToLookFor)) {
decaMethod = methods[i];
break;
}
}
if (decaMethod != null) { // could assert this ...
AnnotationAJ[] axs = decaMethod.getAnnotations();
if (axs != null) { // another error has occurred, dont crash here because of it
toAdd = new Annotation[1];
toAdd[0] = createAnnotationFromBcelAnnotation(axs[0], decaMethod.getSourceLocation().getOffset(), factory);
// BUG BUG BUG - We dont test these abits are correct, in fact
// we'll be very lucky if they are.
// What does that mean? It means on an incremental compile you
// might get away with an
// annotation that isn't allowed on a type being put on a type.
if (toAdd[0].resolvedType != null) {
abits = toAdd[0].resolvedType.getAnnotationTagBits();
}
}
}
} else if (stb != null) {
// much nicer, its a real SourceTypeBinding so we can stay in
// eclipse land
// if (decA.getAnnotationMethod() != null) {
MethodBinding[] mbs = stb.getMethods(decA.getAnnotationMethod().toCharArray());
abits = mbs[0].getAnnotationTagBits(); // ensure resolved
TypeDeclaration typeDecl = ((SourceTypeBinding) mbs[0].declaringClass).scope.referenceContext;
AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(mbs[0]);
toAdd = methodDecl.annotations; // this is what to add
toAdd[0] = createAnnotationCopy(toAdd[0]);
if (toAdd[0].resolvedType != null) {
abits = toAdd[0].resolvedType.getAnnotationTagBits();
// }
}
}
// This happens if there is another error in the code - that should be reported separately
if (toAdd == null || toAdd[0] == null || toAdd[0].type == null) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
if (sourceType instanceof BinaryTypeBinding) {
// In this case we can't access the source type binding to add a new
// annotation, so let's put something
// on the weaver type temporarily
ResolvedType theTargetType = factory.fromEclipse(sourceType);
TypeBinding theAnnotationType = toAdd[0].resolvedType;
// The annotation type may be null if it could not be resolved (eg. the relevant import has not been added yet)
// In this case an error will be put out about the annotation but not if we crash here
if (theAnnotationType == null) {
return false;
}
String sig = new String(theAnnotationType.signature());
UnresolvedType bcelAnnotationType = UnresolvedType.forSignature(sig);
String name = bcelAnnotationType.getName();
if (theTargetType.hasAnnotation(bcelAnnotationType)) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
// FIXME asc tidy up this code that duplicates whats below!
// Simple checks on the bits
boolean giveupnow = false;
if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
if (isAnnotationTargettingSomethingOtherThanAnnotationOrNormal(abits)) {
// error will have been already reported
giveupnow = true;
} else if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
|| (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
if (reportProblems) {
if (decA.isExactPattern()) {
factory.showMessage(IMessage.ERROR, WeaverMessages.format(
WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
stringifyTargets(abits)), decA.getSourceLocation(), null);
}
// dont put out the lint - the weaving process will do
// that
// else {
// if (factory.getWorld().getLint().
// invalidTargetForAnnotation.isEnabled()) {
// factory.getWorld().getLint().invalidTargetForAnnotation
// .signal(new
// String[]{rtx.getName(),toAdd[0].type.toString(),
// stringifyTargets
// (abits)},decA.getSourceLocation(),null);
// }
// }
}
giveupnow = true;
}
}
if (giveupnow) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
theTargetType.addAnnotation(new BcelAnnotation(new FakeAnnotation(name, sig,
(abits & TagBits.AnnotationRuntimeRetention) != 0), factory.getWorld()));
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
Annotation currentAnnotations[] = sourceType.scope.referenceContext.annotations;
if (currentAnnotations != null) {
for (int i = 0; i < currentAnnotations.length; i++) {
Annotation annotation = currentAnnotations[i];
String a = CharOperation.toString(annotation.type.getTypeName());
String b = CharOperation.toString(toAdd[0].type.getTypeName());
// FIXME asc we have a lint for attempting to add an annotation
// twice to a method,
// we could put it out here *if* we can resolve the problem of
// errors coming out
// multiple times if we have cause to loop through here
if (a.equals(b)) {
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
}
}
if (((abits & TagBits.AnnotationTargetMASK) != 0)) {
if ((abits & (TagBits.AnnotationForAnnotationType | TagBits.AnnotationForType)) == 0) {
// this means it specifies something other than annotation or
// normal type - error will have been already reported,
// just resolution process above
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
if ((sourceType.isAnnotationType() && (abits & TagBits.AnnotationForAnnotationType) == 0)
|| (!sourceType.isAnnotationType() && (abits & TagBits.AnnotationForType) == 0)) {
if (reportProblems) {
if (decA.isExactPattern()) {
factory.showMessage(IMessage.ERROR, WeaverMessages.format(
WeaverMessages.INCORRECT_TARGET_FOR_DECLARE_ANNOTATION, rtx.getName(), toAdd[0].type,
stringifyTargets(abits)), decA.getSourceLocation(), null);
}
// dont put out the lint - the weaving process will do that
// else {
// if
// (factory.getWorld().getLint().invalidTargetForAnnotation
// .isEnabled()) {
// factory.getWorld().getLint().invalidTargetForAnnotation.
// signal(new
// String[]{rtx.getName(),toAdd[0].type.toString(),
// stringifyTargets(abits)},decA.getSourceLocation(),null);
// }
// }
}
CompilationAndWeavingContext.leavingPhase(tok);
return false;
}
}
// Build a new array of annotations
// remember the current set (rememberAnnotations only does something the
// first time it is called for a type)
sourceType.scope.referenceContext.rememberAnnotations();
// AsmRelationshipProvider.getDefault().addDeclareAnnotationRelationship(
// decA.getSourceLocation(), rtx.getSourceLocation());
Annotation abefore[] = sourceType.scope.referenceContext.annotations;
Annotation[] newset = new Annotation[toAdd.length + (abefore == null ? 0 : abefore.length)];
System.arraycopy(toAdd, 0, newset, 0, toAdd.length);
if (abefore != null) {
System.arraycopy(abefore, 0, newset, toAdd.length, abefore.length);
}
sourceType.scope.referenceContext.annotations = newset;
CompilationAndWeavingContext.leavingPhase(tok);
return true;
}
|
diff --git a/app/controllers/BaseService.java b/app/controllers/BaseService.java
index 672dae2..ecfff20 100644
--- a/app/controllers/BaseService.java
+++ b/app/controllers/BaseService.java
@@ -1,29 +1,29 @@
package controllers;
import play.Play;
import play.mvc.Controller;
import controllers.response.Ok;
import controllers.response.TodoMal;
import flexjson.JSONSerializer;
public class BaseService extends Controller {
public static final String CHUNK_SEPARATOR = Play.configuration.getProperty("chunk.separator");
public static final String CHUNK_FOR_REGISTER_SEPARATOR = Play.configuration.getProperty("chunk.registration.separator");
public static JSONSerializer serializer = new JSONSerializer();
static {
}
protected static void jsonOk(Object obj) {
- String result = serializer.serialize(new Ok(obj));
+ String result = serializer.include("userCachos").serialize(obj);
play.Logger.info("result: %s", result);
- renderJSON(serializer.serialize(obj));
+ renderJSON(serializer.include("userCachos").serialize(obj));
}
protected static void jsonError(Object obj) {
renderJSON(serializer.serialize(new TodoMal(obj)));
}
}
| false | true | protected static void jsonOk(Object obj) {
String result = serializer.serialize(new Ok(obj));
play.Logger.info("result: %s", result);
renderJSON(serializer.serialize(obj));
}
| protected static void jsonOk(Object obj) {
String result = serializer.include("userCachos").serialize(obj);
play.Logger.info("result: %s", result);
renderJSON(serializer.include("userCachos").serialize(obj));
}
|
diff --git a/moho-remote/src/main/java/com/voxeo/moho/remote/impl/MohoRemoteImpl.java b/moho-remote/src/main/java/com/voxeo/moho/remote/impl/MohoRemoteImpl.java
index 310aa780..5796a73e 100644
--- a/moho-remote/src/main/java/com/voxeo/moho/remote/impl/MohoRemoteImpl.java
+++ b/moho-remote/src/main/java/com/voxeo/moho/remote/impl/MohoRemoteImpl.java
@@ -1,198 +1,200 @@
package com.voxeo.moho.remote.impl;
import java.net.URI;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import com.rayo.client.RayoClient;
import com.rayo.client.XmppException;
import com.rayo.client.listener.StanzaListener;
import com.rayo.client.xmpp.stanza.IQ;
import com.rayo.client.xmpp.stanza.Message;
import com.rayo.client.xmpp.stanza.Presence;
import com.rayo.core.OfferEvent;
import com.voxeo.moho.CallableEndpoint;
import com.voxeo.moho.Participant;
import com.voxeo.moho.common.event.DispatchableEventSource;
import com.voxeo.moho.common.util.Utils.DaemonThreadFactory;
import com.voxeo.moho.remote.AuthenticationCallback;
import com.voxeo.moho.remote.MohoRemote;
import com.voxeo.moho.remote.MohoRemoteException;
@SuppressWarnings("deprecation")
public class MohoRemoteImpl extends DispatchableEventSource implements MohoRemote {
protected static final Logger LOG = Logger.getLogger(MohoRemoteImpl.class);
protected RayoClient _client;
protected ThreadPoolExecutor _executor;
protected Map<String, ParticipantImpl> _participants = new ConcurrentHashMap<String, ParticipantImpl>();
protected Lock _participanstLock = new ReentrantLock();
public MohoRemoteImpl() {
super();
// TODO make configurable
int eventDispatcherThreadPoolSize = 10;
_executor = new ThreadPoolExecutor(eventDispatcherThreadPoolSize, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), new DaemonThreadFactory("MohoContext"));
_dispatcher.setExecutor(_executor, false);
}
@Override
public void disconnect() throws MohoRemoteException {
Collection<ParticipantImpl> participants = _participants.values();
for (Participant participant : participants) {
participant.disconnect();
}
try {
_client.disconnect();
}
catch (XmppException e) {
throw new MohoRemoteException(e);
}
_executor.shutdown();
}
//TODO ask Rayo-client thread model, figure out all possible concurrent issue
class MohoStanzaListener implements StanzaListener {
@Override
public void onIQ(IQ iq) {
if (iq.getFrom() != null) {
// dispatch the stanza to corresponding participant.
JID fromJID = new JID(iq.getFrom());
String id = fromJID.getNode();
if (id != null) {
ParticipantImpl participant = MohoRemoteImpl.this.getParticipant(id);
if (participant != null) {
participant.onRayoCommandResult(fromJID, iq);
}
else {
LOG.error("Can't find call for rayo event:" + iq);
}
}
}
}
@Override
public void onMessage(Message message) {
LOG.error("Received message from rayo:" + message);
}
@Override
public void onPresence(Presence presence) {
JID fromJID = new JID(presence.getFrom());
if (!presence.hasExtension()) {
return;
}
if (presence.getExtension().getStanzaName().equalsIgnoreCase("offer")) {
OfferEvent offerEvent = (OfferEvent) presence.getExtension().getObject();
IncomingCallImpl call = new IncomingCallImpl(MohoRemoteImpl.this, fromJID.getNode(),
createEndpoint(offerEvent.getFrom()), createEndpoint(offerEvent.getTo()), offerEvent.getHeaders());
MohoRemoteImpl.this.dispatch(call);
}
else {
// dispatch the stanza to corresponding participant.
String callID = fromJID.getNode();
ParticipantImpl participant = MohoRemoteImpl.this.getParticipant(callID);
if (participant != null) {
participant.onRayoEvent(fromJID, presence);
}
else {
- LOG.error("Can't find call for rayo event:" + presence);
+ if (presence.getShow() == null) {
+ LOG.error("Can't find call for rayo event:" + presence);
+ }
}
}
}
@Override
public void onError(com.rayo.client.xmpp.stanza.Error error) {
LOG.error("Got error" + error);
}
}
@Override
public ParticipantImpl getParticipant(final String cid) {
getParticipantsLock().lock();
try {
return _participants.get(cid);
}
finally {
getParticipantsLock().unlock();
}
}
protected void addParticipant(final ParticipantImpl participant) {
_participants.put(participant.getId(), participant);
}
protected void removeParticipant(final String id) {
getParticipantsLock().lock();
try {
_participants.remove(id);
}
finally {
getParticipantsLock().unlock();
}
}
public Lock getParticipantsLock() {
return _participanstLock;
}
// TODO connection error handling, ask
@Override
public void connect(AuthenticationCallback callback, String xmppServer, String rayoServer) {
connect(callback.getUserName(), callback.getPassword(), callback.getRealm(), callback.getResource(), xmppServer,
rayoServer);
}
@Override
public void connect(String userName, String passwd, String realm, String resource, String xmppServer,
String rayoServer) throws MohoRemoteException {
connect(userName, passwd, realm, resource, xmppServer, rayoServer, 5);
}
@Override
public void connect(String userName, String passwd, String realm, String resource, String xmppServer,
String rayoServer, int timeout) throws MohoRemoteException {
if (_client == null) {
_client = new RayoClient(xmppServer, rayoServer);
_client.addStanzaListener(new MohoStanzaListener());
}
try {
_client.connect(userName, passwd, resource, timeout);
}
catch (XmppException e) {
LOG.error("Error connecting server", e);
}
}
@Override
public CallableEndpoint createEndpoint(URI uri) {
return new CallableEndpointImpl(this, uri);
}
public Executor getExecutor() {
return _executor;
}
public RayoClient getRayoClient() {
return _client;
}
}
| true | true | public void onPresence(Presence presence) {
JID fromJID = new JID(presence.getFrom());
if (!presence.hasExtension()) {
return;
}
if (presence.getExtension().getStanzaName().equalsIgnoreCase("offer")) {
OfferEvent offerEvent = (OfferEvent) presence.getExtension().getObject();
IncomingCallImpl call = new IncomingCallImpl(MohoRemoteImpl.this, fromJID.getNode(),
createEndpoint(offerEvent.getFrom()), createEndpoint(offerEvent.getTo()), offerEvent.getHeaders());
MohoRemoteImpl.this.dispatch(call);
}
else {
// dispatch the stanza to corresponding participant.
String callID = fromJID.getNode();
ParticipantImpl participant = MohoRemoteImpl.this.getParticipant(callID);
if (participant != null) {
participant.onRayoEvent(fromJID, presence);
}
else {
LOG.error("Can't find call for rayo event:" + presence);
}
}
}
| public void onPresence(Presence presence) {
JID fromJID = new JID(presence.getFrom());
if (!presence.hasExtension()) {
return;
}
if (presence.getExtension().getStanzaName().equalsIgnoreCase("offer")) {
OfferEvent offerEvent = (OfferEvent) presence.getExtension().getObject();
IncomingCallImpl call = new IncomingCallImpl(MohoRemoteImpl.this, fromJID.getNode(),
createEndpoint(offerEvent.getFrom()), createEndpoint(offerEvent.getTo()), offerEvent.getHeaders());
MohoRemoteImpl.this.dispatch(call);
}
else {
// dispatch the stanza to corresponding participant.
String callID = fromJID.getNode();
ParticipantImpl participant = MohoRemoteImpl.this.getParticipant(callID);
if (participant != null) {
participant.onRayoEvent(fromJID, presence);
}
else {
if (presence.getShow() == null) {
LOG.error("Can't find call for rayo event:" + presence);
}
}
}
}
|
diff --git a/src/main/java/org/theider/plugin/templates/DeploymentSaxHandler.java b/src/main/java/org/theider/plugin/templates/DeploymentSaxHandler.java
index 121737c..59f9fc9 100644
--- a/src/main/java/org/theider/plugin/templates/DeploymentSaxHandler.java
+++ b/src/main/java/org/theider/plugin/templates/DeploymentSaxHandler.java
@@ -1,150 +1,150 @@
package org.theider.plugin.templates;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
*
* @author Tim
*/
public class DeploymentSaxHandler extends DefaultHandler {
private Deployment deployment = null;
private TemplateMapping templateMapping;
public Deployment getDeployment() {
return deployment;
}
public static Deployment getDeployment(InputStream in) throws IOException {
try {
DeploymentSaxHandler handler = new DeploymentSaxHandler();
// Obtain a new instance of a SAXParserFactory.
SAXParserFactory factory = SAXParserFactory.newInstance();
// Specifies that the parser produced by this code will provide support for XML namespaces.
factory.setNamespaceAware(false);
// Specifies that the parser produced by this code will validate documents as they are parsed.
factory.setValidating(false);
// Creates a new instance of a SAXParser using the currently configured factory parameters.
SAXParser saxParser = factory.newSAXParser();
InputSource ins = new InputSource(in);
saxParser.parse(ins, handler);
return handler.getDeployment();
} catch (ParserConfigurationException ex) {
throw new IOException("error loading deployment descriptor",ex);
} catch (SAXException ex) {
throw new IOException("error loading deployment descriptor",ex);
}
}
protected enum ParserState {
DEPLOYMENT,
BODY,
TEMPLATE_BODY,
TEMPLATE_SOURCE,
FOLDER_BODY,
DESTINATION_PATH;
};
private ParserState parserState = ParserState.DEPLOYMENT;
private boolean destFileExecutable;
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
String data = new String(ch,start,length);
switch(parserState) {
case TEMPLATE_SOURCE:
templateMapping.setTemplateFilename(data);
break;
case DESTINATION_PATH:
templateMapping.setDestinationFilename(data);
break;
case FOLDER_BODY:
deployment.getFolderNames().add(data);
break;
}
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch(parserState) {
case DEPLOYMENT:
if(!qName.equals("deployment")) {
throw new SAXException("expecting root node to be deployment");
}
deployment = new Deployment();
parserState = ParserState.BODY;
break;
case BODY:
if(qName.equals("template")) {
templateMapping = new TemplateMapping();
parserState = ParserState.TEMPLATE_BODY;
} else if(qName.equals("folder")) {
parserState = ParserState.FOLDER_BODY;
} else {
throw new SAXException("expecting folder or template node and got " + qName);
}
break;
case TEMPLATE_BODY:
if(qName.equals("template-filename")) {
// template source
parserState = ParserState.TEMPLATE_SOURCE;
} else
if(qName.equals("destination-filename")) {
parserState = ParserState.DESTINATION_PATH;
destFileExecutable = false;
String execFile = attributes.getValue("executable");
if(execFile != null) {
destFileExecutable = execFile.equalsIgnoreCase("true");
}
} else {
- throw new SAXException("expecting root node to be deployment");
+ throw new SAXException("expecting template-filename or destination-filename nodes (got " + qName + ")");
}
break;
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
switch(parserState) {
case TEMPLATE_SOURCE:
parserState = ParserState.TEMPLATE_BODY;
break;
case DESTINATION_PATH:
parserState = ParserState.TEMPLATE_BODY;
break;
case FOLDER_BODY:
if(qName.equals("folder")) {
parserState = ParserState.BODY;
} else {
throw new SAXException("missing end folder tag");
}
case TEMPLATE_BODY:
if(qName.equals("template")) {
if(templateMapping.getDestinationFilename() == null) {
throw new SAXException("template mapping is missing destination path");
}
if(templateMapping.getTemplateFilename() == null) {
throw new SAXException("template mapping is missing template source");
}
templateMapping.setExecutable(destFileExecutable);
deployment.getTemplateMappings().add(templateMapping);
parserState = ParserState.BODY;
}
break;
}
}
}
| true | true | public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch(parserState) {
case DEPLOYMENT:
if(!qName.equals("deployment")) {
throw new SAXException("expecting root node to be deployment");
}
deployment = new Deployment();
parserState = ParserState.BODY;
break;
case BODY:
if(qName.equals("template")) {
templateMapping = new TemplateMapping();
parserState = ParserState.TEMPLATE_BODY;
} else if(qName.equals("folder")) {
parserState = ParserState.FOLDER_BODY;
} else {
throw new SAXException("expecting folder or template node and got " + qName);
}
break;
case TEMPLATE_BODY:
if(qName.equals("template-filename")) {
// template source
parserState = ParserState.TEMPLATE_SOURCE;
} else
if(qName.equals("destination-filename")) {
parserState = ParserState.DESTINATION_PATH;
destFileExecutable = false;
String execFile = attributes.getValue("executable");
if(execFile != null) {
destFileExecutable = execFile.equalsIgnoreCase("true");
}
} else {
throw new SAXException("expecting root node to be deployment");
}
break;
}
}
| public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
switch(parserState) {
case DEPLOYMENT:
if(!qName.equals("deployment")) {
throw new SAXException("expecting root node to be deployment");
}
deployment = new Deployment();
parserState = ParserState.BODY;
break;
case BODY:
if(qName.equals("template")) {
templateMapping = new TemplateMapping();
parserState = ParserState.TEMPLATE_BODY;
} else if(qName.equals("folder")) {
parserState = ParserState.FOLDER_BODY;
} else {
throw new SAXException("expecting folder or template node and got " + qName);
}
break;
case TEMPLATE_BODY:
if(qName.equals("template-filename")) {
// template source
parserState = ParserState.TEMPLATE_SOURCE;
} else
if(qName.equals("destination-filename")) {
parserState = ParserState.DESTINATION_PATH;
destFileExecutable = false;
String execFile = attributes.getValue("executable");
if(execFile != null) {
destFileExecutable = execFile.equalsIgnoreCase("true");
}
} else {
throw new SAXException("expecting template-filename or destination-filename nodes (got " + qName + ")");
}
break;
}
}
|
diff --git a/web/src/sirius/web/services/ServiceCall.java b/web/src/sirius/web/services/ServiceCall.java
index 1762bc3..97552a1 100644
--- a/web/src/sirius/web/services/ServiceCall.java
+++ b/web/src/sirius/web/services/ServiceCall.java
@@ -1,89 +1,89 @@
package sirius.web.services;
import sirius.kernel.async.CallContext;
import sirius.kernel.commons.Strings;
import sirius.kernel.commons.Value;
import sirius.kernel.health.Exceptions;
import sirius.kernel.health.HandledException;
import sirius.kernel.health.Log;
import sirius.kernel.xml.StructuredOutput;
import sirius.web.http.WebContext;
import java.util.Arrays;
/**
* Created with IntelliJ IDEA.
* User: aha
* Date: 27.07.13
* Time: 12:24
* To change this template use File | Settings | File Templates.
*/
public abstract class ServiceCall {
protected static Log LOG = Log.get("services");
protected WebContext ctx;
public ServiceCall(WebContext ctx) {
this.ctx = ctx;
}
public void handle(String errorCode, Throwable error) {
HandledException he = Exceptions.handle(LOG, error);
StructuredOutput out = createOutput();
out.beginResult("error");
out.property("success", false);
out.property("message", he.getMessage());
Throwable cause = error.getCause();
- while (cause != null && !cause.getCause().equals(cause)) {
+ while (cause != null && cause.getCause() != null && !cause.getCause().equals(cause)) {
cause = cause.getCause();
}
if (cause == null) {
cause = error;
}
out.property("type", cause.getClass().getName());
if (Strings.isFilled(errorCode)) {
out.property("code", errorCode);
}
out.property("flow", CallContext.getCurrent().getMDCValue(CallContext.MDC_FLOW));
out.endResult();
}
public WebContext getContext() {
return ctx;
}
public Value get(String... keys) {
for (String key : keys) {
Value result = ctx.get(key);
if (result.isFilled()) {
return result;
}
}
return Value.of(null);
}
public Value require(String... keys) {
for (String key : keys) {
Value result = ctx.get(key);
if (result.isFilled()) {
return result;
}
}
throw Exceptions.createHandled()
.withSystemErrorMessage(
"A required parameter was not filled. Provide at least one value for: %s",
Arrays.asList(keys))
.handle();
}
public void invoke(StructuredService serv) {
try {
serv.call(this, createOutput());
} catch (Throwable t) {
handle(null, t);
}
}
protected abstract StructuredOutput createOutput();
}
| true | true | public void handle(String errorCode, Throwable error) {
HandledException he = Exceptions.handle(LOG, error);
StructuredOutput out = createOutput();
out.beginResult("error");
out.property("success", false);
out.property("message", he.getMessage());
Throwable cause = error.getCause();
while (cause != null && !cause.getCause().equals(cause)) {
cause = cause.getCause();
}
if (cause == null) {
cause = error;
}
out.property("type", cause.getClass().getName());
if (Strings.isFilled(errorCode)) {
out.property("code", errorCode);
}
out.property("flow", CallContext.getCurrent().getMDCValue(CallContext.MDC_FLOW));
out.endResult();
}
| public void handle(String errorCode, Throwable error) {
HandledException he = Exceptions.handle(LOG, error);
StructuredOutput out = createOutput();
out.beginResult("error");
out.property("success", false);
out.property("message", he.getMessage());
Throwable cause = error.getCause();
while (cause != null && cause.getCause() != null && !cause.getCause().equals(cause)) {
cause = cause.getCause();
}
if (cause == null) {
cause = error;
}
out.property("type", cause.getClass().getName());
if (Strings.isFilled(errorCode)) {
out.property("code", errorCode);
}
out.property("flow", CallContext.getCurrent().getMDCValue(CallContext.MDC_FLOW));
out.endResult();
}
|
diff --git a/src/be/ibridge/kettle/trans/step/fileinput/FileInputList.java b/src/be/ibridge/kettle/trans/step/fileinput/FileInputList.java
index 73c39f29..e8654b82 100644
--- a/src/be/ibridge/kettle/trans/step/fileinput/FileInputList.java
+++ b/src/be/ibridge/kettle/trans/step/fileinput/FileInputList.java
@@ -1,410 +1,412 @@
package be.ibridge.kettle.trans.step.fileinput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.vfs.AllFileSelector;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSelectInfo;
import org.apache.commons.vfs.FileType;
import be.ibridge.kettle.core.Const;
import be.ibridge.kettle.core.LogWriter;
import be.ibridge.kettle.core.util.StringUtil;
import be.ibridge.kettle.core.vfs.KettleVFS;
public class FileInputList
{
private List files = new ArrayList();
private List nonExistantFiles = new ArrayList(1);
private List nonAccessibleFiles = new ArrayList(1);
private static final String YES = "Y";
public static String getRequiredFilesDescription(List nonExistantFiles)
{
StringBuffer buffer = new StringBuffer();
for (Iterator iter = nonExistantFiles.iterator(); iter.hasNext();)
{
FileObject file = (FileObject) iter.next();
buffer.append(file.getName().getURI());
buffer.append(Const.CR);
}
return buffer.toString();
}
private static boolean[] includeSubdirsFalse(int iLength)
{
boolean[] includeSubdirs = new boolean[iLength];
for (int i = 0; i < iLength; i++)
includeSubdirs[i] = false;
return includeSubdirs;
}
public static String[] createFilePathList(String[] fileName, String[] fileMask, String[] fileRequired)
{
boolean[] includeSubdirs = includeSubdirsFalse(fileName.length);
return createFilePathList(fileName, fileMask, fileRequired, includeSubdirs);
}
public static String[] createFilePathList(String[] fileName, String[] fileMask, String[] fileRequired,
boolean[] includeSubdirs)
{
List fileList = createFileList(fileName, fileMask, fileRequired, includeSubdirs).getFiles();
String[] filePaths = new String[fileList.size()];
for (int i = 0; i < filePaths.length; i++)
{
filePaths[i] = ((FileObject) fileList.get(i)).getName().getURI();
// filePaths[i] = KettleVFS.getFilename((FileObject) fileList.get(i));
}
return filePaths;
}
public static FileInputList createFileList(String[] fileName, String[] fileMask, String[] fileRequired)
{
boolean[] includeSubdirs = includeSubdirsFalse(fileName.length);
return createFileList(fileName, fileMask, fileRequired, includeSubdirs);
}
public static FileInputList createFileList(String[] fileName, String[] fileMask, String[] fileRequired, boolean[] includeSubdirs)
{
FileInputList fileInputList = new FileInputList();
// Replace possible environment variables...
final String realfile[] = StringUtil.environmentSubstitute(fileName);
final String realmask[] = StringUtil.environmentSubstitute(fileMask);
for (int i = 0; i < realfile.length; i++)
{
final String onefile = realfile[i];
final String onemask = realmask[i];
final boolean onerequired = YES.equalsIgnoreCase(fileRequired[i]);
final boolean subdirs = includeSubdirs[i];
if (Const.isEmpty(onefile)) continue;
//
// If a wildcard is set we search for files
//
if (!Const.isEmpty(onemask))
{
try
{
// Find all file names that match the wildcard in this directory
//
FileObject directoryFileObject = KettleVFS.getFileObject(onefile);
if (directoryFileObject != null && directoryFileObject.getType() == FileType.FOLDER) // it's a directory
{
FileObject[] fileObjects = directoryFileObject.findFiles(
new AllFileSelector()
{
public boolean traverseDescendents(FileSelectInfo info)
{
return info.getDepth()==0 || subdirs;
}
public boolean includeFile(FileSelectInfo info)
{
String name = info.getFile().getName().getBaseName();
boolean matches = Pattern.matches(onemask, name);
+ /*
if (matches)
{
System.out.println("File match: URI: "+info.getFile()+", name="+name+", depth="+info.getDepth());
}
+ */
return matches;
}
}
);
if (fileObjects != null)
{
for (int j = 0; j < fileObjects.length; j++)
{
if (fileObjects[j].exists()) fileInputList.addFile(fileObjects[j]);
}
}
if (Const.isEmpty(fileObjects))
{
if (onerequired) fileInputList.addNonAccessibleFile(directoryFileObject);
}
// Sort the list: quicksort, only for regular files
fileInputList.sortFiles();
}
else
{
FileObject[] children = directoryFileObject.getChildren();
for (int j = 0; j < children.length; j++)
{
// See if the wildcard (regexp) matches...
String name = children[j].getName().getBaseName();
if (Pattern.matches(onemask, name)) fileInputList.addFile(children[j]);
}
// We don't sort here, keep the order of the files in the archive.
}
}
catch (Exception e)
{
LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
}
}
else
// A normal file...
{
try
{
FileObject fileObject = KettleVFS.getFileObject(onefile);
if (fileObject.exists())
{
if (fileObject.isReadable())
{
fileInputList.addFile(fileObject);
}
else
{
if (onerequired) fileInputList.addNonAccessibleFile(fileObject);
}
}
else
{
if (onerequired) fileInputList.addNonExistantFile(fileObject);
}
}
catch (Exception e)
{
LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
}
}
}
return fileInputList;
}
/*
public static FileInputList createFileList(String[] fileName, String[] fileMask, String[] fileRequired, boolean[] includeSubdirs)
{
FileInputList fileInputList = new FileInputList();
// Replace possible environment variables...
final String realfile[] = StringUtil.environmentSubstitute(fileName);
final String realmask[] = StringUtil.environmentSubstitute(fileMask);
for (int i = 0; i < realfile.length; i++)
{
final String onefile = realfile[i];
final String onemask = realmask[i];
final boolean onerequired = YES.equalsIgnoreCase(fileRequired[i]);
boolean subdirs = includeSubdirs[i];
// System.out.println("Checking file ["+onefile+"] mask
// ["+onemask+"]");
if (onefile == null) continue;
if (!Const.isEmpty(onemask))
// If wildcard is set we assume it's a directory
{
File file = new File(onefile);
try
{
// Find all file names that match the wildcard in this directory
String[] fileNames = file.list(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return Pattern.matches(onemask, name);
}
});
if (subdirs)
{
Vector matchingFilenames = new Vector();
appendToVector(matchingFilenames, fileNames, "");
findMatchingFiles(file, onemask, matchingFilenames, "");
fileNames = new String[matchingFilenames.size()];
matchingFilenames.copyInto(fileNames);
}
if (fileNames != null)
{
for (int j = 0; j < fileNames.length; j++)
{
File localFile = new File(file, fileNames[j]);
if (!localFile.isDirectory() && localFile.isFile()) fileInputList.addFile(localFile);
}
}
if (Const.isEmpty(fileNames))
{
if (onerequired) fileInputList.addNonAccessibleFile(file);
}
}
catch (Exception e)
{
LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
}
}
else
// A normal file...
{
File file = new File(onefile);
if (file.exists())
{
if (file.canRead() && file.isFile())
{
if (file.isFile()) fileInputList.addFile(file);
}
else
{
if (onerequired) fileInputList.addNonAccessibleFile(file);
}
}
else
{
if (onerequired) fileInputList.addNonExistantFile(file);
}
}
}
// Sort the list: quicksort
fileInputList.sortFiles();
// OK, return the list in filelist...
// files = (String[]) filelist.toArray(new String[filelist.size()]);
return fileInputList;
}
*/
/*
* Copies all elements of a String array into a Vector
* @param sArray The string array
* @param sPrefix the prefix to put before all strings to be copied to the vector
* @return The Vector.
private static void appendToVector(Vector v, String[] sArray, String sPrefix)
{
if (sArray == null || sArray.length == 0)
return;
for (int i = 0; i < sArray.length; i++)
v.add(sPrefix + sArray[i]);
}
*/
/*
private static void appendToVector(Vector v, String[] sArray, String sPrefix)
{
if (sArray == null || sArray.length == 0)
return;
for (int i = 0; i < sArray.length; i++)
v.add(sPrefix + sArray[i]);
}
*/
/*
*
* @param dir
* @param onemask
* @param matchingFileNames
* @param sPrefix
private static void findMatchingFiles(File dir, final String onemask, Vector matchingFileNames, String sPrefix)
{
if (!Const.isEmpty(sPrefix))
{
String[] fileNames = dir.list(new FilenameFilter()
{
public boolean accept(File dir, String name)
{
return Pattern.matches(onemask, name);
}
});
appendToVector(matchingFileNames, fileNames, sPrefix);
}
String[] files = dir.list();
for (int i = 0; i < files.length; i++)
{
File f = new File(dir.getAbsolutePath() + Const.FILE_SEPARATOR + files[i]);
if (f.isDirectory())
{
findMatchingFiles(f, onemask, matchingFileNames, sPrefix + files[i] + Const.FILE_SEPARATOR);
}
}
}
*/
public List getFiles()
{
return files;
}
public String[] getFileStrings()
{
String[] fileStrings = new String[files.size()];
for (int i=0;i<fileStrings.length;i++)
{
fileStrings[i] = KettleVFS.getFilename((FileObject) files.get(i));
}
return fileStrings;
}
public List getNonAccessibleFiles()
{
return nonAccessibleFiles;
}
public List getNonExistantFiles()
{
return nonExistantFiles;
}
public void addFile(FileObject file)
{
files.add(file);
}
public void addNonAccessibleFile(FileObject file)
{
nonAccessibleFiles.add(file);
}
public void addNonExistantFile(FileObject file)
{
nonExistantFiles.add(file);
}
public void sortFiles()
{
Collections.sort(files, KettleVFS.getComparator());
Collections.sort(nonAccessibleFiles, KettleVFS.getComparator());
Collections.sort(nonExistantFiles, KettleVFS.getComparator());
}
/*
private boolean containsComparable(List list)
{
if (list == null || list.size() == 0)
return false;
return (list.get(0) instanceof Comparable);
}
*/
public FileObject getFile(int i)
{
return (FileObject) files.get(i);
}
public int nrOfFiles()
{
return files.size();
}
public int nrOfMissingFiles()
{
return nonAccessibleFiles.size() + nonExistantFiles.size();
}
}
| false | true | public static FileInputList createFileList(String[] fileName, String[] fileMask, String[] fileRequired, boolean[] includeSubdirs)
{
FileInputList fileInputList = new FileInputList();
// Replace possible environment variables...
final String realfile[] = StringUtil.environmentSubstitute(fileName);
final String realmask[] = StringUtil.environmentSubstitute(fileMask);
for (int i = 0; i < realfile.length; i++)
{
final String onefile = realfile[i];
final String onemask = realmask[i];
final boolean onerequired = YES.equalsIgnoreCase(fileRequired[i]);
final boolean subdirs = includeSubdirs[i];
if (Const.isEmpty(onefile)) continue;
//
// If a wildcard is set we search for files
//
if (!Const.isEmpty(onemask))
{
try
{
// Find all file names that match the wildcard in this directory
//
FileObject directoryFileObject = KettleVFS.getFileObject(onefile);
if (directoryFileObject != null && directoryFileObject.getType() == FileType.FOLDER) // it's a directory
{
FileObject[] fileObjects = directoryFileObject.findFiles(
new AllFileSelector()
{
public boolean traverseDescendents(FileSelectInfo info)
{
return info.getDepth()==0 || subdirs;
}
public boolean includeFile(FileSelectInfo info)
{
String name = info.getFile().getName().getBaseName();
boolean matches = Pattern.matches(onemask, name);
if (matches)
{
System.out.println("File match: URI: "+info.getFile()+", name="+name+", depth="+info.getDepth());
}
return matches;
}
}
);
if (fileObjects != null)
{
for (int j = 0; j < fileObjects.length; j++)
{
if (fileObjects[j].exists()) fileInputList.addFile(fileObjects[j]);
}
}
if (Const.isEmpty(fileObjects))
{
if (onerequired) fileInputList.addNonAccessibleFile(directoryFileObject);
}
// Sort the list: quicksort, only for regular files
fileInputList.sortFiles();
}
else
{
FileObject[] children = directoryFileObject.getChildren();
for (int j = 0; j < children.length; j++)
{
// See if the wildcard (regexp) matches...
String name = children[j].getName().getBaseName();
if (Pattern.matches(onemask, name)) fileInputList.addFile(children[j]);
}
// We don't sort here, keep the order of the files in the archive.
}
}
catch (Exception e)
{
LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
}
}
else
// A normal file...
{
try
{
FileObject fileObject = KettleVFS.getFileObject(onefile);
if (fileObject.exists())
{
if (fileObject.isReadable())
{
fileInputList.addFile(fileObject);
}
else
{
if (onerequired) fileInputList.addNonAccessibleFile(fileObject);
}
}
else
{
if (onerequired) fileInputList.addNonExistantFile(fileObject);
}
}
catch (Exception e)
{
LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
}
}
}
return fileInputList;
}
| public static FileInputList createFileList(String[] fileName, String[] fileMask, String[] fileRequired, boolean[] includeSubdirs)
{
FileInputList fileInputList = new FileInputList();
// Replace possible environment variables...
final String realfile[] = StringUtil.environmentSubstitute(fileName);
final String realmask[] = StringUtil.environmentSubstitute(fileMask);
for (int i = 0; i < realfile.length; i++)
{
final String onefile = realfile[i];
final String onemask = realmask[i];
final boolean onerequired = YES.equalsIgnoreCase(fileRequired[i]);
final boolean subdirs = includeSubdirs[i];
if (Const.isEmpty(onefile)) continue;
//
// If a wildcard is set we search for files
//
if (!Const.isEmpty(onemask))
{
try
{
// Find all file names that match the wildcard in this directory
//
FileObject directoryFileObject = KettleVFS.getFileObject(onefile);
if (directoryFileObject != null && directoryFileObject.getType() == FileType.FOLDER) // it's a directory
{
FileObject[] fileObjects = directoryFileObject.findFiles(
new AllFileSelector()
{
public boolean traverseDescendents(FileSelectInfo info)
{
return info.getDepth()==0 || subdirs;
}
public boolean includeFile(FileSelectInfo info)
{
String name = info.getFile().getName().getBaseName();
boolean matches = Pattern.matches(onemask, name);
/*
if (matches)
{
System.out.println("File match: URI: "+info.getFile()+", name="+name+", depth="+info.getDepth());
}
*/
return matches;
}
}
);
if (fileObjects != null)
{
for (int j = 0; j < fileObjects.length; j++)
{
if (fileObjects[j].exists()) fileInputList.addFile(fileObjects[j]);
}
}
if (Const.isEmpty(fileObjects))
{
if (onerequired) fileInputList.addNonAccessibleFile(directoryFileObject);
}
// Sort the list: quicksort, only for regular files
fileInputList.sortFiles();
}
else
{
FileObject[] children = directoryFileObject.getChildren();
for (int j = 0; j < children.length; j++)
{
// See if the wildcard (regexp) matches...
String name = children[j].getName().getBaseName();
if (Pattern.matches(onemask, name)) fileInputList.addFile(children[j]);
}
// We don't sort here, keep the order of the files in the archive.
}
}
catch (Exception e)
{
LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
}
}
else
// A normal file...
{
try
{
FileObject fileObject = KettleVFS.getFileObject(onefile);
if (fileObject.exists())
{
if (fileObject.isReadable())
{
fileInputList.addFile(fileObject);
}
else
{
if (onerequired) fileInputList.addNonAccessibleFile(fileObject);
}
}
else
{
if (onerequired) fileInputList.addNonExistantFile(fileObject);
}
}
catch (Exception e)
{
LogWriter.getInstance().logError("FileInputList", Const.getStackTracker(e));
}
}
}
return fileInputList;
}
|
diff --git a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityLiquiCrafter.java b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityLiquiCrafter.java
index df479557..cd41dc4c 100644
--- a/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityLiquiCrafter.java
+++ b/src/powercrystals/minefactoryreloaded/tile/machine/TileEntityLiquiCrafter.java
@@ -1,515 +1,515 @@
package powercrystals.minefactoryreloaded.tile.machine;
import java.util.LinkedList;
import java.util.List;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.liquids.ILiquidTank;
import net.minecraftforge.liquids.LiquidContainerRegistry;
import net.minecraftforge.liquids.LiquidStack;
import net.minecraftforge.liquids.LiquidTank;
import powercrystals.core.util.Util;
import powercrystals.minefactoryreloaded.core.ITankContainerBucketable;
import powercrystals.minefactoryreloaded.core.RemoteInventoryCrafting;
import powercrystals.minefactoryreloaded.gui.client.GuiFactoryInventory;
import powercrystals.minefactoryreloaded.gui.client.GuiLiquiCrafter;
import powercrystals.minefactoryreloaded.gui.container.ContainerLiquiCrafter;
import powercrystals.minefactoryreloaded.tile.base.TileEntityFactoryInventory;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
// slots 0-8 craft grid, 9 craft grid template output, 10 output, 11-28 resources
public class TileEntityLiquiCrafter extends TileEntityFactoryInventory implements ITankContainerBucketable
{
private boolean _lastRedstoneState;
private boolean _resourcesChangedSinceLastFailedCraft = true;
private class ItemResourceTracker
{
public ItemResourceTracker(int id, int meta, int required)
{
this.id = id;
this.meta = meta;
this.required = required;
}
public int id;
public int meta;
public int required;
public int found;
}
private LiquidTank[] _tanks = new LiquidTank[9];
public TileEntityLiquiCrafter()
{
for(int i = 0; i < 9; i++)
{
_tanks[i] = new LiquidTank(LiquidContainerRegistry.BUCKET_VOLUME * 10);
}
}
@Override
public boolean shouldDropSlotWhenBroken(int slot)
{
return slot > 9;
}
@Override
public String getGuiBackground()
{
return "liquicrafter.png";
}
@Override
@SideOnly(Side.CLIENT)
public GuiFactoryInventory getGui(InventoryPlayer inventoryPlayer)
{
return new GuiLiquiCrafter(getContainer(inventoryPlayer), this);
}
@Override
public ContainerLiquiCrafter getContainer(InventoryPlayer inventoryPlayer)
{
return new ContainerLiquiCrafter(this, inventoryPlayer);
}
@Override
public void updateEntity()
{
super.updateEntity();
boolean redstoneState = Util.isRedstonePowered(this);
if(redstoneState && !_lastRedstoneState)
{
if(!worldObj.isRemote &&
_resourcesChangedSinceLastFailedCraft &&
_inventory[9] != null &&
(_inventory[10] == null ||
(_inventory[10].stackSize + _inventory[9].stackSize <= _inventory[9].getMaxStackSize() &&
_inventory[9].itemID == _inventory[10].itemID &&
_inventory[9].getItemDamage() == _inventory[10].getItemDamage())))
{
checkResources();
}
}
_lastRedstoneState = redstoneState;
}
private void checkResources()
{
List<ItemResourceTracker> requiredItems = new LinkedList<ItemResourceTracker>();
inv: for(int i = 0; i < 9; i++)
{
if(_inventory[i] != null)
{
if(LiquidContainerRegistry.isFilledContainer(_inventory[i]))
{
LiquidStack l = LiquidContainerRegistry.getLiquidForFilledItem(_inventory[i]);
for(ItemResourceTracker t : requiredItems)
{
if(t.id == l.itemID && t.meta == l.itemMeta)
{
t.required += 1000;
continue inv;
}
}
requiredItems.add(new ItemResourceTracker(l.itemID, l.itemMeta, 1000));
}
else
{
for(ItemResourceTracker t : requiredItems)
{
if(t.id == _inventory[i].itemID && t.meta == _inventory[i].getItemDamage())
{
t.required++;
continue inv;
}
}
requiredItems.add(new ItemResourceTracker(_inventory[i].itemID, _inventory[i].getItemDamage(), 1));
}
}
}
for(int i = 11; i < 29; i++)
{
if(_inventory[i] != null)
{
for(ItemResourceTracker t : requiredItems)
{
if(t.id == _inventory[i].itemID && (t.meta == _inventory[i].getItemDamage() || _inventory[i].getItem().isDamageable()))
{
if(!_inventory[i].getItem().hasContainerItem())
{
t.found += _inventory[i].stackSize;
}
else
{
t.found += 1;
}
break;
}
}
}
}
for(int i = 0; i < _tanks.length; i++)
{
LiquidStack l = _tanks[i].getLiquid();
if(l == null || l.amount == 0)
{
continue;
}
for(ItemResourceTracker t : requiredItems)
{
if(t.id == l.itemID && t.meta == l.itemMeta)
{
t.found += l.amount;
break;
}
}
}
for(ItemResourceTracker t : requiredItems)
{
if(t.found < t.required)
{
_resourcesChangedSinceLastFailedCraft = false;
return;
}
}
for(int i = 11; i < 29; i++)
{
if(_inventory[i] != null)
{
for(ItemResourceTracker t : requiredItems)
{
if(t.id == _inventory[i].itemID && (t.meta == _inventory[i].getItemDamage() || _inventory[i].getItem().isDamageable()))
{
int use;
if(_inventory[i].getItem().hasContainerItem())
{
use = 1;
ItemStack container = _inventory[i].getItem().getContainerItemStack(_inventory[i]);
if(container.isItemStackDamageable() && container.getItemDamage() > container.getMaxDamage())
{
_inventory[i] = null;
}
else
{
_inventory[i] = container;
}
}
else
{
use = Math.min(t.required, _inventory[i].stackSize);
_inventory[i].stackSize -= use;
}
t.required -= use;
- if(_inventory[i].stackSize == 0)
+ if(_inventory[i] != null && _inventory[i].stackSize == 0)
{
_inventory[i] = null;
}
if(t.required == 0)
{
requiredItems.remove(t);
}
break;
}
}
}
}
for(int i = 0; i < _tanks.length; i++)
{
LiquidStack l = _tanks[i].getLiquid();
if(l == null || l.amount == 0)
{
continue;
}
for(ItemResourceTracker t : requiredItems)
{
if(t.id == l.itemID && t.meta == l.itemMeta)
{
int use = Math.min(t.required, l.amount);
_tanks[i].drain(use, true);
t.required -= use;
if(t.required == 0)
{
requiredItems.remove(t);
}
break;
}
}
}
if(_inventory[10] == null)
{
_inventory[10] = _inventory[9].copy();
_inventory[10].stackSize = _inventory[9].stackSize;
}
else
{
_inventory[10].stackSize += _inventory[9].stackSize;
}
}
private void calculateOutput()
{
_inventory[9] = findMatchingRecipe();
}
@Override
public int getSizeInventory()
{
return 29;
}
@Override
public void setInventorySlotContents(int slot, ItemStack stack)
{
_inventory[slot] = stack;
if(slot < 9) calculateOutput();
onFactoryInventoryChanged();
}
@Override
public ItemStack decrStackSize(int slot, int size)
{
ItemStack result = super.decrStackSize(slot, size);
if(slot < 9) calculateOutput();
onFactoryInventoryChanged();
return result;
}
@Override
public String getInvName()
{
return "LiquiCrafter";
}
@Override
public int getInventoryStackLimit()
{
return 64;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player)
{
return player.getDistanceSq(xCoord, yCoord, zCoord) <= 64D;
}
@Override
public int getStartInventorySide(ForgeDirection side)
{
return 10;
}
@Override
public int getSizeInventorySide(ForgeDirection side)
{
return 19;
//if(side == ForgeDirection.UP || side == ForgeDirection.DOWN) return 1;
//return 18;
}
@Override
public boolean canInsertItem(int slot, ItemStack stack, int sideordinal)
{
if(slot > 10) return true;
return false;
}
@Override
public boolean canExtractItem(int slot, ItemStack itemstack, int sideordinal)
{
if(slot == 10) return true;
return false;
}
@Override
protected void onFactoryInventoryChanged()
{
_resourcesChangedSinceLastFailedCraft = true;
super.onFactoryInventoryChanged();
}
@Override
public boolean allowBucketFill()
{
return false;
}
@Override
public int fill(ForgeDirection from, LiquidStack resource, boolean doFill)
{
return this.fill(0, resource, doFill);
}
@Override
public int fill(int tankIndex, LiquidStack resource, boolean doFill)
{
int quantity;
int match = findFirstMatchingTank(resource);
if(match >= 0)
{
quantity = _tanks[match].fill(resource, doFill);
if(quantity > 0) _resourcesChangedSinceLastFailedCraft = true;
return quantity;
}
match = findFirstEmptyTank();
if(match >= 0)
{
quantity = _tanks[match].fill(resource, doFill);
if(quantity > 0) _resourcesChangedSinceLastFailedCraft = true;
return quantity;
}
return 0;
}
@Override
public boolean allowBucketDrain()
{
return false;
}
@Override
public LiquidStack drain(ForgeDirection from, int maxDrain, boolean doDrain)
{
int match = findFirstNonEmptyTank();
if(match >= 0) return _tanks[match].drain(maxDrain, doDrain);
return null;
}
@Override
public LiquidStack drain(int tankIndex, int maxDrain, boolean doDrain)
{
return _tanks[tankIndex].drain(maxDrain, doDrain);
}
@Override
public ILiquidTank[] getTanks(ForgeDirection direction)
{
return _tanks;
}
@Override
public ILiquidTank getTank(ForgeDirection direction, LiquidStack type)
{
int match = findFirstMatchingTank(type);
if(match >= 0) return _tanks[match];
match = findFirstEmptyTank();
if(match >= 0) return _tanks[match];
return null;
}
private int findFirstEmptyTank()
{
for(int i = 0; i < 9; i++)
{
if(_tanks[i].getLiquid() == null || _tanks[i].getLiquid().amount == 0)
{
return i;
}
}
return -1;
}
private int findFirstNonEmptyTank()
{
for(int i = 0; i < 9; i++)
{
if(_tanks[i].getLiquid() != null && _tanks[i].getLiquid().amount > 0)
{
return i;
}
}
return -1;
}
private int findFirstMatchingTank(LiquidStack liquid)
{
if(liquid == null)
{
return -1;
}
for(int i = 0; i < 9; i++)
{
if(_tanks[i].getLiquid() != null && _tanks[i].getLiquid().itemID == liquid.itemID && _tanks[i].getLiquid().itemMeta == liquid.itemMeta)
{
return i;
}
}
return -1;
}
private ItemStack findMatchingRecipe()
{
InventoryCrafting craft = new RemoteInventoryCrafting();
for(int i = 0; i < 9; i++)
{
craft.setInventorySlotContents(i, (_inventory[i] == null ? null : _inventory[i].copy()));
}
return CraftingManager.getInstance().findMatchingRecipe(craft, worldObj);
}
@Override
public void readFromNBT(NBTTagCompound nbttagcompound)
{
super.readFromNBT(nbttagcompound);
NBTTagList nbttaglist = nbttagcompound.getTagList("Tanks");
for(int i = 0; i < nbttaglist.tagCount(); i++)
{
NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttaglist.tagAt(i);
int j = nbttagcompound1.getByte("Tank") & 0xff;
if(j >= 0 && j < _tanks.length)
{
LiquidStack l = LiquidStack.loadLiquidStackFromNBT(nbttagcompound1);
if(l != null && l.asItemStack().getItem() != null && LiquidContainerRegistry.isLiquid(l.asItemStack()))
{
_tanks[j].setLiquid(l);
}
}
}
}
@Override
public void writeToNBT(NBTTagCompound nbttagcompound)
{
super.writeToNBT(nbttagcompound);
NBTTagList tanks = new NBTTagList();
for(int i = 0; i < _tanks.length; i++)
{
if(_tanks[i].getLiquid() != null)
{
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Tank", (byte)i);
LiquidStack l = _tanks[i].getLiquid();
l.writeToNBT(nbttagcompound1);
tanks.appendTag(nbttagcompound1);
}
}
nbttagcompound.setTag("Tanks", tanks);
}
}
| true | true | private void checkResources()
{
List<ItemResourceTracker> requiredItems = new LinkedList<ItemResourceTracker>();
inv: for(int i = 0; i < 9; i++)
{
if(_inventory[i] != null)
{
if(LiquidContainerRegistry.isFilledContainer(_inventory[i]))
{
LiquidStack l = LiquidContainerRegistry.getLiquidForFilledItem(_inventory[i]);
for(ItemResourceTracker t : requiredItems)
{
if(t.id == l.itemID && t.meta == l.itemMeta)
{
t.required += 1000;
continue inv;
}
}
requiredItems.add(new ItemResourceTracker(l.itemID, l.itemMeta, 1000));
}
else
{
for(ItemResourceTracker t : requiredItems)
{
if(t.id == _inventory[i].itemID && t.meta == _inventory[i].getItemDamage())
{
t.required++;
continue inv;
}
}
requiredItems.add(new ItemResourceTracker(_inventory[i].itemID, _inventory[i].getItemDamage(), 1));
}
}
}
for(int i = 11; i < 29; i++)
{
if(_inventory[i] != null)
{
for(ItemResourceTracker t : requiredItems)
{
if(t.id == _inventory[i].itemID && (t.meta == _inventory[i].getItemDamage() || _inventory[i].getItem().isDamageable()))
{
if(!_inventory[i].getItem().hasContainerItem())
{
t.found += _inventory[i].stackSize;
}
else
{
t.found += 1;
}
break;
}
}
}
}
for(int i = 0; i < _tanks.length; i++)
{
LiquidStack l = _tanks[i].getLiquid();
if(l == null || l.amount == 0)
{
continue;
}
for(ItemResourceTracker t : requiredItems)
{
if(t.id == l.itemID && t.meta == l.itemMeta)
{
t.found += l.amount;
break;
}
}
}
for(ItemResourceTracker t : requiredItems)
{
if(t.found < t.required)
{
_resourcesChangedSinceLastFailedCraft = false;
return;
}
}
for(int i = 11; i < 29; i++)
{
if(_inventory[i] != null)
{
for(ItemResourceTracker t : requiredItems)
{
if(t.id == _inventory[i].itemID && (t.meta == _inventory[i].getItemDamage() || _inventory[i].getItem().isDamageable()))
{
int use;
if(_inventory[i].getItem().hasContainerItem())
{
use = 1;
ItemStack container = _inventory[i].getItem().getContainerItemStack(_inventory[i]);
if(container.isItemStackDamageable() && container.getItemDamage() > container.getMaxDamage())
{
_inventory[i] = null;
}
else
{
_inventory[i] = container;
}
}
else
{
use = Math.min(t.required, _inventory[i].stackSize);
_inventory[i].stackSize -= use;
}
t.required -= use;
if(_inventory[i].stackSize == 0)
{
_inventory[i] = null;
}
if(t.required == 0)
{
requiredItems.remove(t);
}
break;
}
}
}
}
for(int i = 0; i < _tanks.length; i++)
{
LiquidStack l = _tanks[i].getLiquid();
if(l == null || l.amount == 0)
{
continue;
}
for(ItemResourceTracker t : requiredItems)
{
if(t.id == l.itemID && t.meta == l.itemMeta)
{
int use = Math.min(t.required, l.amount);
_tanks[i].drain(use, true);
t.required -= use;
if(t.required == 0)
{
requiredItems.remove(t);
}
break;
}
}
}
if(_inventory[10] == null)
{
_inventory[10] = _inventory[9].copy();
_inventory[10].stackSize = _inventory[9].stackSize;
}
else
{
_inventory[10].stackSize += _inventory[9].stackSize;
}
}
| private void checkResources()
{
List<ItemResourceTracker> requiredItems = new LinkedList<ItemResourceTracker>();
inv: for(int i = 0; i < 9; i++)
{
if(_inventory[i] != null)
{
if(LiquidContainerRegistry.isFilledContainer(_inventory[i]))
{
LiquidStack l = LiquidContainerRegistry.getLiquidForFilledItem(_inventory[i]);
for(ItemResourceTracker t : requiredItems)
{
if(t.id == l.itemID && t.meta == l.itemMeta)
{
t.required += 1000;
continue inv;
}
}
requiredItems.add(new ItemResourceTracker(l.itemID, l.itemMeta, 1000));
}
else
{
for(ItemResourceTracker t : requiredItems)
{
if(t.id == _inventory[i].itemID && t.meta == _inventory[i].getItemDamage())
{
t.required++;
continue inv;
}
}
requiredItems.add(new ItemResourceTracker(_inventory[i].itemID, _inventory[i].getItemDamage(), 1));
}
}
}
for(int i = 11; i < 29; i++)
{
if(_inventory[i] != null)
{
for(ItemResourceTracker t : requiredItems)
{
if(t.id == _inventory[i].itemID && (t.meta == _inventory[i].getItemDamage() || _inventory[i].getItem().isDamageable()))
{
if(!_inventory[i].getItem().hasContainerItem())
{
t.found += _inventory[i].stackSize;
}
else
{
t.found += 1;
}
break;
}
}
}
}
for(int i = 0; i < _tanks.length; i++)
{
LiquidStack l = _tanks[i].getLiquid();
if(l == null || l.amount == 0)
{
continue;
}
for(ItemResourceTracker t : requiredItems)
{
if(t.id == l.itemID && t.meta == l.itemMeta)
{
t.found += l.amount;
break;
}
}
}
for(ItemResourceTracker t : requiredItems)
{
if(t.found < t.required)
{
_resourcesChangedSinceLastFailedCraft = false;
return;
}
}
for(int i = 11; i < 29; i++)
{
if(_inventory[i] != null)
{
for(ItemResourceTracker t : requiredItems)
{
if(t.id == _inventory[i].itemID && (t.meta == _inventory[i].getItemDamage() || _inventory[i].getItem().isDamageable()))
{
int use;
if(_inventory[i].getItem().hasContainerItem())
{
use = 1;
ItemStack container = _inventory[i].getItem().getContainerItemStack(_inventory[i]);
if(container.isItemStackDamageable() && container.getItemDamage() > container.getMaxDamage())
{
_inventory[i] = null;
}
else
{
_inventory[i] = container;
}
}
else
{
use = Math.min(t.required, _inventory[i].stackSize);
_inventory[i].stackSize -= use;
}
t.required -= use;
if(_inventory[i] != null && _inventory[i].stackSize == 0)
{
_inventory[i] = null;
}
if(t.required == 0)
{
requiredItems.remove(t);
}
break;
}
}
}
}
for(int i = 0; i < _tanks.length; i++)
{
LiquidStack l = _tanks[i].getLiquid();
if(l == null || l.amount == 0)
{
continue;
}
for(ItemResourceTracker t : requiredItems)
{
if(t.id == l.itemID && t.meta == l.itemMeta)
{
int use = Math.min(t.required, l.amount);
_tanks[i].drain(use, true);
t.required -= use;
if(t.required == 0)
{
requiredItems.remove(t);
}
break;
}
}
}
if(_inventory[10] == null)
{
_inventory[10] = _inventory[9].copy();
_inventory[10].stackSize = _inventory[9].stackSize;
}
else
{
_inventory[10].stackSize += _inventory[9].stackSize;
}
}
|
diff --git a/pluginsource/org/enigma/EnigmaRunner.java b/pluginsource/org/enigma/EnigmaRunner.java
index b52b15b9..c7bcca17 100644
--- a/pluginsource/org/enigma/EnigmaRunner.java
+++ b/pluginsource/org/enigma/EnigmaRunner.java
@@ -1,928 +1,928 @@
/*
* Copyright (C) 2008-2011 IsmAvatar <[email protected]>
* Copyright (C) 2013, Robert B. Colton
*
* This file is part of Enigma Plugin.
*
* Enigma Plugin 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.
*
* Enigma Plugin 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 (COPYING) 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.enigma;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Pattern;
import javax.swing.AbstractListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JList;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.tree.TreeNode;
import org.enigma.backend.Definitions;
import org.enigma.backend.EnigmaCallbacks;
import org.enigma.backend.EnigmaDriver;
import org.enigma.backend.EnigmaDriver.SyntaxError;
import org.enigma.backend.EnigmaSettings;
import org.enigma.backend.EnigmaStruct;
import org.enigma.file.EFileReader;
import org.enigma.file.EgmIO;
import org.enigma.file.YamlParser;
import org.enigma.file.YamlParser.YamlNode;
import org.enigma.frames.EnigmaSettingsFrame;
import org.enigma.frames.ProgressFrame;
import org.enigma.messages.Messages;
import org.enigma.utility.EnigmaBuildReader;
import org.lateralgm.components.ErrorDialog;
import org.lateralgm.components.GMLTextArea;
import org.lateralgm.components.impl.CustomFileFilter;
import org.lateralgm.components.impl.ResNode;
import org.lateralgm.components.mdi.MDIFrame;
import org.lateralgm.file.GmFile.ResourceHolder;
import org.lateralgm.file.GmFile.SingletonResourceHolder;
import org.lateralgm.file.GmFormatException;
import org.lateralgm.jedit.GMLKeywords;
import org.lateralgm.jedit.GMLKeywords.Construct;
import org.lateralgm.jedit.GMLKeywords.Function;
import org.lateralgm.jedit.GMLKeywords.Keyword;
import org.lateralgm.main.FileChooser;
import org.lateralgm.main.LGM;
import org.lateralgm.main.LGM.ReloadListener;
import org.lateralgm.main.LGM.SingletonPluginResource;
import org.lateralgm.main.Listener;
import org.lateralgm.resources.Resource;
import org.lateralgm.resources.Script;
import org.lateralgm.subframes.ActionFrame;
import org.lateralgm.subframes.CodeFrame;
import org.lateralgm.subframes.ResourceFrame;
import org.lateralgm.subframes.ResourceFrame.ResourceFrameFactory;
import org.lateralgm.subframes.ScriptFrame;
import org.lateralgm.subframes.SubframeInformer;
import org.lateralgm.subframes.SubframeInformer.SubframeListener;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import com.sun.jna.StringArray;
public class EnigmaRunner implements ActionListener,SubframeListener,ReloadListener
{
public static boolean NEW_DEFINITIONS_READY_YET = false;
public static boolean ENIGMA_READY = false, ENIGMA_FAIL = false, SHUTDOWN = false;
public static final int MODE_RUN = 0, MODE_DEBUG = 1, MODE_DESIGN = 2;
public static final int MODE_COMPILE = 3, MODE_REBUILD = 4;
public static final File WORKDIR = LGM.workDir.getParentFile();
/** This is static because it belongs to EnigmaStruct's dll, which is statically loaded. */
public static EnigmaDriver DRIVER;
public ProgressFrame ef = new ProgressFrame();
/** This is global scoped so that it doesn't get GC'd */
private EnigmaCallbacks ec = new EnigmaCallbacks(ef);
public EnigmaSettingsFrame esf;
public JMenuItem busy, run, debug, design, compile, rebuild;
public JButton runb, debugb, compileb;
public JMenuItem mImport, showFunctions, showGlobals, showTypes;
public ResNode node = new ResNode(Messages.getString("EnigmaRunner.RESNODE_NAME"), //$NON-NLS-1$
ResNode.STATUS_SECONDARY,EnigmaSettings.class);
public EnigmaRunner()
{
addResourceHook();
populateMenu();
populateTree();
LGM.addReloadListener(this);
SubframeInformer.addSubframeListener(this);
applyBackground("org/enigma/enigma.png"); //$NON-NLS-1$
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
SHUTDOWN = true;
}
});
new Thread()
{
public void run()
{
//Make checks for changes itself
if (!make()) //displays own error
{
ENIGMA_FAIL = true;
return;
}
Error e = attemptLib();
if (e != null)
{
String err = Messages.getString("EnigmaRunner.ERROR_LIBRARY") //$NON-NLS-1$
+ Messages.format("EnigmaRunner.ERROR_LIBRARY_EXACT",e.getMessage()); //$NON-NLS-1$
JOptionPane.showMessageDialog(null,err);
ENIGMA_FAIL = true;
return;
}
System.out.println(Messages.getString("EnigmaRunner.INITIALIZING")); //$NON-NLS-1$
String err = DRIVER.libInit(ec);
if (err != null)
{
JOptionPane.showMessageDialog(null,err);
ENIGMA_FAIL = true;
return;
}
ENIGMA_READY = true;
EnigmaSettings es = LGM.currentFile.resMap.get(EnigmaSettings.class).getResource();
esf = new EnigmaSettingsFrame(es);
LGM.mdi.add(esf);
es.commitToDriver(DRIVER);
setupBaseKeywords();
populateKeywords();
}
}.start();
}
private static UnsatisfiedLinkError attemptLib()
{
try
{
String lib = "compileEGMf"; //$NON-NLS-1$
NativeLibrary.addSearchPath(lib,"."); //$NON-NLS-1$
NativeLibrary.addSearchPath(lib,LGM.workDir.getParent());
DRIVER = (EnigmaDriver) Native.loadLibrary(lib,EnigmaDriver.class);
return null;
}
catch (UnsatisfiedLinkError e)
{
return e;
}
}
//This can be static since the ENIGMA_READY and Enigma dll are both static.
public static boolean assertReady()
{
if (!ENIGMA_READY)
JOptionPane.showMessageDialog(null,
ENIGMA_FAIL ? Messages.getString("EnigmaRunner.UNABLE_ERROR") //$NON-NLS-1$
: Messages.getString("EnigmaRunner.UNABLE_BUSY")); //$NON-NLS-1$
return ENIGMA_READY;
}
public boolean make()
{
String make, tcpath, path;
//try to read the YAML definition for `make` on this platform
try
{
try
{
File gccey = new File(new File("Compilers",TargetHandler.getOS()),"gcc.ey"); //$NON-NLS-1$ //$NON-NLS-2$
YamlNode n = YamlParser.parse(gccey);
make = n.getMC("Make"); //or OOB //$NON-NLS-1$
tcpath = n.getMC("TCPath",new String()); //$NON-NLS-1$
path = n.getMC("Path",new String()); //$NON-NLS-1$
//replace starting \ with root
if (make.startsWith("\\")) make = new File("/").getAbsolutePath() + make.substring(1); //$NON-NLS-1$ //$NON-NLS-2$
}
catch (FileNotFoundException e)
{
throw new GmFormatException(null,e);
}
catch (IndexOutOfBoundsException e)
{
throw new GmFormatException(null,e);
}
}
catch (GmFormatException e2)
{
e2.printStackTrace();
new ErrorDialog(null,Messages.getString("EnigmaRunner.ERROR_YAML_MAKE_TITLE"), //$NON-NLS-1$
Messages.getString("EnigmaRunner.ERROR_YAML_MAKE"),e2).setVisible(true); //$NON-NLS-1$
return false;
}
//run make
Process p = null;
String cmd = make + " eTCpath=\"" + tcpath + "\""; //$NON-NLS-1$
String[] env = null;
if (path != null) env = new String[] { "PATH=" + path };
try
{
p = Runtime.getRuntime().exec(cmd,env,LGM.workDir.getParentFile());
}
catch (IOException e)
{
GmFormatException e2 = new GmFormatException(null,e);
e2.printStackTrace();
new ErrorDialog(null,Messages.getString("EnigmaRunner.ERROR_MAKE_TITLE"), //$NON-NLS-1$
Messages.getString("EnigmaRunner.ERROR_MAKE"),e2).setVisible(true); //$NON-NLS-1$
return false;
}
//Set up listeners, waitFor, finish successfully
String calling = Messages.format("EnigmaRunner.EXEC_CALLING",cmd); //$NON-NLS-1$
System.out.println(calling);
ef.append(calling + "\n");
new EnigmaThread(ef,p.getInputStream());
new EnigmaThread(ef,p.getErrorStream());
ef.open();
try
{
System.out.println(p.waitFor());
System.out.println("Process terminated");
}
catch (InterruptedException e)
{
e.printStackTrace();
}
ef.close();
return true;
}
void addResourceHook()
{
EgmIO io = new EgmIO();
FileChooser.fileViews.add(io);
FileChooser.readers.add(io);
FileChooser.writers.add(io);
Listener.getInstance().fc.addOpenFilters(io);
Listener.getInstance().fc.addSaveFilters(io);
LGM.addPluginResource(new EnigmaSettingsPluginResource());
}
private class EnigmaSettingsPluginResource extends SingletonPluginResource<EnigmaSettings>
{
@Override
public Class<? extends Resource<?,?>> getKind()
{
return EnigmaSettings.class;
}
@Override
public ImageIcon getIcon()
{
return LGM.findIcon("restree/gm.png");
}
@Override
public String getName3()
{
return "EGS";
}
@Override
public String getName()
{
return Messages.getString("EnigmaRunner.RESNODE_NAME");
}
@Override
public ResourceFrameFactory getResourceFrameFactory()
{
return new ResourceFrameFactory()
{
@Override
public ResourceFrame<?,?> makeFrame(Resource<?,?> r, ResNode node)
{
return esf;
}
};
}
@Override
public EnigmaSettings getInstance()
{
return new EnigmaSettings();
}
}
public void populateMenu()
{
runb = new JButton(); //$NON-NLS-1$
runb.addActionListener(this);
runb.setToolTipText(Messages.getString("EnigmaRunner.MENU_RUN"));
runb.setIcon(LGM.getIconForKey("EnigmaPlugin.EXECUTE"));
LGM.tool.add(new JToolBar.Separator(), 4);
LGM.tool.add(runb, 5);
debugb = new JButton(); //$NON-NLS-1$
debugb.addActionListener(this);
debugb.setToolTipText(Messages.getString("EnigmaRunner.MENU_DEBUG"));
debugb.setIcon(LGM.getIconForKey("EnigmaPlugin.DEBUG"));
LGM.tool.add(debugb, 6);
compileb = new JButton(); //$NON-NLS-1$
compileb.addActionListener(this);
compileb.setToolTipText(Messages.getString("EnigmaRunner.MENU_COMPILE"));
compileb.setIcon(LGM.getIconForKey("EnigmaPlugin.COMPILE"));
LGM.tool.add(compileb, 7);
- JMenu menu = new JMenu(Messages.getString("EnigmaRunner.MENU_ENIGMA")); //$NON-NLS-1$
- menu.setFont(LGM.lnfFont.deriveFont(Font.BOLD));
+ JMenu menu = new JMenu(Messages.getString("EnigmaRunner.MENU_BUILD")); //$NON-NLS-1$
+ menu.setFont(LGM.lnfFont.deriveFont(Font.BOLD, 14));
busy = addItem(Messages.getString("EnigmaRunner.MENU_BUSY"));
busy.setEnabled(false);
busy.setVisible(false);
menu.add(busy);
run = addItem(Messages.getString("EnigmaRunner.MENU_RUN")); //$NON-NLS-1$
run.addActionListener(this);
run.setIcon(LGM.getIconForKey("EnigmaPlugin.EXECUTE"));
run.setAccelerator(KeyStroke.getKeyStroke("F5"));
menu.add(run);
debug = addItem(Messages.getString("EnigmaRunner.MENU_DEBUG")); //$NON-NLS-1$
debug.addActionListener(this);
debug.setIcon(LGM.getIconForKey("EnigmaPlugin.DEBUG"));
debug.setAccelerator(KeyStroke.getKeyStroke("F6"));
menu.add(debug);
design = addItem(Messages.getString("EnigmaRunner.MENU_DESIGN")); //$NON-NLS-1$
design.addActionListener(this);
design.setAccelerator(KeyStroke.getKeyStroke("F7"));
menu.add(design);
compile = addItem(Messages.getString("EnigmaRunner.MENU_COMPILE")); //$NON-NLS-1$
compile.addActionListener(this);
compile.setIcon(LGM.getIconForKey("EnigmaPlugin.COMPILE"));
compile.setAccelerator(KeyStroke.getKeyStroke("F8"));
menu.add(compile);
rebuild = addItem(Messages.getString("EnigmaRunner.MENU_REBUILD_ALL")); //$NON-NLS-1$
rebuild.addActionListener(this);
rebuild.setIcon(LGM.getIconForKey("EnigmaPlugin.REBUILD_ALL"));
rebuild.setAccelerator(KeyStroke.getKeyStroke("F9"));
menu.add(rebuild);
menu.addSeparator();
mImport = addItem(Messages.getString("EnigmaRunner.MENU_IMPORT")); //$NON-NLS-1$
mImport.addActionListener(this);
menu.add(mImport);
menu.addSeparator();
JMenuItem mi = addItem(Messages.getString("EnigmaRunner.MENU_SETTINGS")); //$NON-NLS-1$
mi.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
node.openFrame();
}
});
menu.add(mi);
JMenu sub = new JMenu(Messages.getString("EnigmaRunner.MENU_KEYWORDS")); //$NON-NLS-1$
sub.setFont(LGM.lnfFont.deriveFont(Font.BOLD));
menu.add(sub);
showFunctions = addItem(KEY_MODES[FUNCTIONS]);
showFunctions.addActionListener(this);
sub.add(showFunctions);
showGlobals = addItem(KEY_MODES[GLOBALS]);
showGlobals.addActionListener(this);
sub.add(showGlobals);
showTypes = addItem(KEY_MODES[TYPES]);
showTypes.addActionListener(this);
sub.add(showTypes);
LGM.frame.getJMenuBar().add(menu,1);
}
private JMenuItem addItem(String string) {
JMenuItem ret = new JMenuItem(string);
ret.setFont(LGM.lnfFont.deriveFont(Font.BOLD));
return ret;
}
public void firstSetup()
{
LGM.root.add(node); //EnigmaSettings node
if (NEW_DEFINITIONS_READY_YET)
{
LGM.currentFile.resMap.addList(Definitions.class);
String name = Resource.kindNamesPlural.get(Definitions.class);
LGM.root.addChild(name,ResNode.STATUS_PRIMARY,Definitions.class);
}
LGM.tree.updateUI();
}
public void populateTree()
{
if (!LGM.root.isNodeChild(node))
{
boolean found = false;
for (int i = 0; i < LGM.root.getChildCount() && !found; i++)
{
TreeNode n = LGM.root.getChildAt(i);
if (n instanceof ResNode && ((ResNode) n).kind == EnigmaSettings.class)
{
node = (ResNode) n;
found = true;
}
}
if (!found) firstSetup();
}
}
private static SortedSet<Function> BASE_FUNCTIONS;
private static SortedSet<Construct> BASE_CONSTRUCTS;
private static final Comparator<Keyword> KEYWORD_COMP = new Comparator<Keyword>()
{
@Override
public int compare(Keyword o1, Keyword o2)
{
return o1.getName().compareTo(o2.getName());
}
};
private static void setupBaseKeywords()
{
BASE_FUNCTIONS = new TreeSet<Function>(KEYWORD_COMP);
for (Function f : GMLKeywords.FUNCTIONS)
BASE_FUNCTIONS.add(f);
BASE_CONSTRUCTS = new TreeSet<Construct>(KEYWORD_COMP);
for (Construct f : GMLKeywords.CONSTRUCTS)
BASE_CONSTRUCTS.add(f);
}
public static void populateKeywords()
{
Set<Function> fl = new TreeSet<Function>(BASE_FUNCTIONS);
Set<Construct> cl = new TreeSet<Construct>(BASE_CONSTRUCTS);
String res = DRIVER.first_available_resource();
while (res != null)
{
if (nameRegex.matcher(res).matches())
{
if (DRIVER.resource_isFunction())
{
int overloads = DRIVER.resource_overloadCount();
if (overloads > 0)
{
String args = DRIVER.resource_parameters(0);
fl.add(new Function(res,args.substring(1,args.length() - 1),null));
}
else
{
int min = DRIVER.resource_argCountMin();
int max = DRIVER.resource_argCountMax();
String args = Integer.toString(min);
if (min != max) args += "-" + max; //$NON-NLS-1$
fl.add(new Function(res,args,null));
}
}
// else if (DRIVER.resource_isGlobal()) rl.add(res);
else if (DRIVER.resource_isTypeName()) cl.add(new Construct(res));
}
res = DRIVER.next_available_resource();
}
GMLKeywords.FUNCTIONS = fl.toArray(new Function[0]);
for (Construct c : GMLKeywords.CONSTRUCTS)
cl.add(c);
GMLKeywords.CONSTRUCTS = cl.toArray(new Construct[0]);
}
public void applyBackground(String bgloc)
{
ImageIcon bg = findIcon(bgloc);
LGM.mdi.add(new MDIBackground(bg),JLayeredPane.FRAME_CONTENT_LAYER);
}
public class MDIBackground extends JComponent
{
private static final long serialVersionUID = 1L;
ImageIcon image;
public MDIBackground(ImageIcon icon)
{
image = icon;
if (image == null) return;
if (image.getIconWidth() <= 0) image = null;
}
public int getWidth()
{
return LGM.mdi.getWidth();
}
public int getHeight()
{
return LGM.mdi.getHeight();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (image == null) return;
for (int y = 0; y < getHeight(); y += image.getIconHeight())
for (int x = 0; x < getWidth(); x += image.getIconWidth())
g.drawImage(image.getImage(),x,y,null);
}
}
public void setMenuEnabled(boolean en)
{
busy.setVisible(!en);
run.setEnabled(en);
debug.setEnabled(en);
design.setEnabled(en);
compile.setEnabled(en);
rebuild.setEnabled(en);
runb.setEnabled(en);
debugb.setEnabled(en);
compileb.setEnabled(en);
}
public void compile(final int mode)
{
if (!assertReady()) return;
EnigmaSettings es = LGM.currentFile.resMap.get(EnigmaSettings.class).getResource();
if (es.targets.get(TargetHandler.COMPILER) == null)
{
JOptionPane.showMessageDialog(null,Messages.getString("EnigmaRunner.UNABLE_SETTINGS_NULL")); //$NON-NLS-1$
return;
}
String ext = es.targets.get(TargetHandler.COMPILER).ext;
//determine `outname` (rebuild has no `outname`)
File outname = null;
try
{
String outputexe = es.targets.get(TargetHandler.COMPILER).outputexe;
if (!outputexe.equals("$tempfile")) //$NON-NLS-1$
outname = new File(outputexe);
else if (mode < MODE_DESIGN) //run/debug
outname = File.createTempFile("egm",ext); //$NON-NLS-1$
else if (mode == MODE_DESIGN) outname = File.createTempFile("egm",".emd"); //$NON-NLS-1$ //$NON-NLS-2$
if (outname != null) outname.deleteOnExit();
}
catch (IOException e)
{
e.printStackTrace();
return;
}
if (mode == MODE_COMPILE)
{
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new CustomFileFilter(ext,
Messages.getString("EnigmaRunner.CHOOSER_EXE_DESCRIPTION"))); //$NON-NLS-1$
if (fc.showSaveDialog(LGM.frame) != JFileChooser.APPROVE_OPTION) return;
outname = fc.getSelectedFile();
if (ext != null && !outname.getName().endsWith(ext))
outname = new File(outname.getPath() + ext);
else
outname = new File(outname.getPath());
}
setMenuEnabled(false);
LGM.commitAll();
//Don't need to update ESF since commitAll traverses all nodes
//esf.updateResource();
es.commitToDriver(DRIVER);
//System.out.println("Compiling with " + enigma);
final File efi = outname;
new Thread()
{
public void run()
{
ef.open();
ef.progress(10,Messages.getString("EnigmaRunner.POPULATING")); //$NON-NLS-1$
EnigmaStruct es = EnigmaWriter.prepareStruct(LGM.currentFile,LGM.root);
ef.progress(20,Messages.getString("EnigmaRunner.CALLING")); //$NON-NLS-1$
System.out.println("Plugin: Delegating to ENIGMA (out of my hands now)");
System.out.println(DRIVER.compileEGMf(es,efi == null ? null : efi.getAbsolutePath(),mode));
setMenuEnabled(true);
}
}.start();
if (mode == MODE_DESIGN) //design
{
try
{
EnigmaBuildReader.readChanges(outname);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static SyntaxError checkSyntax(String code)
{
if (!assertReady()) return null;
String osl[] = new String[LGM.currentFile.resMap.getList(Script.class).size()];
Script isl[] = LGM.currentFile.resMap.getList(Script.class).toArray(new Script[0]);
for (int i = 0; i < osl.length; i++)
osl[i] = isl[i].getName();
return DRIVER.syntaxCheck(osl.length,new StringArray(osl),code);
}
public void actionPerformed(ActionEvent e)
{
if (!assertReady()) return;
Object s = e.getSource();
if (s == run || s == runb) compile(MODE_RUN);
if (s == debug || s == debugb) compile(MODE_DEBUG);
if (s == design) compile(MODE_DESIGN);
if (s == compile || s == compileb) compile(MODE_COMPILE);
if (s == rebuild) compile(MODE_REBUILD);
if (s == mImport) EFileReader.importEgmFolder();
if (s == showFunctions) showKeywordListFrame(FUNCTIONS);
if (s == showGlobals) showKeywordListFrame(GLOBALS);
if (s == showTypes) showKeywordListFrame(TYPES);
}
private static final int FUNCTIONS = 0, GLOBALS = 1, TYPES = 2;
private static final String[] KEY_MODES = { Messages.getString("EnigmaRunner.KEY_FUNCTIONS"), //$NON-NLS-1$
Messages.getString("EnigmaRunner.KEY_GLOBALS"), //$NON-NLS-1$
Messages.getString("EnigmaRunner.KEY_TYPES") }; //$NON-NLS-1$
private MDIFrame keywordListFrames[] = new MDIFrame[3];
private KeywordListModel keywordLists[] = new KeywordListModel[3];
private final static Pattern nameRegex = Pattern.compile("[a-zA-Z][a-zA-Z0-9_]*"); //$NON-NLS-1$
public void showKeywordListFrame(final int mode)
{
if (keywordListFrames[mode] == null)
{
keywordListFrames[mode] = new MDIFrame(KEY_MODES[mode],true,true,true,true);
keywordListFrames[mode].setSize(200,400);
keywordListFrames[mode].setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);
LGM.mdi.add(keywordListFrames[mode]);
keywordLists[mode] = new KeywordListModel();
final JList list = new JList(keywordLists[mode]);
// keywordLists[mode].setEditable(false);
// keywordLists[mode].setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
list.setFont(new Font(Font.MONOSPACED,Font.PLAIN,12));
final JTextField filter = new JTextField();
filter.getDocument().addDocumentListener(new DocumentListener()
{
@Override
public void changedUpdate(DocumentEvent e)
{
keywordLists[mode].setFilter(filter.getText());
}
@Override
public void insertUpdate(DocumentEvent e)
{
keywordLists[mode].setFilter(filter.getText());
}
@Override
public void removeUpdate(DocumentEvent e)
{
keywordLists[mode].setFilter(filter.getText());
}
});
keywordListFrames[mode].add(new JScrollPane(filter),BorderLayout.NORTH);
keywordListFrames[mode].add(new JScrollPane(list),BorderLayout.CENTER);
// keywordListFrames[mode].setFocusTraversalPolicy(new TextAreaFocusTraversalPolicy(list));
}
//TODO: should only repopulate when whitespace changes
keywordLists[mode].setKeywords(getKeywordList(mode));
keywordListFrames[mode].toTop();
}
public class KeywordListModel extends AbstractListModel
{
private static final long serialVersionUID = 1L;
public List<String> keywords;
private List<String> filteredKeywords = new ArrayList<String>();
private String filter;
public void setKeywords(List<String> keywords)
{
this.keywords = keywords;
applyFilter();
}
public void setFilter(String filter)
{
this.filter = filter;
applyFilter();
}
private void applyFilter()
{
filteredKeywords.clear();
if (filter == null || filter.isEmpty() && keywords != null)
filteredKeywords.addAll(keywords);
else
{
for (String s : keywords)
if (s.startsWith(filter)) filteredKeywords.add(s);
for (String s : keywords)
if (s.contains(filter) && !s.startsWith(filter)) filteredKeywords.add(s);
}
this.fireContentsChanged(this,0,getSize());
}
@Override
public Object getElementAt(int index)
{
return filteredKeywords.get(index);
}
@Override
public int getSize()
{
return filteredKeywords.size();
}
}
/**
* Generates a newline (\n) delimited list of keywords of given type
* @param type 0 for functions, 1 for globals, 2 for types
* @return The keyword list
*/
public static List<String> getKeywordList(int type)
{
List<String> rl = new ArrayList<String>();
String res = DRIVER.first_available_resource();
while (res != null)
{
if (nameRegex.matcher(res).matches()) switch (type)
{
case 0:
if (DRIVER.resource_isFunction())
{
int overloads = DRIVER.resource_overloadCount();
if (overloads > 0)
{
rl.add(res + DRIVER.resource_parameters(0));
break;
}
int min = DRIVER.resource_argCountMin();
int max = DRIVER.resource_argCountMax();
res += "(" + min; //$NON-NLS-1$
if (min != max) res += "-" + max; //$NON-NLS-1$
res += ")"; //$NON-NLS-1$
rl.add(res);
}
break;
case 1:
if (DRIVER.resource_isGlobal()) rl.add(res);
break;
case 2:
if (DRIVER.resource_isTypeName()) rl.add(res);
break;
}
res = DRIVER.next_available_resource();
}
return rl;
}
public void subframeAppeared(MDIFrame source)
{
JToolBar tool;
final GMLTextArea code;
final JPanel status;
if (source instanceof ScriptFrame)
{
ScriptFrame sf = (ScriptFrame) source;
tool = sf.tool;
code = sf.code;
status = sf.status;
}
else if (source instanceof CodeFrame)
{
CodeFrame cf = (CodeFrame) source;
if (esf != null && cf.codeHolder == esf.sDef) return;
tool = cf.tool;
code = cf.code;
status = cf.status;
}
else if (source instanceof ActionFrame && ((ActionFrame) source).code != null)
{
ActionFrame af = (ActionFrame) source;
tool = af.tool;
code = af.code;
status = af.status;
}
else
return;
status.add(new JLabel(" | ")); //$NON-NLS-1$
//visible divider ^ since JSeparator isn't visible and takes up the whole thing...
final JLabel errors = new JLabel(Messages.getString("EnigmaRunner.LABEL_ERRORS_UNSET")); //$NON-NLS-1$
status.add(errors);
JButton syntaxCheck;
ImageIcon i = findIcon("syntax.png"); //$NON-NLS-1$
if (i == null)
syntaxCheck = new JButton(Messages.getString("EnigmaRunner.BUTTON_SYNTAX")); //$NON-NLS-1$
else
{
syntaxCheck = new JButton(i);
syntaxCheck.setToolTipText(Messages.getString("EnigmaRunner.BUTTON_SYNTAX_TIP")); //$NON-NLS-1$
}
syntaxCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SyntaxError se = checkSyntax(code.getTextCompat());
if (se == null) return;
if (se.absoluteIndex != -1) //-1 = no error
{
code.markError(se.line - 1,se.position - 1,se.absoluteIndex);
errors.setText(se.line + ":" + se.position + "::" + se.errorString); //$NON-NLS-1$ //$NON-NLS-2$
}
else
errors.setText(Messages.getString("EnigmaRunner.LABEL_ERRORS_UNSET")); //$NON-NLS-1$
code.requestFocusInWindow();
}
});
tool.add(syntaxCheck,5);
}
@Override
public void reloadPerformed(boolean newRoot)
{
if (newRoot) populateTree();
if (ENIGMA_READY)
{
ResourceHolder<EnigmaSettings> rh = LGM.currentFile.resMap.get(EnigmaSettings.class);
if (rh == null)
LGM.currentFile.resMap.put(EnigmaSettings.class,
rh = new SingletonResourceHolder<EnigmaSettings>(new EnigmaSettings()));
esf.resOriginal = rh.getResource();
esf.revertResource(); //updates local res copy as well
}
}
public static ImageIcon findIcon(String loc)
{
ImageIcon ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
URL url = EnigmaRunner.class.getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
if (ico.getIconWidth() != -1) return ico;
loc = "org/enigma/" + loc; //$NON-NLS-1$
ico = new ImageIcon(loc);
if (ico.getIconWidth() != -1) return ico;
url = EnigmaRunner.class.getClassLoader().getResource(loc);
if (url != null) ico = new ImageIcon(url);
return ico;
}
public boolean subframeRequested(Resource<?,?> res, ResNode node)
{
return false;
}
public static void main(String[] args)
{
LGM.main(args);
new EnigmaRunner();
}
}
| true | true | public void populateMenu()
{
runb = new JButton(); //$NON-NLS-1$
runb.addActionListener(this);
runb.setToolTipText(Messages.getString("EnigmaRunner.MENU_RUN"));
runb.setIcon(LGM.getIconForKey("EnigmaPlugin.EXECUTE"));
LGM.tool.add(new JToolBar.Separator(), 4);
LGM.tool.add(runb, 5);
debugb = new JButton(); //$NON-NLS-1$
debugb.addActionListener(this);
debugb.setToolTipText(Messages.getString("EnigmaRunner.MENU_DEBUG"));
debugb.setIcon(LGM.getIconForKey("EnigmaPlugin.DEBUG"));
LGM.tool.add(debugb, 6);
compileb = new JButton(); //$NON-NLS-1$
compileb.addActionListener(this);
compileb.setToolTipText(Messages.getString("EnigmaRunner.MENU_COMPILE"));
compileb.setIcon(LGM.getIconForKey("EnigmaPlugin.COMPILE"));
LGM.tool.add(compileb, 7);
JMenu menu = new JMenu(Messages.getString("EnigmaRunner.MENU_ENIGMA")); //$NON-NLS-1$
menu.setFont(LGM.lnfFont.deriveFont(Font.BOLD));
busy = addItem(Messages.getString("EnigmaRunner.MENU_BUSY"));
busy.setEnabled(false);
busy.setVisible(false);
menu.add(busy);
run = addItem(Messages.getString("EnigmaRunner.MENU_RUN")); //$NON-NLS-1$
run.addActionListener(this);
run.setIcon(LGM.getIconForKey("EnigmaPlugin.EXECUTE"));
run.setAccelerator(KeyStroke.getKeyStroke("F5"));
menu.add(run);
debug = addItem(Messages.getString("EnigmaRunner.MENU_DEBUG")); //$NON-NLS-1$
debug.addActionListener(this);
debug.setIcon(LGM.getIconForKey("EnigmaPlugin.DEBUG"));
debug.setAccelerator(KeyStroke.getKeyStroke("F6"));
menu.add(debug);
design = addItem(Messages.getString("EnigmaRunner.MENU_DESIGN")); //$NON-NLS-1$
design.addActionListener(this);
design.setAccelerator(KeyStroke.getKeyStroke("F7"));
menu.add(design);
compile = addItem(Messages.getString("EnigmaRunner.MENU_COMPILE")); //$NON-NLS-1$
compile.addActionListener(this);
compile.setIcon(LGM.getIconForKey("EnigmaPlugin.COMPILE"));
compile.setAccelerator(KeyStroke.getKeyStroke("F8"));
menu.add(compile);
rebuild = addItem(Messages.getString("EnigmaRunner.MENU_REBUILD_ALL")); //$NON-NLS-1$
rebuild.addActionListener(this);
rebuild.setIcon(LGM.getIconForKey("EnigmaPlugin.REBUILD_ALL"));
rebuild.setAccelerator(KeyStroke.getKeyStroke("F9"));
menu.add(rebuild);
menu.addSeparator();
mImport = addItem(Messages.getString("EnigmaRunner.MENU_IMPORT")); //$NON-NLS-1$
mImport.addActionListener(this);
menu.add(mImport);
menu.addSeparator();
JMenuItem mi = addItem(Messages.getString("EnigmaRunner.MENU_SETTINGS")); //$NON-NLS-1$
mi.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
node.openFrame();
}
});
menu.add(mi);
JMenu sub = new JMenu(Messages.getString("EnigmaRunner.MENU_KEYWORDS")); //$NON-NLS-1$
sub.setFont(LGM.lnfFont.deriveFont(Font.BOLD));
menu.add(sub);
showFunctions = addItem(KEY_MODES[FUNCTIONS]);
showFunctions.addActionListener(this);
sub.add(showFunctions);
showGlobals = addItem(KEY_MODES[GLOBALS]);
showGlobals.addActionListener(this);
sub.add(showGlobals);
showTypes = addItem(KEY_MODES[TYPES]);
showTypes.addActionListener(this);
sub.add(showTypes);
LGM.frame.getJMenuBar().add(menu,1);
}
| public void populateMenu()
{
runb = new JButton(); //$NON-NLS-1$
runb.addActionListener(this);
runb.setToolTipText(Messages.getString("EnigmaRunner.MENU_RUN"));
runb.setIcon(LGM.getIconForKey("EnigmaPlugin.EXECUTE"));
LGM.tool.add(new JToolBar.Separator(), 4);
LGM.tool.add(runb, 5);
debugb = new JButton(); //$NON-NLS-1$
debugb.addActionListener(this);
debugb.setToolTipText(Messages.getString("EnigmaRunner.MENU_DEBUG"));
debugb.setIcon(LGM.getIconForKey("EnigmaPlugin.DEBUG"));
LGM.tool.add(debugb, 6);
compileb = new JButton(); //$NON-NLS-1$
compileb.addActionListener(this);
compileb.setToolTipText(Messages.getString("EnigmaRunner.MENU_COMPILE"));
compileb.setIcon(LGM.getIconForKey("EnigmaPlugin.COMPILE"));
LGM.tool.add(compileb, 7);
JMenu menu = new JMenu(Messages.getString("EnigmaRunner.MENU_BUILD")); //$NON-NLS-1$
menu.setFont(LGM.lnfFont.deriveFont(Font.BOLD, 14));
busy = addItem(Messages.getString("EnigmaRunner.MENU_BUSY"));
busy.setEnabled(false);
busy.setVisible(false);
menu.add(busy);
run = addItem(Messages.getString("EnigmaRunner.MENU_RUN")); //$NON-NLS-1$
run.addActionListener(this);
run.setIcon(LGM.getIconForKey("EnigmaPlugin.EXECUTE"));
run.setAccelerator(KeyStroke.getKeyStroke("F5"));
menu.add(run);
debug = addItem(Messages.getString("EnigmaRunner.MENU_DEBUG")); //$NON-NLS-1$
debug.addActionListener(this);
debug.setIcon(LGM.getIconForKey("EnigmaPlugin.DEBUG"));
debug.setAccelerator(KeyStroke.getKeyStroke("F6"));
menu.add(debug);
design = addItem(Messages.getString("EnigmaRunner.MENU_DESIGN")); //$NON-NLS-1$
design.addActionListener(this);
design.setAccelerator(KeyStroke.getKeyStroke("F7"));
menu.add(design);
compile = addItem(Messages.getString("EnigmaRunner.MENU_COMPILE")); //$NON-NLS-1$
compile.addActionListener(this);
compile.setIcon(LGM.getIconForKey("EnigmaPlugin.COMPILE"));
compile.setAccelerator(KeyStroke.getKeyStroke("F8"));
menu.add(compile);
rebuild = addItem(Messages.getString("EnigmaRunner.MENU_REBUILD_ALL")); //$NON-NLS-1$
rebuild.addActionListener(this);
rebuild.setIcon(LGM.getIconForKey("EnigmaPlugin.REBUILD_ALL"));
rebuild.setAccelerator(KeyStroke.getKeyStroke("F9"));
menu.add(rebuild);
menu.addSeparator();
mImport = addItem(Messages.getString("EnigmaRunner.MENU_IMPORT")); //$NON-NLS-1$
mImport.addActionListener(this);
menu.add(mImport);
menu.addSeparator();
JMenuItem mi = addItem(Messages.getString("EnigmaRunner.MENU_SETTINGS")); //$NON-NLS-1$
mi.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
node.openFrame();
}
});
menu.add(mi);
JMenu sub = new JMenu(Messages.getString("EnigmaRunner.MENU_KEYWORDS")); //$NON-NLS-1$
sub.setFont(LGM.lnfFont.deriveFont(Font.BOLD));
menu.add(sub);
showFunctions = addItem(KEY_MODES[FUNCTIONS]);
showFunctions.addActionListener(this);
sub.add(showFunctions);
showGlobals = addItem(KEY_MODES[GLOBALS]);
showGlobals.addActionListener(this);
sub.add(showGlobals);
showTypes = addItem(KEY_MODES[TYPES]);
showTypes.addActionListener(this);
sub.add(showTypes);
LGM.frame.getJMenuBar().add(menu,1);
}
|
diff --git a/src/api/org/openmrs/util/OpenmrsUtil.java b/src/api/org/openmrs/util/OpenmrsUtil.java
index 2412dc31..199f68af 100644
--- a/src/api/org/openmrs/util/OpenmrsUtil.java
+++ b/src/api/org/openmrs/util/OpenmrsUtil.java
@@ -1,2006 +1,2005 @@
/**
* The contents of this file are subject to the OpenMRS Public 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://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.util;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.Vector;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.zip.ZipEntry;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.openmrs.Cohort;
import org.openmrs.Concept;
import org.openmrs.ConceptNumeric;
import org.openmrs.Drug;
import org.openmrs.EncounterType;
import org.openmrs.Form;
import org.openmrs.Location;
import org.openmrs.Person;
import org.openmrs.PersonAttributeType;
import org.openmrs.Program;
import org.openmrs.ProgramWorkflowState;
import org.openmrs.User;
import org.openmrs.api.APIException;
import org.openmrs.api.AdministrationService;
import org.openmrs.api.ConceptService;
import org.openmrs.api.InvalidCharactersPasswordException;
import org.openmrs.api.PasswordException;
import org.openmrs.api.PatientService;
import org.openmrs.api.ShortPasswordException;
import org.openmrs.api.WeakPasswordException;
import org.openmrs.api.context.Context;
import org.openmrs.cohort.CohortSearchHistory;
import org.openmrs.logic.LogicCriteria;
import org.openmrs.module.ModuleException;
import org.openmrs.patient.IdentifierValidator;
import org.openmrs.propertyeditor.CohortEditor;
import org.openmrs.propertyeditor.ConceptEditor;
import org.openmrs.propertyeditor.DrugEditor;
import org.openmrs.propertyeditor.EncounterTypeEditor;
import org.openmrs.propertyeditor.FormEditor;
import org.openmrs.propertyeditor.LocationEditor;
import org.openmrs.propertyeditor.PersonAttributeTypeEditor;
import org.openmrs.propertyeditor.ProgramEditor;
import org.openmrs.propertyeditor.ProgramWorkflowStateEditor;
import org.openmrs.report.EvaluationContext;
import org.openmrs.reporting.CohortFilter;
import org.openmrs.reporting.PatientFilter;
import org.openmrs.reporting.PatientSearch;
import org.openmrs.reporting.PatientSearchReportObject;
import org.openmrs.reporting.SearchArgument;
import org.openmrs.xml.OpenmrsCycleStrategy;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.load.Persister;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.NoSuchMessageException;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
/**
* Utility methods used in openmrs
*/
public class OpenmrsUtil {
private static Log log = LogFactory.getLog(OpenmrsUtil.class);
private static Map<Locale, SimpleDateFormat> dateFormatCache = new HashMap<Locale, SimpleDateFormat>();
/**
* @param idWithoutCheckdigit
* @return int - the calculated check digit for the given string
* @throws Exception
* @deprecated Use {@link PatientService#getIdentifierValidator(String)}
* @should get valid check digits
*/
public static int getCheckDigit(String idWithoutCheckdigit) throws Exception {
PatientService ps = Context.getPatientService();
IdentifierValidator piv = ps.getDefaultIdentifierValidator();
String withCheckDigit = piv.getValidIdentifier(idWithoutCheckdigit);
char checkDigitChar = withCheckDigit.charAt(withCheckDigit.length() - 1);
if (Character.isDigit(checkDigitChar))
return Integer.parseInt("" + checkDigitChar);
else {
switch (checkDigitChar) {
case 'A':
case 'a':
return 0;
case 'B':
case 'b':
return 1;
case 'C':
case 'c':
return 2;
case 'D':
case 'd':
return 3;
case 'E':
case 'e':
return 4;
case 'F':
case 'f':
return 5;
case 'G':
case 'g':
return 6;
case 'H':
case 'h':
return 7;
case 'I':
case 'i':
return 8;
case 'J':
case 'j':
return 9;
default:
return 10;
}
}
}
/**
* @param id
* @return true/false whether id has a valid check digit
* @throws Exception on invalid characters and invalid id formation
* @deprecated Should be using {@link PatientService#getIdentifierValidator(String)}
* @should validate correct check digits
* @should not validate invalid check digits
* @should throw error if given an invalid character in id
*/
public static boolean isValidCheckDigit(String id) throws Exception {
PatientService ps = Context.getPatientService();
IdentifierValidator piv = ps.getDefaultIdentifierValidator();
return piv.isValid(id);
}
/**
* Compares origList to newList returning map of differences
*
* @param origList
* @param newList
* @return [List toAdd, List toDelete] with respect to origList
*/
public static <E extends Object> Collection<Collection<E>> compareLists(Collection<E> origList, Collection<E> newList) {
// TODO finish function
Collection<Collection<E>> returnList = new Vector<Collection<E>>();
Collection<E> toAdd = new LinkedList<E>();
Collection<E> toDel = new LinkedList<E>();
// loop over the new list.
for (E currentNewListObj : newList) {
// loop over the original list
boolean foundInList = false;
for (E currentOrigListObj : origList) {
// checking if the current new list object is in the original
// list
if (currentNewListObj.equals(currentOrigListObj)) {
foundInList = true;
origList.remove(currentOrigListObj);
break;
}
}
if (!foundInList)
toAdd.add(currentNewListObj);
// all found new objects were removed from the orig list,
// leaving only objects needing to be removed
toDel = origList;
}
returnList.add(toAdd);
returnList.add(toDel);
return returnList;
}
public static boolean isStringInArray(String str, String[] arr) {
boolean retVal = false;
if (str != null && arr != null) {
for (int i = 0; i < arr.length; i++) {
if (str.equals(arr[i]))
retVal = true;
}
}
return retVal;
}
public static Boolean isInNormalNumericRange(Float value, ConceptNumeric concept) {
if (concept.getHiNormal() == null || concept.getLowNormal() == null)
return false;
return (value <= concept.getHiNormal() && value >= concept.getLowNormal());
}
public static Boolean isInCriticalNumericRange(Float value, ConceptNumeric concept) {
if (concept.getHiCritical() == null || concept.getLowCritical() == null)
return false;
return (value <= concept.getHiCritical() && value >= concept.getLowCritical());
}
public static Boolean isInAbsoluteNumericRange(Float value, ConceptNumeric concept) {
if (concept.getHiAbsolute() == null || concept.getLowAbsolute() == null)
return false;
return (value <= concept.getHiAbsolute() && value >= concept.getLowAbsolute());
}
public static Boolean isValidNumericValue(Float value, ConceptNumeric concept) {
if (concept.getHiAbsolute() == null || concept.getLowAbsolute() == null)
return true;
return (value <= concept.getHiAbsolute() && value >= concept.getLowAbsolute());
}
/**
* Return a string representation of the given file
*
* @param file
* @return String file contents
* @throws IOException
*/
public static String getFileAsString(File file) throws IOException {
StringBuffer fileData = new StringBuffer(1000);
BufferedReader reader = new BufferedReader(new FileReader(file));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1) {
String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
return fileData.toString();
}
/**
* Return a byte array representation of the given file
*
* @param file
* @return byte[] file contents
* @throws IOException
*/
public static byte[] getFileAsBytes(File file) throws IOException {
try {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] b = new byte[fileInputStream.available()];
fileInputStream.read(b);
fileInputStream.close();
return b;
}
catch (Exception e) {
log.error("Unable to get file as byte array", e);
}
return null;
}
/**
* Copy file from inputStream onto the outputStream inputStream is not closed in this method
* outputStream /is/ closed at completion of this method
*
* @param inputStream Stream to copy from
* @param outputStream Stream/location to copy to
* @throws IOException thrown if an error occurs during read/write
*/
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException {
if (inputStream == null || outputStream == null) {
if (outputStream != null) {
try {
outputStream.close();
}
catch (Exception e) { /* pass */}
}
return;
}
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(inputStream);
out = new BufferedOutputStream(outputStream);
while (true) {
int data = in.read();
if (data == -1) {
break;
}
out.write(data);
}
}
finally {
if (in != null)
in.close();
if (out != null)
out.close();
try {
outputStream.close();
}
catch (Exception e) { /* pass */}
}
}
/**
* Look for a file named <code>filename</code> in folder
*
* @param folder
* @param filename
* @return true/false whether filename exists in folder
*/
public static boolean folderContains(File folder, String filename) {
if (folder == null)
return false;
if (!folder.isDirectory())
return false;
for (File f : folder.listFiles()) {
if (f.getName().equals(filename))
return true;
}
return false;
}
/**
* Initialize global settings Find and load modules
*
* @param p properties from runtime configuration
*/
public static void startup(Properties p) {
// Override global OpenMRS constants if specified by the user
// Allow for "demo" mode where patient data is obscured
String val = p.getProperty("obscure_patients", null);
if (val != null && "true".equalsIgnoreCase(val))
OpenmrsConstants.OBSCURE_PATIENTS = true;
val = p.getProperty("obscure_patients.family_name", null);
if (val != null)
OpenmrsConstants.OBSCURE_PATIENTS_FAMILY_NAME = val;
val = p.getProperty("obscure_patients.given_name", null);
if (val != null)
OpenmrsConstants.OBSCURE_PATIENTS_GIVEN_NAME = val;
val = p.getProperty("obscure_patients.middle_name", null);
if (val != null)
OpenmrsConstants.OBSCURE_PATIENTS_MIDDLE_NAME = val;
// Override the default "openmrs" database name
val = p.getProperty("connection.database_name", null);
if (val == null) {
// the database name wasn't supplied explicitly, guess it
// from the connection string
val = p.getProperty("connection.url", null);
if (val != null) {
try {
int endIndex = val.lastIndexOf("?");
if (endIndex == -1)
endIndex = val.length();
int startIndex = val.lastIndexOf("/", endIndex);
val = val.substring(startIndex + 1, endIndex);
OpenmrsConstants.DATABASE_NAME = val;
}
catch (Exception e) {
log.fatal("Database name cannot be configured from 'connection.url' ."
+ "Either supply 'connection.database_name' or correct the url", e);
}
}
}
// set the business database name
val = p.getProperty("connection.database_business_name", null);
if (val == null)
val = OpenmrsConstants.DATABASE_NAME;
OpenmrsConstants.DATABASE_BUSINESS_NAME = val;
// set the application data directory
val = p.getProperty(OpenmrsConstants.APPLICATION_DATA_DIRECTORY_RUNTIME_PROPERTY, null);
if (val != null)
OpenmrsConstants.APPLICATION_DATA_DIRECTORY = val;
// set global log level
applyLogLevels();
}
/**
* Set the org.openmrs log4j logger's level if global property log.level.openmrs (
* OpenmrsConstants.GLOBAL_PROPERTY_LOG_LEVEL ) exists. Valid values for global property are
* trace, debug, info, warn, error or fatal.
*/
public static void applyLogLevels() {
AdministrationService adminService = Context.getAdministrationService();
String logLevel = adminService.getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_LOG_LEVEL);
String logClass = OpenmrsConstants.LOG_CLASS_DEFAULT;
// potentially have different levels here. only doing org.openmrs right now
applyLogLevel(logClass, logLevel);
}
/**
* Set the log4j log level for class <code>logClass</code> to <code>logLevel</code>.
*
* @param logClass optional string giving the class level to change. Defaults to
* OpenmrsConstants.LOG_CLASS_DEFAULT . Should be something like org.openmrs.___
* @param logLevel one of OpenmrsConstants.LOG_LEVEL_*
*/
public static void applyLogLevel(String logClass, String logLevel) {
if (logLevel != null) {
// the default log level is org.openmrs
if (logClass == null || "".equals(logClass))
logClass = OpenmrsConstants.LOG_CLASS_DEFAULT;
Logger logger = Logger.getLogger(logClass);
logLevel = logLevel.toLowerCase();
if (OpenmrsConstants.LOG_LEVEL_TRACE.equals(logLevel)) {
logger.setLevel(Level.TRACE);
} else if (OpenmrsConstants.LOG_LEVEL_DEBUG.equals(logLevel)) {
logger.setLevel(Level.DEBUG);
} else if (OpenmrsConstants.LOG_LEVEL_INFO.equals(logLevel)) {
logger.setLevel(Level.INFO);
} else if (OpenmrsConstants.LOG_LEVEL_WARN.equals(logLevel)) {
logger.setLevel(Level.WARN);
} else if (OpenmrsConstants.LOG_LEVEL_ERROR.equals(logLevel)) {
logger.setLevel(Level.ERROR);
} else if (OpenmrsConstants.LOG_LEVEL_FATAL.equals(logLevel)) {
logger.setLevel(Level.FATAL);
} else {
log.warn("Global property " + logLevel + " is invalid. "
+ "Valid values are trace, debug, info, warn, error or fatal");
}
}
}
/**
* Takes a String like "size=compact|order=date" and returns a Map<String,String> from the keys
* to the values.
*
* @param paramList <code>String</code> with a list of parameters
* @return Map<String, String> of the parameters passed
*/
public static Map<String, String> parseParameterList(String paramList) {
Map<String, String> ret = new HashMap<String, String>();
if (paramList != null && paramList.length() > 0) {
String[] args = paramList.split("\\|");
for (String s : args) {
int ind = s.indexOf('=');
if (ind <= 0) {
throw new IllegalArgumentException("Misformed argument in dynamic page specification string: '" + s
+ "' is not 'key=value'.");
}
String name = s.substring(0, ind);
String value = s.substring(ind + 1);
ret.put(name, value);
}
}
return ret;
}
public static <Arg1, Arg2 extends Arg1> boolean nullSafeEquals(Arg1 d1, Arg2 d2) {
if (d1 == null)
return d2 == null;
else if (d2 == null)
return false;
else
return d1.equals(d2);
}
/**
* Compares two java.util.Date objects, but handles java.sql.Timestamp (which is not directly
* comparable to a date) by dropping its nanosecond value.
*/
public static int compare(Date d1, Date d2) {
if (d1 instanceof Timestamp && d2 instanceof Timestamp) {
return d1.compareTo(d2);
}
if (d1 instanceof Timestamp)
d1 = new Date(((Timestamp) d1).getTime());
if (d2 instanceof Timestamp)
d2 = new Date(((Timestamp) d2).getTime());
return d1.compareTo(d2);
}
/**
* Compares two Date/Timestamp objects, treating null as the earliest possible date.
*/
public static int compareWithNullAsEarliest(Date d1, Date d2) {
if (d1 == null && d2 == null)
return 0;
if (d1 == null)
return -1;
else if (d2 == null)
return 1;
else
return compare(d1, d2);
}
/**
* Compares two Date/Timestamp objects, treating null as the earliest possible date.
*/
public static int compareWithNullAsLatest(Date d1, Date d2) {
if (d1 == null && d2 == null)
return 0;
if (d1 == null)
return 1;
else if (d2 == null)
return -1;
else
return compare(d1, d2);
}
public static <E extends Comparable<E>> int compareWithNullAsLowest(E c1, E c2) {
if (c1 == null && c2 == null)
return 0;
if (c1 == null)
return -1;
else if (c2 == null)
return 1;
else
return c1.compareTo(c2);
}
public static <E extends Comparable<E>> int compareWithNullAsGreatest(E c1, E c2) {
if (c1 == null && c2 == null)
return 0;
if (c1 == null)
return 1;
else if (c2 == null)
return -1;
else
return c1.compareTo(c2);
}
/**
* @deprecated this method is not currently used within OpenMRS and is a duplicate of
* {@link Person#getAge(Date)}
*/
public static Integer ageFromBirthdate(Date birthdate) {
if (birthdate == null)
return null;
Calendar today = Calendar.getInstance();
Calendar bday = Calendar.getInstance();
bday.setTime(birthdate);
int age = today.get(Calendar.YEAR) - bday.get(Calendar.YEAR);
//Adjust age when today's date is before the person's birthday
int todaysMonth = today.get(Calendar.MONTH);
int bdayMonth = bday.get(Calendar.MONTH);
int todaysDay = today.get(Calendar.DAY_OF_MONTH);
int bdayDay = bday.get(Calendar.DAY_OF_MONTH);
if (todaysMonth < bdayMonth) {
age--;
} else if (todaysMonth == bdayMonth && todaysDay < bdayDay) {
// we're only comparing on month and day, not minutes, etc
age--;
}
return age;
}
/**
* Converts a collection to a String with a specified separator between all elements
*
* @param c Collection to be joined
* @param separator string to put between all elements
* @return a String representing the toString() of all elements in c, separated by separator
*/
public static <E extends Object> String join(Collection<E> c, String separator) {
if (c == null)
return "";
StringBuilder ret = new StringBuilder();
for (Iterator<E> i = c.iterator(); i.hasNext();) {
ret.append(i.next());
if (i.hasNext())
ret.append(separator);
}
return ret.toString();
}
public static Set<Concept> conceptSetHelper(String descriptor) {
Set<Concept> ret = new HashSet<Concept>();
if (descriptor == null || descriptor.length() == 0)
return ret;
ConceptService cs = Context.getConceptService();
for (StringTokenizer st = new StringTokenizer(descriptor, "|"); st.hasMoreTokens();) {
String s = st.nextToken().trim();
boolean isSet = s.startsWith("set:");
if (isSet)
s = s.substring(4).trim();
Concept c = null;
if (s.startsWith("name:")) {
String name = s.substring(5).trim();
c = cs.getConceptByName(name);
} else {
try {
c = cs.getConcept(Integer.valueOf(s.trim()));
}
catch (Exception ex) {}
}
if (c != null) {
if (isSet) {
List<Concept> inSet = cs.getConceptsByConceptSet(c);
ret.addAll(inSet);
} else {
ret.add(c);
}
}
}
return ret;
}
public static List<Concept> delimitedStringToConceptList(String delimitedString, String delimiter, Context context) {
List<Concept> ret = null;
if (delimitedString != null && context != null) {
String[] tokens = delimitedString.split(delimiter);
for (String token : tokens) {
Integer conceptId = null;
try {
conceptId = new Integer(token);
}
catch (NumberFormatException nfe) {
conceptId = null;
}
Concept c = null;
if (conceptId != null) {
c = Context.getConceptService().getConcept(conceptId);
} else {
c = Context.getConceptService().getConceptByName(token);
}
if (c != null) {
if (ret == null)
ret = new ArrayList<Concept>();
ret.add(c);
}
}
}
return ret;
}
public static Map<String, Concept> delimitedStringToConceptMap(String delimitedString, String delimiter) {
Map<String, Concept> ret = null;
if (delimitedString != null) {
String[] tokens = delimitedString.split(delimiter);
for (String token : tokens) {
Concept c = OpenmrsUtil.getConceptByIdOrName(token);
if (c != null) {
if (ret == null)
ret = new HashMap<String, Concept>();
ret.put(token, c);
}
}
}
return ret;
}
// DEPRECATED: This method should now be replaced with ConceptService.getConceptByIdOrName()
public static Concept getConceptByIdOrName(String idOrName) {
Concept c = null;
Integer conceptId = null;
try {
conceptId = new Integer(idOrName);
}
catch (NumberFormatException nfe) {
conceptId = null;
}
if (conceptId != null) {
c = Context.getConceptService().getConcept(conceptId);
} else {
c = Context.getConceptService().getConceptByName(idOrName);
}
return c;
}
// TODO: properly handle duplicates
public static List<Concept> conceptListHelper(String descriptor) {
List<Concept> ret = new ArrayList<Concept>();
if (descriptor == null || descriptor.length() == 0)
return ret;
ConceptService cs = Context.getConceptService();
for (StringTokenizer st = new StringTokenizer(descriptor, "|"); st.hasMoreTokens();) {
String s = st.nextToken().trim();
boolean isSet = s.startsWith("set:");
if (isSet)
s = s.substring(4).trim();
Concept c = null;
if (s.startsWith("name:")) {
String name = s.substring(5).trim();
c = cs.getConceptByName(name);
} else {
try {
c = cs.getConcept(Integer.valueOf(s.trim()));
}
catch (Exception ex) {}
}
if (c != null) {
if (isSet) {
List<Concept> inSet = cs.getConceptsByConceptSet(c);
ret.addAll(inSet);
} else {
ret.add(c);
}
}
}
return ret;
}
/**
* Return a date that is the same day as the passed in date, but the hours and seconds are the
* latest possible for that day.
*
* @param date date to adjust
* @return a date that is the last possible time in the day
*/
public static Date lastSecondOfDay(Date date) {
if (date == null)
return null;
Calendar c = Calendar.getInstance();
c.setTime(date);
// TODO: figure out the right way to do this (or at least set milliseconds to zero)
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.add(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.SECOND, -1);
return c.getTime();
}
public static Date safeDate(Date d1) {
return new Date(d1.getTime());
}
/**
* Recursively deletes files in the given <code>dir</code> folder
*
* @param dir File directory to delete
* @return true/false whether the delete was completed successfully
* @throws IOException if <code>dir</code> is not a directory
*/
public static boolean deleteDirectory(File dir) throws IOException {
if (!dir.exists() || !dir.isDirectory())
throw new IOException("Could not delete directory '" + dir.getAbsolutePath() + "' (not a directory)");
if (log.isDebugEnabled())
log.debug("Deleting directory " + dir.getAbsolutePath());
File[] fileList = dir.listFiles();
for (File f : fileList) {
if (f.isDirectory())
deleteDirectory(f);
boolean success = f.delete();
if (log.isDebugEnabled())
log.debug(" deleting " + f.getName() + " : " + (success ? "ok" : "failed"));
if (!success)
f.deleteOnExit();
}
boolean success = dir.delete();
if (!success) {
log.warn(" ...could not remove directory: " + dir.getAbsolutePath());
dir.deleteOnExit();
}
if (success && log.isDebugEnabled())
log.debug(" ...and directory itself");
return success;
}
/**
* Utility method to convert local URL to a File object.
*
* @param url an URL
* @return file object for given URL or <code>null</code> if URL is not local
* @should return null given null parameter
*/
public static File url2file(final URL url) {
if (url == null || !"file".equalsIgnoreCase(url.getProtocol())) {
return null;
}
return new File(url.getFile().replaceAll("%20", " "));
}
/**
* Opens input stream for given resource. This method behaves differently for different URL
* types:
* <ul>
* <li>for <b>local files</b> it returns buffered file input stream;</li>
* <li>for <b>local JAR files</b> it reads resource content into memory buffer and returns byte
* array input stream that wraps those buffer (this prevents locking JAR file);</li>
* <li>for <b>common URL's</b> this method simply opens stream to that URL using standard URL
* API.</li>
* </ul>
* It is not recommended to use this method for big resources within JAR files.
*
* @param url resource URL
* @return input stream for given resource
* @throws IOException if any I/O error has occurred
*/
public static InputStream getResourceInputStream(final URL url) throws IOException {
File file = url2file(url);
if (file != null) {
return new BufferedInputStream(new FileInputStream(file));
}
if (!"jar".equalsIgnoreCase(url.getProtocol())) {
return url.openStream();
}
String urlStr = url.toExternalForm();
if (urlStr.endsWith("!/")) {
//JAR URL points to a root entry
throw new FileNotFoundException(url.toExternalForm());
}
int p = urlStr.indexOf("!/");
if (p == -1) {
throw new MalformedURLException(url.toExternalForm());
}
String path = urlStr.substring(p + 2);
file = url2file(new URL(urlStr.substring(4, p)));
if (file == null) {// non-local JAR file URL
return url.openStream();
}
JarFile jarFile = new JarFile(file);
try {
ZipEntry entry = jarFile.getEntry(path);
if (entry == null) {
throw new FileNotFoundException(url.toExternalForm());
}
InputStream in = jarFile.getInputStream(entry);
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
copyFile(in, out);
return new ByteArrayInputStream(out.toByteArray());
}
finally {
in.close();
}
}
finally {
jarFile.close();
}
}
/**
* @return The path to the directory on the file system that will hold miscellaneous data about
* the application (runtime properties, modules, etc)
*/
public static String getApplicationDataDirectory() {
String filepath = null;
if (OpenmrsConstants.APPLICATION_DATA_DIRECTORY != null) {
filepath = OpenmrsConstants.APPLICATION_DATA_DIRECTORY;
} else {
if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM)
filepath = System.getProperty("user.home") + File.separator + ".OpenMRS";
else
filepath = System.getProperty("user.home") + File.separator + "Application Data" + File.separator
+ "OpenMRS";
filepath = filepath + File.separator;
}
File folder = new File(filepath);
if (!folder.exists())
folder.mkdirs();
return filepath;
}
/**
* Find the given folderName in the application data directory. Or, treat folderName like an
* absolute url to a directory
*
* @param folderName
* @return folder capable of storing information
*/
public static File getDirectoryInApplicationDataDirectory(String folderName) throws APIException {
// try to load the repository folder straight away.
File folder = new File(folderName);
// if the property wasn't a full path already, assume it was intended to be a folder in the
// application directory
if (!folder.isAbsolute()) {
folder = new File(OpenmrsUtil.getApplicationDataDirectory(), folderName);
}
// now create the directory folder if it doesn't exist
if (!folder.exists()) {
log.warn("'" + folder.getAbsolutePath() + "' doesn't exist. Creating directories now.");
folder.mkdirs();
}
if (!folder.isDirectory())
throw new APIException("'" + folder.getAbsolutePath() + "' should be a directory but it is not");
return folder;
}
/**
* Save the given xml document to the given outfile
*
* @param doc Document to be saved
* @param outFile file pointer to the location the xml file is to be saved to
*/
public static void saveDocument(Document doc, File outFile) {
OutputStream outStream = null;
try {
outStream = new FileOutputStream(outFile);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
DocumentType doctype = doc.getDoctype();
if (doctype != null) {
transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, doctype.getPublicId());
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, doctype.getSystemId());
}
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(outStream);
transformer.transform(source, result);
}
catch (TransformerException e) {
throw new ModuleException("Error while saving dwrmodulexml back to dwr-modules.xml", e);
}
catch (FileNotFoundException e) {
throw new ModuleException("/WEB-INF/dwr-modules.xml file doesn't exist.", e);
}
finally {
try {
if (outStream != null)
outStream.close();
}
catch (Exception e) {
log.warn("Unable to close outstream", e);
}
}
}
public static List<Integer> delimitedStringToIntegerList(String delimitedString, String delimiter) {
List<Integer> ret = new ArrayList<Integer>();
String[] tokens = delimitedString.split(delimiter);
for (String token : tokens) {
token = token.trim();
if (token.length() == 0)
continue;
else
ret.add(Integer.valueOf(token));
}
return ret;
}
public static boolean isConceptInList(Concept concept, List<Concept> list) {
boolean ret = false;
if (concept != null && list != null) {
for (Concept c : list) {
if (c.equals(concept)) {
ret = true;
break;
}
}
}
return ret;
}
public static Date fromDateHelper(Date comparisonDate, Integer withinLastDays, Integer withinLastMonths,
Integer untilDaysAgo, Integer untilMonthsAgo, Date sinceDate, Date untilDate) {
Date ret = null;
if (withinLastDays != null || withinLastMonths != null) {
Calendar gc = Calendar.getInstance();
gc.setTime(comparisonDate != null ? comparisonDate : new Date());
if (withinLastDays != null)
gc.add(Calendar.DAY_OF_MONTH, -withinLastDays);
if (withinLastMonths != null)
gc.add(Calendar.MONTH, -withinLastMonths);
ret = gc.getTime();
}
if (sinceDate != null && (ret == null || sinceDate.after(ret)))
ret = sinceDate;
return ret;
}
public static Date toDateHelper(Date comparisonDate, Integer withinLastDays, Integer withinLastMonths,
Integer untilDaysAgo, Integer untilMonthsAgo, Date sinceDate, Date untilDate) {
Date ret = null;
if (untilDaysAgo != null || untilMonthsAgo != null) {
Calendar gc = Calendar.getInstance();
gc.setTime(comparisonDate != null ? comparisonDate : new Date());
if (untilDaysAgo != null)
gc.add(Calendar.DAY_OF_MONTH, -untilDaysAgo);
if (untilMonthsAgo != null)
gc.add(Calendar.MONTH, -untilMonthsAgo);
ret = gc.getTime();
}
if (untilDate != null && (ret == null || untilDate.before(ret)))
ret = untilDate;
return ret;
}
/**
* @param collection
* @param elements
* @return Whether _collection_ contains any of _elements_
*/
public static <T> boolean containsAny(Collection<T> collection, Collection<T> elements) {
for (T obj : elements) {
if (collection.contains(obj))
return true;
}
return false;
}
/**
* Allows easy manipulation of a Map<?, Set>
*/
public static <K, V> void addToSetMap(Map<K, Set<V>> map, K key, V obj) {
Set<V> set = map.get(key);
if (set == null) {
set = new HashSet<V>();
map.put(key, set);
}
set.add(obj);
}
public static <K, V> void addToListMap(Map<K, List<V>> map, K key, V obj) {
List<V> list = map.get(key);
if (list == null) {
list = new ArrayList<V>();
map.put(key, list);
}
list.add(obj);
}
/**
* Get the current user's date format Will look similar to "mm-dd-yyyy". Depends on user's
* locale.
*
* @return a simple date format
* @deprecated use {@link Context#getDateFormat()} or {@link #getDateFormat(Context#getLocale())} instead
*/
public static SimpleDateFormat getDateFormat() {
return Context.getDateFormat();
}
/**
* Get the current user's date format Will look similar to "mm-dd-yyyy". Depends on user's
* locale.
*
* @return a simple date format
* @should return a pattern with four y characters in it
* @since 1.5
*/
public static SimpleDateFormat getDateFormat(Locale locale) {
if (dateFormatCache.containsKey(locale))
return dateFormatCache.get(locale);
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale);
String pattern = sdf.toPattern();
if (!pattern.contains("yyyy")) {
// otherwise, change the pattern to be a four digit year
pattern = pattern.replaceFirst("yy", "yyyy");
sdf.applyPattern(pattern);
}
if (!pattern.contains("MM")) {
// change the pattern to be a two digit month
pattern = pattern.replaceFirst("M", "MM");
sdf.applyPattern(pattern);
}
if (!pattern.contains("dd")) {
// change the pattern to be a two digit day
pattern = pattern.replaceFirst("d", "dd");
sdf.applyPattern(pattern);
}
dateFormatCache.put(locale, sdf);
return sdf;
}
/**
* @deprecated see reportingcompatibility module
*/
@Deprecated
public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history) {
return toPatientFilter(search, history, null);
}
/**
* Takes a String (e.g. a user-entered one) and parses it into an object of the specified class
*
* @param string
* @param clazz
* @return Object of type <code>clazz</code> with the data from <code>string</code>
*/
@SuppressWarnings("unchecked")
public static Object parse(String string, Class clazz) {
try {
// If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean)
Method valueOfMethod = null;
try {
valueOfMethod = clazz.getMethod("valueOf", String.class);
}
catch (NoSuchMethodException ex) {}
if (valueOfMethod != null) {
return valueOfMethod.invoke(null, string);
} else if (clazz.isEnum()) {
// Special-case for enum types
List<Enum> constants = Arrays.asList((Enum[]) clazz.getEnumConstants());
for (Enum e : constants)
if (e.toString().equals(string))
return e;
throw new IllegalArgumentException(string + " is not a legal value of enum class " + clazz);
} else if (String.class.equals(clazz)) {
return string;
} else if (Location.class.equals(clazz)) {
try {
Integer.parseInt(string);
LocationEditor ed = new LocationEditor();
ed.setAsText(string);
return ed.getValue();
}
catch (NumberFormatException ex) {
return Context.getLocationService().getLocation(string);
}
} else if (Concept.class.equals(clazz)) {
ConceptEditor ed = new ConceptEditor();
ed.setAsText(string);
return ed.getValue();
} else if (Program.class.equals(clazz)) {
ProgramEditor ed = new ProgramEditor();
ed.setAsText(string);
return ed.getValue();
} else if (ProgramWorkflowState.class.equals(clazz)) {
ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor();
ed.setAsText(string);
return ed.getValue();
} else if (EncounterType.class.equals(clazz)) {
EncounterTypeEditor ed = new EncounterTypeEditor();
ed.setAsText(string);
return ed.getValue();
} else if (Form.class.equals(clazz)) {
FormEditor ed = new FormEditor();
ed.setAsText(string);
return ed.getValue();
} else if (Drug.class.equals(clazz)) {
DrugEditor ed = new DrugEditor();
ed.setAsText(string);
return ed.getValue();
} else if (PersonAttributeType.class.equals(clazz)) {
PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor();
ed.setAsText(string);
return ed.getValue();
} else if (Cohort.class.equals(clazz)) {
CohortEditor ed = new CohortEditor();
ed.setAsText(string);
return ed.getValue();
} else if (Date.class.equals(clazz)) {
// TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching.
CustomDateEditor ed = new CustomDateEditor(Context.getDateFormat(), true, 10);
ed.setAsText(string);
return ed.getValue();
} else if (Object.class.equals(clazz)) {
// TODO: Decide whether this is a hack. Currently setting Object arguments with a String
return string;
} else {
throw new IllegalArgumentException("Don't know how to handle class: " + clazz);
}
}
catch (Exception ex) {
log.error("error converting \"" + string + "\" to " + clazz, ex);
throw new IllegalArgumentException(ex);
}
}
/**
* Uses reflection to translate a PatientSearch into a PatientFilter
*
* @deprecated see reportingcompatibility module
*/
@SuppressWarnings("unchecked")
@Deprecated
public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history,
EvaluationContext evalContext) {
if (search.isSavedSearchReference()) {
PatientSearch ps = ((PatientSearchReportObject) Context.getReportObjectService().getReportObject(
search.getSavedSearchId())).getPatientSearch();
return toPatientFilter(ps, history, evalContext);
} else if (search.isSavedFilterReference()) {
return Context.getReportObjectService().getPatientFilterById(search.getSavedFilterId());
} else if (search.isSavedCohortReference()) {
Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId());
// to prevent lazy loading exceptions, cache the member ids here
if (c != null)
c.getMemberIds().size();
return new CohortFilter(c);
} else if (search.isComposition()) {
if (history == null && search.requiresHistory())
throw new IllegalArgumentException("You can't evaluate this search without a history");
else
return search.cloneCompositionAsFilter(history, evalContext);
} else {
Class clz = search.getFilterClass();
if (clz == null)
throw new IllegalArgumentException("search must be saved, composition, or must have a class specified");
log.debug("About to instantiate " + clz);
PatientFilter pf = null;
try {
pf = (PatientFilter) clz.newInstance();
}
catch (Exception ex) {
log.error("Couldn't instantiate a " + search.getFilterClass(), ex);
return null;
}
Class[] stringSingleton = { String.class };
if (search.getArguments() != null) {
for (SearchArgument sa : search.getArguments()) {
if (log.isDebugEnabled())
log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue());
PropertyDescriptor pd = null;
try {
pd = new PropertyDescriptor(sa.getName(), clz);
}
catch (IntrospectionException ex) {
log.error("Error while examining property " + sa.getName(), ex);
continue;
}
Class<?> realPropertyType = pd.getPropertyType();
// instantiate the value of the search argument
String valueAsString = sa.getValue();
String testForExpression = search.getArgumentValue(sa.getName());
if (testForExpression != null) {
- valueAsString = testForExpression;
- log.debug("Setting " + sa.getName() + " to: " + valueAsString);
- if (evalContext != null && EvaluationContext.isExpression(valueAsString)) {
+ log.debug("Setting " + sa.getName() + " to: " + testForExpression);
+ if (evalContext != null && EvaluationContext.isExpression(testForExpression)) {
Object evaluated = evalContext.evaluateExpression(testForExpression);
if (evaluated != null) {
if (evaluated instanceof Date)
valueAsString = Context.getDateFormat().format((Date) evaluated);
else
valueAsString = evaluated.toString();
}
log.debug("Evaluated " + sa.getName() + " to: " + valueAsString);
}
}
Object value = null;
Class<?> valueClass = sa.getPropertyClass();
try {
// If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean)
Method valueOfMethod = null;
try {
valueOfMethod = valueClass.getMethod("valueOf", stringSingleton);
}
catch (NoSuchMethodException ex) {}
if (valueOfMethod != null) {
Object[] holder = { valueAsString };
value = valueOfMethod.invoke(pf, holder);
} else if (realPropertyType.isEnum()) {
// Special-case for enum types
List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants());
for (Enum e : constants) {
if (e.toString().equals(valueAsString)) {
value = e;
break;
}
}
} else if (String.class.equals(valueClass)) {
value = valueAsString;
} else if (Location.class.equals(valueClass)) {
LocationEditor ed = new LocationEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Concept.class.equals(valueClass)) {
ConceptEditor ed = new ConceptEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Program.class.equals(valueClass)) {
ProgramEditor ed = new ProgramEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (ProgramWorkflowState.class.equals(valueClass)) {
ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (EncounterType.class.equals(valueClass)) {
EncounterTypeEditor ed = new EncounterTypeEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Form.class.equals(valueClass)) {
FormEditor ed = new FormEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Drug.class.equals(valueClass)) {
DrugEditor ed = new DrugEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (PersonAttributeType.class.equals(valueClass)) {
PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Cohort.class.equals(valueClass)) {
CohortEditor ed = new CohortEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Date.class.equals(valueClass)) {
// TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching.
DateFormat df = Context.getDateFormat(); // new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale());
CustomDateEditor ed = new CustomDateEditor(df, true, 10);
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (LogicCriteria.class.equals(valueClass)) {
value = Context.getLogicService().parseString(valueAsString);
} else {
// TODO: Decide whether this is a hack. Currently setting Object arguments with a String
value = valueAsString;
}
}
catch (Exception ex) {
log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex);
continue;
}
if (value != null) {
if (realPropertyType.isAssignableFrom(valueClass)) {
log.debug("setting value of " + sa.getName() + " to " + value);
try {
pd.getWriteMethod().invoke(pf, value);
}
catch (Exception ex) {
log.error(
"Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex);
continue;
}
} else if (Collection.class.isAssignableFrom(realPropertyType)) {
log.debug(sa.getName() + " is a Collection property");
// if realPropertyType is a collection, add this value to it (possibly after instantiating)
try {
Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null);
if (collection == null) {
// we need to instantiate this collection. I'm going with the following rules, which should be rethought:
// SortedSet -> TreeSet
// Set -> HashSet
// Otherwise -> ArrayList
if (SortedSet.class.isAssignableFrom(realPropertyType)) {
collection = new TreeSet();
log.debug("instantiated a TreeSet");
pd.getWriteMethod().invoke(pf, collection);
} else if (Set.class.isAssignableFrom(realPropertyType)) {
collection = new HashSet();
log.debug("instantiated a HashSet");
pd.getWriteMethod().invoke(pf, collection);
} else {
collection = new ArrayList();
log.debug("instantiated an ArrayList");
pd.getWriteMethod().invoke(pf, collection);
}
}
collection.add(value);
}
catch (Exception ex) {
log.error("Error instantiating collection for property " + sa.getName() + " whose class is "
+ realPropertyType, ex);
continue;
}
} else {
log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType
+ " but is given as " + valueClass);
}
}
}
}
log.debug("Returning " + pf);
return pf;
}
}
/**
* Loops over the collection to check to see if the given object is in that collection. This
* method <i>only</i> uses the .equals() method for comparison. This should be used in the
* patient/person objects on their collections. Their collections are SortedSets which use the
* compareTo method for equality as well. The compareTo method is currently optimized for
* sorting, not for equality. A null <code>obj</code> will return false
*
* @param objects collection to loop over
* @param obj Object to look for in the <code>objects</code>
* @return true/false whether the given object is found
* @should use equals method for comparison instead of compareTo given List collection
* @should use equals method for comparison instead of compareTo given SortedSet collection
*/
public static boolean collectionContains(Collection<?> objects, Object obj) {
if (obj == null || objects == null)
return false;
for (Object o : objects) {
if (o != null && o.equals(obj))
return true;
}
return false;
}
/**
* Get a serializer that will do the common type of serialization and deserialization. Cycles of
* objects are taken into account
*
* @return Serializer to do the (de)serialization
* @deprecated - Use OpenmrsSerializer from
* Context.getSerializationService.getDefaultSerializer() Note, this uses a
* different Serialization mechanism, so you may need to use this for conversion
*/
@Deprecated
public static Serializer getSerializer() {
return new Persister(new OpenmrsCycleStrategy());
}
/**
* Get a short serializer that will only do the very basic serialization necessary. This is
* controlled by the objects that are being serialized via the @Replace methods
*
* @return Serializer to do the short (de)serialization
* @see OpenmrsConstants#SHORT_SERIALIZATION
* @deprecated - Use OpenmrsSerializer from
* Context.getSerializationService.getDefaultSerializer() Note, this uses a
* different Serialization mechanism, so you may need to use this for conversion
*/
@Deprecated
public static Serializer getShortSerializer() {
return new Persister(new OpenmrsCycleStrategy(true));
}
/**
* True/false whether the current serialization is supposed to be a short serialization. A
* shortened serialization This should be called from methods marked with the @Replace notation
* that take in a single <code>Map</code> parameter.
*
* @param sessionMap current serialization session
* @return true/false whether or not to do the shortened serialization
* @deprecated - use SerializationService and OpenmrsSerializer implementation for Serialization
*/
@Deprecated
public static boolean isShortSerialization(Map<?, ?> sessionMap) {
return sessionMap.containsKey(OpenmrsConstants.SHORT_SERIALIZATION);
}
/**
* Gets an out File object. If date is not provided, the current timestamp is used. If user is
* not provided, the user id is not put into the filename. Assumes dir is already created
*
* @param dir directory to make the random filename in
* @param date optional Date object used for the name
* @param user optional User creating this file object
* @return file new file that is able to be written to
*/
public static File getOutFile(File dir, Date date, User user) {
File outFile;
do {
// format to print date in filenmae
DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd-HHmm-ssSSS");
// use current date if none provided
if (date == null)
date = new Date();
StringBuilder filename = new StringBuilder();
// the start of the filename is the time so we can do some sorting
filename.append(dateFormat.format(date));
// insert the user id if they provided it
if (user != null) {
filename.append("-");
filename.append(user.getUserId());
filename.append("-");
}
// the end of the filename is a randome number between 0 and 10000
filename.append((int) (Math.random() * 10000));
filename.append(".xml");
outFile = new File(dir, filename.toString());
// set to null to avoid very minimal possiblity of an infinite loop
date = null;
} while (outFile.exists());
return outFile;
}
/**
* Creates a relatively acceptable unique string of the give size
*
* @return unique string
*/
public static String generateUid(Integer size) {
StringBuffer sb = new StringBuffer(size);
for (int i = 0; i < size; i++) {
int ch = (int) (Math.random() * 62);
if (ch < 10) // 0-9
sb.append(ch);
else if (ch < 36) // a-z
sb.append((char) (ch - 10 + 'a'));
else
sb.append((char) (ch - 36 + 'A'));
}
return sb.toString();
}
/**
* Creates a uid of length 20
*
* @see #generateUid(Integer)
*/
public static String generateUid() {
return generateUid(20);
}
/**
* Post the given map of variables to the given url string
*
* @param urlString valid http url to post data to
* @param dataToPost Map<String, String> of key value pairs to post to urlString
* @return response from urlString after posting
*/
public static String postToUrl(String urlString, Map<String, String> dataToPost) {
OutputStreamWriter wr = null;
BufferedReader rd = null;
String response = "";
StringBuffer data = null;
try {
// Construct data
for (Map.Entry<String, String> entry : dataToPost.entrySet()) {
// skip over invalid post variables
if (entry.getKey() == null || entry.getValue() == null)
continue;
// create the string buffer if this is the first variable
if (data == null)
data = new StringBuffer();
else
data.append("&"); // only append this if its _not_ the first datum
// finally, setup the actual post string
data.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
data.append("=");
data.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
// Send the data
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Length", String.valueOf(data.length()));
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data.toString());
wr.flush();
wr.close();
// Get the response
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response = response + line + "\n";
}
}
catch (Exception e) {
log.warn("Exception while posting to : " + urlString, e);
log.warn("Reponse from server was: " + response);
}
finally {
if (wr != null)
try {
wr.close();
}
catch (Exception e) { /* pass */}
if (rd != null)
try {
rd.close();
}
catch (Exception e) { /* pass */}
}
return response;
}
/**
* Convenience method to replace Properties.store(), which isn't UTF-8 compliant
* NOTE: In Java 6, you will be able to pass the load() and store() methods a UTF-8 Reader/Writer
* object as an argument, making this method unnecessary.
*
* @param properties
* @param file
* @param comment
*/
public static void storeProperties(Properties properties, File file, String comment) {
OutputStream outStream = null;
try {
outStream = new FileOutputStream(file, true);
storeProperties(properties, outStream, comment);
}
catch (IOException ex) {
log.error("Unable to create file " + file.getAbsolutePath() + " in storeProperties routine.");
}
finally {
try {
if (outStream != null)
outStream.close();
}
catch (IOException ioe) {
//pass
}
}
}
/**
* Convenience method to replace Properties.store(), which isn't UTF-8 compliant
* NOTE: In Java 6, you will be able to pass the load() and store() methods a UTF-8 Reader/Writer
* object as an argument.
*
* @param properties
* @param file
* @param comment (which appears in comments in properties file)
*/
public static void storeProperties(Properties properties, OutputStream outStream, String comment) {
try {
OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(outStream), "UTF-8");
Writer out = new BufferedWriter(osw);
if (comment != null)
out.write("\n#" + comment + "\n");
out.write("#" + new Date() + "\n");
for (Map.Entry<Object, Object> e : properties.entrySet()) {
out.write(e.getKey() + "=" + e.getValue() + "\n");
}
out.write("\n");
out.flush();
out.close();
}
catch (FileNotFoundException fnfe) {
log.error("target file not found" + fnfe);
}
catch (UnsupportedEncodingException ex) { //pass
log.error("unsupported encoding error hit" + ex);
}
catch (IOException ioex) {
log.error("IO exception encountered trying to append to properties file" + ioex);
}
}
/**
* This method is a replacement for Properties.load(InputStream) so that we can load in utf-8
* characters. Currently the load method expects the inputStream to point to a latin1 encoded
* file.
* NOTE: In Java 6, you will be able to pass the load() and store() methods a UTF-8 Reader/Writer
* object as an argument, making this method unnecesary.
*
* @param props the properties object to write into
* @param input the input stream to read from
*/
public static void loadProperties(Properties props, InputStream input) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
while (reader.ready()) {
String line = reader.readLine();
if (line.length() > 0 && line.charAt(0) != '#') {
int pos = line.indexOf("=");
if (pos > 0) {
String keyString = line.substring(0, pos);
String valueString = line.substring(pos + 1);
if (keyString != null && keyString.length() > 0) {
props.put(keyString, fixPropertiesValueString(valueString));
}
}
}
}
reader.close();
}
catch (UnsupportedEncodingException uee) {
log.error("Unsupported encoding used in properties file " + uee);
}
catch (IOException ioe) {
log.error("Unable to read properties from properties file " + ioe);
}
}
/**
* By default java will escape colons and equal signs when writing properites files. <br/>
* <br/>
* This method turns escaped colons into colons and escaped equal signs into just equal signs.
*
* @param value the value portion of a properties file to fix
* @return the value with escaped characters fixed
*/
private static String fixPropertiesValueString(String value) {
String returnString = value.replace("\n", "");
returnString = returnString.replace("\\:", ":");
returnString = returnString.replace("\\=", "=");
return returnString;
}
/**
* Utility method for getting the translation for the passed code
* @param code the message key to lookup
* @param args the replacement values for the translation string
* @return the message, or if not found, the code
*/
public static String getMessage(String code, Object... args) {
Locale l = Context.getLocale();
try {
String translation = Context.getMessageSourceService().getMessage(code, args, l);
if (translation != null) {
return translation;
}
}
catch (NoSuchMessageException e) {
log.warn("Message code <"+code+"> not found for locale " + l);
}
return code;
}
/**
* Utility to check the validity of a password for a certain {@link User}.
* Passwords must be non-null. Their required strength is configured via global properties:
* <table>
* <tr><th>Description</th><th>Property</th><th>Default Value</th></tr>
* <tr>
* <th>Require that it not match the {@link User}'s username or system id
* <th>{@link OpenmrsConstants#GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID}</th>
* <th>true</th>
* </tr>
* <tr>
* <th>Require a minimum length
* <th>{@link OpenmrsConstants#GP_PASSWORD_MINIMUM_LENGTH}</th>
* <th>8</th>
* </tr>
* <tr>
* <th>Require both an upper and lower case character
* <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE}</th>
* <th>true</th>
* </tr>
* <tr>
* <th>Require at least one numeric character
* <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_DIGIT}</th>
* <th>true</th>
* </tr>
* <tr>
* <th>Require at least one non-numeric character
* <th>{@link OpenmrsConstants#GP_PASSWORD_REQUIRES_NON_DIGIT}</th>
* <th>true</th>
* </tr>
* <tr>
* <th>Require a match on the specified regular expression
* <th>{@link OpenmrsConstants#GP_PASSWORD_CUSTOM_REGEX}</th>
* <th>null</th>
* </tr>
* </table>
*
* @param username user name of the user with password to validated
* @param password string that will be validated
* @param systemId system id of the user with password to be validated
* @throws PasswordException
* @since 1.5
* @should fail with short password by default
* @should fail with short password if not allowed
* @should pass with short password if allowed
* @should fail with digit only password by default
* @should fail with digit only password if not allowed
* @should pass with digit only password if allowed
* @should fail with char only password by default
* @should fail with char only password if not allowed
* @should pass with char only password if allowed
* @should fail without both upper and lower case password by default
* @should fail without both upper and lower case password if not allowed
* @should pass without both upper and lower case password if allowed
* @should fail with password equals to user name by default
* @should fail with password equals to user name if not allowed
* @should pass with password equals to user name if allowed
* @should fail with password equals to system id by default
* @should fail with password equals to system id if not allowed
* @should pass with password equals to system id if allowed
* @should fail with password not matching configured regex
* @should pass with password matching configured regex
* @should allow password to contain non alphanumeric characters
* @should allow password to contain white spaces
*/
public static void validatePassword(String username, String password, String systemId) throws PasswordException {
AdministrationService svc = Context.getAdministrationService();
if (password == null) {
throw new WeakPasswordException();
}
String userGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_CANNOT_MATCH_USERNAME_OR_SYSTEMID, "true");
if ("true".equals(userGp) && (password.equals(username) || password.equals(systemId))) {
throw new WeakPasswordException();
}
String lengthGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_MINIMUM_LENGTH, "8");
if (StringUtils.isNotEmpty(lengthGp)) {
try {
int minLength = Integer.parseInt(lengthGp);
if (password.length() < minLength) {
throw new ShortPasswordException(getMessage("error.password.length", lengthGp));
}
}
catch (NumberFormatException nfe) {
log.warn("Error in global property <" + OpenmrsConstants.GP_PASSWORD_MINIMUM_LENGTH + "> must be an Integer");
}
}
String caseGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_UPPER_AND_LOWER_CASE, "true");
if ("true".equals(caseGp) && !containsUpperAndLowerCase(password)) {
throw new InvalidCharactersPasswordException(getMessage("error.password.requireMixedCase"));
}
String digitGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_DIGIT, "true");
if ("true".equals(digitGp) && !containsDigit(password)) {
throw new InvalidCharactersPasswordException(getMessage("error.password.requireNumber"));
}
String nonDigitGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_REQUIRES_NON_DIGIT, "true");
if ("true".equals(nonDigitGp) && containsOnlyDigits(password)) {
throw new InvalidCharactersPasswordException(getMessage("error.password.requireLetter"));
}
String regexGp = svc.getGlobalProperty(OpenmrsConstants.GP_PASSWORD_CUSTOM_REGEX);
if (StringUtils.isNotEmpty(regexGp)) {
try {
Pattern pattern = Pattern.compile(regexGp);
Matcher matcher = pattern.matcher(password);
if (!matcher.matches()) {
throw new InvalidCharactersPasswordException(getMessage("error.password.different"));
}
}
catch (PatternSyntaxException pse) {
log.warn("Invalid regex of " + regexGp + " defined in global property <" +
OpenmrsConstants.GP_PASSWORD_CUSTOM_REGEX + ">.");
}
}
}
/**
* @param test the string to test
* @return true if the passed string contains both upper and lower case characters
* @should return true if string contains upper and lower case
* @should return false if string does not contain lower case characters
* @should return false if string does not contain upper case characters
*/
public static boolean containsUpperAndLowerCase(String test) {
if (test != null) {
Pattern pattern = Pattern.compile("^(?=.*?[A-Z])(?=.*?[a-z])[\\w|\\W]*$");
Matcher matcher = pattern.matcher(test);
return matcher.matches();
}
return false;
}
/**
* @param test the string to test
* @return true if the passed string contains only numeric characters
* @should return true if string contains only digits
* @should return false if string contains any non-digits
*/
public static boolean containsOnlyDigits(String test) {
if (test != null) {
for (char c : test.toCharArray()) {
if (!Character.isDigit(c)) {
return false;
}
}
}
return StringUtils.isNotEmpty(test);
}
/**
* @param test the string to test
* @return true if the passed string contains any numeric characters
* @should return true if string contains any digits
* @should return false if string contains no digits
*/
public static boolean containsDigit(String test) {
if (test != null) {
for (char c : test.toCharArray()) {
if (Character.isDigit(c)) {
return true;
}
}
}
return false;
}
}
| true | true | public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history,
EvaluationContext evalContext) {
if (search.isSavedSearchReference()) {
PatientSearch ps = ((PatientSearchReportObject) Context.getReportObjectService().getReportObject(
search.getSavedSearchId())).getPatientSearch();
return toPatientFilter(ps, history, evalContext);
} else if (search.isSavedFilterReference()) {
return Context.getReportObjectService().getPatientFilterById(search.getSavedFilterId());
} else if (search.isSavedCohortReference()) {
Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId());
// to prevent lazy loading exceptions, cache the member ids here
if (c != null)
c.getMemberIds().size();
return new CohortFilter(c);
} else if (search.isComposition()) {
if (history == null && search.requiresHistory())
throw new IllegalArgumentException("You can't evaluate this search without a history");
else
return search.cloneCompositionAsFilter(history, evalContext);
} else {
Class clz = search.getFilterClass();
if (clz == null)
throw new IllegalArgumentException("search must be saved, composition, or must have a class specified");
log.debug("About to instantiate " + clz);
PatientFilter pf = null;
try {
pf = (PatientFilter) clz.newInstance();
}
catch (Exception ex) {
log.error("Couldn't instantiate a " + search.getFilterClass(), ex);
return null;
}
Class[] stringSingleton = { String.class };
if (search.getArguments() != null) {
for (SearchArgument sa : search.getArguments()) {
if (log.isDebugEnabled())
log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue());
PropertyDescriptor pd = null;
try {
pd = new PropertyDescriptor(sa.getName(), clz);
}
catch (IntrospectionException ex) {
log.error("Error while examining property " + sa.getName(), ex);
continue;
}
Class<?> realPropertyType = pd.getPropertyType();
// instantiate the value of the search argument
String valueAsString = sa.getValue();
String testForExpression = search.getArgumentValue(sa.getName());
if (testForExpression != null) {
valueAsString = testForExpression;
log.debug("Setting " + sa.getName() + " to: " + valueAsString);
if (evalContext != null && EvaluationContext.isExpression(valueAsString)) {
Object evaluated = evalContext.evaluateExpression(testForExpression);
if (evaluated != null) {
if (evaluated instanceof Date)
valueAsString = Context.getDateFormat().format((Date) evaluated);
else
valueAsString = evaluated.toString();
}
log.debug("Evaluated " + sa.getName() + " to: " + valueAsString);
}
}
Object value = null;
Class<?> valueClass = sa.getPropertyClass();
try {
// If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean)
Method valueOfMethod = null;
try {
valueOfMethod = valueClass.getMethod("valueOf", stringSingleton);
}
catch (NoSuchMethodException ex) {}
if (valueOfMethod != null) {
Object[] holder = { valueAsString };
value = valueOfMethod.invoke(pf, holder);
} else if (realPropertyType.isEnum()) {
// Special-case for enum types
List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants());
for (Enum e : constants) {
if (e.toString().equals(valueAsString)) {
value = e;
break;
}
}
} else if (String.class.equals(valueClass)) {
value = valueAsString;
} else if (Location.class.equals(valueClass)) {
LocationEditor ed = new LocationEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Concept.class.equals(valueClass)) {
ConceptEditor ed = new ConceptEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Program.class.equals(valueClass)) {
ProgramEditor ed = new ProgramEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (ProgramWorkflowState.class.equals(valueClass)) {
ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (EncounterType.class.equals(valueClass)) {
EncounterTypeEditor ed = new EncounterTypeEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Form.class.equals(valueClass)) {
FormEditor ed = new FormEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Drug.class.equals(valueClass)) {
DrugEditor ed = new DrugEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (PersonAttributeType.class.equals(valueClass)) {
PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Cohort.class.equals(valueClass)) {
CohortEditor ed = new CohortEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Date.class.equals(valueClass)) {
// TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching.
DateFormat df = Context.getDateFormat(); // new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale());
CustomDateEditor ed = new CustomDateEditor(df, true, 10);
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (LogicCriteria.class.equals(valueClass)) {
value = Context.getLogicService().parseString(valueAsString);
} else {
// TODO: Decide whether this is a hack. Currently setting Object arguments with a String
value = valueAsString;
}
}
catch (Exception ex) {
log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex);
continue;
}
if (value != null) {
if (realPropertyType.isAssignableFrom(valueClass)) {
log.debug("setting value of " + sa.getName() + " to " + value);
try {
pd.getWriteMethod().invoke(pf, value);
}
catch (Exception ex) {
log.error(
"Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex);
continue;
}
} else if (Collection.class.isAssignableFrom(realPropertyType)) {
log.debug(sa.getName() + " is a Collection property");
// if realPropertyType is a collection, add this value to it (possibly after instantiating)
try {
Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null);
if (collection == null) {
// we need to instantiate this collection. I'm going with the following rules, which should be rethought:
// SortedSet -> TreeSet
// Set -> HashSet
// Otherwise -> ArrayList
if (SortedSet.class.isAssignableFrom(realPropertyType)) {
collection = new TreeSet();
log.debug("instantiated a TreeSet");
pd.getWriteMethod().invoke(pf, collection);
} else if (Set.class.isAssignableFrom(realPropertyType)) {
collection = new HashSet();
log.debug("instantiated a HashSet");
pd.getWriteMethod().invoke(pf, collection);
} else {
collection = new ArrayList();
log.debug("instantiated an ArrayList");
pd.getWriteMethod().invoke(pf, collection);
}
}
collection.add(value);
}
catch (Exception ex) {
log.error("Error instantiating collection for property " + sa.getName() + " whose class is "
+ realPropertyType, ex);
continue;
}
} else {
log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType
+ " but is given as " + valueClass);
}
}
}
}
log.debug("Returning " + pf);
return pf;
}
}
| public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history,
EvaluationContext evalContext) {
if (search.isSavedSearchReference()) {
PatientSearch ps = ((PatientSearchReportObject) Context.getReportObjectService().getReportObject(
search.getSavedSearchId())).getPatientSearch();
return toPatientFilter(ps, history, evalContext);
} else if (search.isSavedFilterReference()) {
return Context.getReportObjectService().getPatientFilterById(search.getSavedFilterId());
} else if (search.isSavedCohortReference()) {
Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId());
// to prevent lazy loading exceptions, cache the member ids here
if (c != null)
c.getMemberIds().size();
return new CohortFilter(c);
} else if (search.isComposition()) {
if (history == null && search.requiresHistory())
throw new IllegalArgumentException("You can't evaluate this search without a history");
else
return search.cloneCompositionAsFilter(history, evalContext);
} else {
Class clz = search.getFilterClass();
if (clz == null)
throw new IllegalArgumentException("search must be saved, composition, or must have a class specified");
log.debug("About to instantiate " + clz);
PatientFilter pf = null;
try {
pf = (PatientFilter) clz.newInstance();
}
catch (Exception ex) {
log.error("Couldn't instantiate a " + search.getFilterClass(), ex);
return null;
}
Class[] stringSingleton = { String.class };
if (search.getArguments() != null) {
for (SearchArgument sa : search.getArguments()) {
if (log.isDebugEnabled())
log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue());
PropertyDescriptor pd = null;
try {
pd = new PropertyDescriptor(sa.getName(), clz);
}
catch (IntrospectionException ex) {
log.error("Error while examining property " + sa.getName(), ex);
continue;
}
Class<?> realPropertyType = pd.getPropertyType();
// instantiate the value of the search argument
String valueAsString = sa.getValue();
String testForExpression = search.getArgumentValue(sa.getName());
if (testForExpression != null) {
log.debug("Setting " + sa.getName() + " to: " + testForExpression);
if (evalContext != null && EvaluationContext.isExpression(testForExpression)) {
Object evaluated = evalContext.evaluateExpression(testForExpression);
if (evaluated != null) {
if (evaluated instanceof Date)
valueAsString = Context.getDateFormat().format((Date) evaluated);
else
valueAsString = evaluated.toString();
}
log.debug("Evaluated " + sa.getName() + " to: " + valueAsString);
}
}
Object value = null;
Class<?> valueClass = sa.getPropertyClass();
try {
// If there's a valueOf(String) method, just use that (will cover at least String, Integer, Double, Boolean)
Method valueOfMethod = null;
try {
valueOfMethod = valueClass.getMethod("valueOf", stringSingleton);
}
catch (NoSuchMethodException ex) {}
if (valueOfMethod != null) {
Object[] holder = { valueAsString };
value = valueOfMethod.invoke(pf, holder);
} else if (realPropertyType.isEnum()) {
// Special-case for enum types
List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants());
for (Enum e : constants) {
if (e.toString().equals(valueAsString)) {
value = e;
break;
}
}
} else if (String.class.equals(valueClass)) {
value = valueAsString;
} else if (Location.class.equals(valueClass)) {
LocationEditor ed = new LocationEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Concept.class.equals(valueClass)) {
ConceptEditor ed = new ConceptEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Program.class.equals(valueClass)) {
ProgramEditor ed = new ProgramEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (ProgramWorkflowState.class.equals(valueClass)) {
ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (EncounterType.class.equals(valueClass)) {
EncounterTypeEditor ed = new EncounterTypeEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Form.class.equals(valueClass)) {
FormEditor ed = new FormEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Drug.class.equals(valueClass)) {
DrugEditor ed = new DrugEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (PersonAttributeType.class.equals(valueClass)) {
PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Cohort.class.equals(valueClass)) {
CohortEditor ed = new CohortEditor();
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (Date.class.equals(valueClass)) {
// TODO: this uses the date format from the current session, which could cause problems if the user changes it after searching.
DateFormat df = Context.getDateFormat(); // new SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), Context.getLocale());
CustomDateEditor ed = new CustomDateEditor(df, true, 10);
ed.setAsText(valueAsString);
value = ed.getValue();
} else if (LogicCriteria.class.equals(valueClass)) {
value = Context.getLogicService().parseString(valueAsString);
} else {
// TODO: Decide whether this is a hack. Currently setting Object arguments with a String
value = valueAsString;
}
}
catch (Exception ex) {
log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex);
continue;
}
if (value != null) {
if (realPropertyType.isAssignableFrom(valueClass)) {
log.debug("setting value of " + sa.getName() + " to " + value);
try {
pd.getWriteMethod().invoke(pf, value);
}
catch (Exception ex) {
log.error(
"Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex);
continue;
}
} else if (Collection.class.isAssignableFrom(realPropertyType)) {
log.debug(sa.getName() + " is a Collection property");
// if realPropertyType is a collection, add this value to it (possibly after instantiating)
try {
Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null);
if (collection == null) {
// we need to instantiate this collection. I'm going with the following rules, which should be rethought:
// SortedSet -> TreeSet
// Set -> HashSet
// Otherwise -> ArrayList
if (SortedSet.class.isAssignableFrom(realPropertyType)) {
collection = new TreeSet();
log.debug("instantiated a TreeSet");
pd.getWriteMethod().invoke(pf, collection);
} else if (Set.class.isAssignableFrom(realPropertyType)) {
collection = new HashSet();
log.debug("instantiated a HashSet");
pd.getWriteMethod().invoke(pf, collection);
} else {
collection = new ArrayList();
log.debug("instantiated an ArrayList");
pd.getWriteMethod().invoke(pf, collection);
}
}
collection.add(value);
}
catch (Exception ex) {
log.error("Error instantiating collection for property " + sa.getName() + " whose class is "
+ realPropertyType, ex);
continue;
}
} else {
log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType
+ " but is given as " + valueClass);
}
}
}
}
log.debug("Returning " + pf);
return pf;
}
}
|
diff --git a/Disasteroids/trunk/src/disasteroids/TutorialMode.java b/Disasteroids/trunk/src/disasteroids/TutorialMode.java
index 77d7f00..1929dd1 100644
--- a/Disasteroids/trunk/src/disasteroids/TutorialMode.java
+++ b/Disasteroids/trunk/src/disasteroids/TutorialMode.java
@@ -1,222 +1,222 @@
/**
* DISASTEROIDS
* TutorialMode.java
*/
package disasteroids;
import disasteroids.gui.AsteroidsFrame;
import disasteroids.gui.Local;
import disasteroids.weapons.BulletManager;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
/**
* A short tutorial for players.
* @author Phillip Cohen
*/
public class TutorialMode implements GameMode
{
int stage = 0, counter = 0;
double playerStartX = 0, playerStartY = 0;
public void act()
{
if ( Local.isStuffNull() )
return;
++counter;
// Welcome!
if ( stage == 0 && counter > 200 )
nextStage();
// You are the ship.
if ( stage == 1 && counter > 100 )
nextStage();
// Use the arrow keys.
if ( stage == 2 && counter > 200 )
{
nextStage();
- Game.getInstance().getObjectManager().addObject( new Asteroid( Local.getLocalPlayer().getX(), Local.getLocalPlayer().getY() - 150, 0, -0.5, 150, 5 ) );
+ Game.getInstance().getObjectManager().addObject( new Asteroid( Local.getLocalPlayer().getX(), Local.getLocalPlayer().getY() - 150, 0, -0.5, 150, 5 ), true );
}
// Ram it!
if ( stage == 3 && counter > 50 && Game.getInstance().getObjectManager().getAsteroids().size() != 1 )
nextStage();
// Good!
if ( ( stage == 4 || stage == 6 || stage == 10 || stage == 16 ) && counter > 135 )
nextStage();
// Shoot!
if ( stage == 5 && counter > 250 && Game.getInstance().getObjectManager().getAsteroids().size() == 0 )
nextStage();
// You have two cows - ah, weapons.
if ( stage == 7 && counter > 200 )
nextStage();
// Use whichever.
if ( stage == 8 && Local.getLocalPlayer().getWeaponManager() instanceof BulletManager )
{
nextStage();
for ( int i = 0; i < 8; i++ )
Game.getInstance().getObjectManager().addObject( new Asteroid( Local.getLocalPlayer().getX() + Util.getRandomGenerator().nextInt( 900 ) - 450,
Local.getLocalPlayer().getY() - 700 + Util.getRandomGenerator().nextInt( 80 ) - 40,
- Util.getRandomGenerator().nextMidpointDouble( 2 ), Util.getRandomGenerator().nextDouble() * 2, Util.getRandomGenerator().nextInt( 50 ) + 60, 50 ) );
+ Util.getRandomGenerator().nextMidpointDouble( 2 ), Util.getRandomGenerator().nextDouble() * 2, Util.getRandomGenerator().nextInt( 50 ) + 60, 50 ), true );
}
// Take it out!
if ( stage == 9 && counter > 250 && Game.getInstance().getObjectManager().getAsteroids().size() == 0 )
nextStage();
// Boring.
if ( stage == 11 && counter > 200 )
nextStage();
// Aliens!
if ( stage == 12 && counter > 200 )
nextStage();
// Manuevering.
if ( stage == 13 && counter > 200 )
nextStage();
// Strafing.
if ( stage == 14 && counter > 700 )
{
nextStage();
for ( int i = 0; i < 4; i++ )
Game.getInstance().getObjectManager().addObject( new Alien( Local.getLocalPlayer().getX() + Util.getRandomGenerator().nextInt( 900 ) - 450,
Local.getLocalPlayer().getY() - 700 + Util.getRandomGenerator().nextInt( 80 ) - 40,
- Util.getRandomGenerator().nextMidpointDouble( 2 ), Util.getRandomGenerator().nextDouble() * 2 ) );
+ Util.getRandomGenerator().nextMidpointDouble( 2 ), Util.getRandomGenerator().nextDouble() * 2 ), true );
}
// Here they come!
if ( stage == 15 && Game.getInstance().getObjectManager().getBaddies().size() == 0 )
nextStage();
// Berserk.
if ( stage == 17 && counter > 350 )
nextStage();
// Press ~.
if ( stage == 18 && counter > 150 && !Local.getLocalPlayer().getWeapons()[0].canBerserk() )
nextStage();
if ( stage == 19 && counter > 250 )
nextStage();
}
private void nextStage()
{
counter = 0;
++stage;
}
public void draw( Graphics g )
{
Graphics2D g2d = (Graphics2D) g;
Font title = new Font( "Tahoma", Font.BOLD, 24 );
Font textFont = new Font( "Tahoma", Font.BOLD, 12 );
g.setFont( textFont );
int x = 0, y = AsteroidsFrame.frame().getPanel().getHeight() / 4;
String text = "";
g.setColor( Local.getLocalPlayer().getColor() );
switch ( stage )
{
case 0:
g.setFont( title );
y = Math.min( counter * 4, AsteroidsFrame.frame().getPanel().getHeight() / 4 );
text = "Welcome to DISASTEROIDS!";
break;
case 1:
text = "You're the player in the center of the screen.";
break;
case 2:
text = "To move, use the arrow keys.";
break;
case 3:
text = "Try it - ram that asteroid!";
break;
case 4:
case 6:
case 10:
case 16:
text = "Good!";
break;
case 5:
text = "Now try shooting. Press SPACE to shoot.";
break;
case 7:
text = "By default, you have two guns.";
break;
case 8:
text = "You've seen the missile launcher. Press Q to cycle to the MACHINE GUN!";
break;
case 9:
text = "Use whichever gun you like to take out this next wave.";
break;
case 11:
text = "Asteroids are pretty boring.";
break;
case 12:
text = "This is why god made aliens.";
break;
case 13:
text = "You'll need some better manuevering skills, because they fire back.";
break;
case 14:
text = "Use CTRL and NUMPAD0 to strafe left and right.";
break;
case 15:
text = "Here they come!";
break;
case 17:
text = "Our last tidbit of advice is how to BERSERK!";
break;
case 18:
text = "Press ~ to release a powerful shelling of shrapnel!";
break;
case 19:
text = "Would've been helpful earlier, no?";
break;
case 20:
text = "Those're the basics! Enjoy playing the game.";
break;
}
x = (int) ( AsteroidsFrame.frame().getPanel().getWidth() / 2 - g2d.getFont().getStringBounds( text, g2d.getFontRenderContext() ).getWidth() / 2 );
g.drawString( text, x, y );
}
public void flatten( DataOutputStream stream ) throws IOException
{
throw new UnsupportedOperationException( "Tutorials can't be used in net games." );
}
public void optionsKey()
{
try
{
stage = Integer.parseInt( JOptionPane.showInputDialog( null, "Enter the section to skip to.", stage ) );
counter = Integer.MAX_VALUE / 2;
}
catch ( NumberFormatException e )
{
// Do nothing with incorrect or cancelled input.
Running.log( "Invalid section command.", 800 );
}
}
public int id()
{
throw new UnsupportedOperationException( "Tutorials can't be used in net games." );
}
}
| false | true | public void act()
{
if ( Local.isStuffNull() )
return;
++counter;
// Welcome!
if ( stage == 0 && counter > 200 )
nextStage();
// You are the ship.
if ( stage == 1 && counter > 100 )
nextStage();
// Use the arrow keys.
if ( stage == 2 && counter > 200 )
{
nextStage();
Game.getInstance().getObjectManager().addObject( new Asteroid( Local.getLocalPlayer().getX(), Local.getLocalPlayer().getY() - 150, 0, -0.5, 150, 5 ) );
}
// Ram it!
if ( stage == 3 && counter > 50 && Game.getInstance().getObjectManager().getAsteroids().size() != 1 )
nextStage();
// Good!
if ( ( stage == 4 || stage == 6 || stage == 10 || stage == 16 ) && counter > 135 )
nextStage();
// Shoot!
if ( stage == 5 && counter > 250 && Game.getInstance().getObjectManager().getAsteroids().size() == 0 )
nextStage();
// You have two cows - ah, weapons.
if ( stage == 7 && counter > 200 )
nextStage();
// Use whichever.
if ( stage == 8 && Local.getLocalPlayer().getWeaponManager() instanceof BulletManager )
{
nextStage();
for ( int i = 0; i < 8; i++ )
Game.getInstance().getObjectManager().addObject( new Asteroid( Local.getLocalPlayer().getX() + Util.getRandomGenerator().nextInt( 900 ) - 450,
Local.getLocalPlayer().getY() - 700 + Util.getRandomGenerator().nextInt( 80 ) - 40,
Util.getRandomGenerator().nextMidpointDouble( 2 ), Util.getRandomGenerator().nextDouble() * 2, Util.getRandomGenerator().nextInt( 50 ) + 60, 50 ) );
}
// Take it out!
if ( stage == 9 && counter > 250 && Game.getInstance().getObjectManager().getAsteroids().size() == 0 )
nextStage();
// Boring.
if ( stage == 11 && counter > 200 )
nextStage();
// Aliens!
if ( stage == 12 && counter > 200 )
nextStage();
// Manuevering.
if ( stage == 13 && counter > 200 )
nextStage();
// Strafing.
if ( stage == 14 && counter > 700 )
{
nextStage();
for ( int i = 0; i < 4; i++ )
Game.getInstance().getObjectManager().addObject( new Alien( Local.getLocalPlayer().getX() + Util.getRandomGenerator().nextInt( 900 ) - 450,
Local.getLocalPlayer().getY() - 700 + Util.getRandomGenerator().nextInt( 80 ) - 40,
Util.getRandomGenerator().nextMidpointDouble( 2 ), Util.getRandomGenerator().nextDouble() * 2 ) );
}
// Here they come!
if ( stage == 15 && Game.getInstance().getObjectManager().getBaddies().size() == 0 )
nextStage();
// Berserk.
if ( stage == 17 && counter > 350 )
nextStage();
// Press ~.
if ( stage == 18 && counter > 150 && !Local.getLocalPlayer().getWeapons()[0].canBerserk() )
nextStage();
if ( stage == 19 && counter > 250 )
nextStage();
}
| public void act()
{
if ( Local.isStuffNull() )
return;
++counter;
// Welcome!
if ( stage == 0 && counter > 200 )
nextStage();
// You are the ship.
if ( stage == 1 && counter > 100 )
nextStage();
// Use the arrow keys.
if ( stage == 2 && counter > 200 )
{
nextStage();
Game.getInstance().getObjectManager().addObject( new Asteroid( Local.getLocalPlayer().getX(), Local.getLocalPlayer().getY() - 150, 0, -0.5, 150, 5 ), true );
}
// Ram it!
if ( stage == 3 && counter > 50 && Game.getInstance().getObjectManager().getAsteroids().size() != 1 )
nextStage();
// Good!
if ( ( stage == 4 || stage == 6 || stage == 10 || stage == 16 ) && counter > 135 )
nextStage();
// Shoot!
if ( stage == 5 && counter > 250 && Game.getInstance().getObjectManager().getAsteroids().size() == 0 )
nextStage();
// You have two cows - ah, weapons.
if ( stage == 7 && counter > 200 )
nextStage();
// Use whichever.
if ( stage == 8 && Local.getLocalPlayer().getWeaponManager() instanceof BulletManager )
{
nextStage();
for ( int i = 0; i < 8; i++ )
Game.getInstance().getObjectManager().addObject( new Asteroid( Local.getLocalPlayer().getX() + Util.getRandomGenerator().nextInt( 900 ) - 450,
Local.getLocalPlayer().getY() - 700 + Util.getRandomGenerator().nextInt( 80 ) - 40,
Util.getRandomGenerator().nextMidpointDouble( 2 ), Util.getRandomGenerator().nextDouble() * 2, Util.getRandomGenerator().nextInt( 50 ) + 60, 50 ), true );
}
// Take it out!
if ( stage == 9 && counter > 250 && Game.getInstance().getObjectManager().getAsteroids().size() == 0 )
nextStage();
// Boring.
if ( stage == 11 && counter > 200 )
nextStage();
// Aliens!
if ( stage == 12 && counter > 200 )
nextStage();
// Manuevering.
if ( stage == 13 && counter > 200 )
nextStage();
// Strafing.
if ( stage == 14 && counter > 700 )
{
nextStage();
for ( int i = 0; i < 4; i++ )
Game.getInstance().getObjectManager().addObject( new Alien( Local.getLocalPlayer().getX() + Util.getRandomGenerator().nextInt( 900 ) - 450,
Local.getLocalPlayer().getY() - 700 + Util.getRandomGenerator().nextInt( 80 ) - 40,
Util.getRandomGenerator().nextMidpointDouble( 2 ), Util.getRandomGenerator().nextDouble() * 2 ), true );
}
// Here they come!
if ( stage == 15 && Game.getInstance().getObjectManager().getBaddies().size() == 0 )
nextStage();
// Berserk.
if ( stage == 17 && counter > 350 )
nextStage();
// Press ~.
if ( stage == 18 && counter > 150 && !Local.getLocalPlayer().getWeapons()[0].canBerserk() )
nextStage();
if ( stage == 19 && counter > 250 )
nextStage();
}
|
diff --git a/src/heig/igl3/roc2/GUI/MouvementEditor.java b/src/heig/igl3/roc2/GUI/MouvementEditor.java
index e31ea51..15c746e 100644
--- a/src/heig/igl3/roc2/GUI/MouvementEditor.java
+++ b/src/heig/igl3/roc2/GUI/MouvementEditor.java
@@ -1,329 +1,329 @@
package heig.igl3.roc2.GUI;
import heig.igl3.roc2.Business.Budget;
import heig.igl3.roc2.Business.Categorie;
import heig.igl3.roc2.Business.Mouvement;
import heig.igl3.roc2.Business.SousCategorie;
import heig.igl3.roc2.Data.Roc2DB;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;
/**
* Classe MouvementEditor Affichage de l'éditeur de mouvements
*
* @author Raphael Santos, Olivier Francillon, Chris Paccaud, Cédric Bugnon
*
*/
@SuppressWarnings("serial")
public class MouvementEditor extends JDialog implements ActionListener,
ItemListener, FocusListener {
private JPanel panel;
private JTextField libelle, montant;
private JFormattedTextField date;
private JComboBox<Categorie> CBcategorie;
private JComboBox<SousCategorie> CBsousCategorie;
private JComboBox<String> CBtype, CBtypeES;
private JComboBox<Integer> CBperiodicite;
@SuppressWarnings("unused")
// sur lblType
private JLabel lblLibelle, lblMontant, lblDate, lblCategorie,
lblSousCategorie, lblType, lblTypeES, lblPeriodicite;
private JButton btSubmit, btCancel;
public Mouvement mouvement, mouvToEdit;
private Budget budget;
private boolean edit;
/**
* Constructeur
*
* @param frame
* @param modal
* @param budget
*/
public MouvementEditor(JFrame frame, boolean modal, Budget budget) {
super(frame, modal);
this.budget = budget;
MaskFormatter df = null;
try {
df = new MaskFormatter("##.##.####");
} catch (java.text.ParseException e) {
System.err.println(e);
}
;
df.setPlaceholderCharacter('_');
lblLibelle = new JLabel("Libellé:");
lblMontant = new JLabel("Montant:");
lblDate = new JLabel("Date:");
lblCategorie = new JLabel("Catégorie:");
lblSousCategorie = new JLabel("Sous-catégorie:");
lblType = new JLabel("Type:");
lblTypeES = new JLabel("Entrée/Sortie:");
lblPeriodicite = new JLabel("Périodicité:");
libelle = new JTextField(25);
montant = new JTextField(10);
date = new JFormattedTextField(df);
CBtype = new JComboBox<String>();
CBtype.addItem("Ponctuel");
CBtype.addItem("Récurrent");
CBtypeES = new JComboBox<String>();
CBtypeES.addItem("Entrée");
CBtypeES.addItem("Sortie");
CBperiodicite = new JComboBox<Integer>();
- for (int i = 1; i < 12; i++) {
+ for (int i = 1; i <= 12; i++) {
CBperiodicite.addItem(i);
}
CBcategorie = new JComboBox<Categorie>();
for (Categorie cat : budget.categories) {
CBcategorie.addItem(cat);
}
CBcategorie.addItemListener(this);
CBsousCategorie = new JComboBox<SousCategorie>();
Categorie cat = (Categorie) CBcategorie.getSelectedItem();
for (SousCategorie sousCat : cat.sousCategories)
CBsousCategorie.addItem(sousCat);
btSubmit = new JButton("Valider");
btCancel = new JButton("Annuler");
btSubmit.addActionListener(this);
btCancel.addActionListener(this);
montant.addFocusListener(this);
KeyAdapter actionClavier = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER)
btSubmit.doClick();
else if (key == KeyEvent.VK_ESCAPE)
btCancel.doClick();
}
};
panel = new JPanel(new GridLayout(8, 1));
panel.add(lblLibelle);
panel.add(libelle);
panel.add(lblMontant);
panel.add(montant);
panel.add(lblDate);
panel.add(date);
panel.add(lblCategorie);
panel.add(CBcategorie);
panel.add(lblSousCategorie);
panel.add(CBsousCategorie);
// panel.add(lblType);
// panel.add(CBtype);
panel.add(lblTypeES);
panel.add(CBtypeES);
panel.add(lblPeriodicite);
panel.add(CBperiodicite);
panel.add(btCancel);
panel.add(btSubmit);
setTitle("ROC2");
add(panel, BorderLayout.CENTER);
for (Component c : panel.getComponents()) {
c.addKeyListener(actionClavier);
}
}
/**
* Constructeur
*
* @param frame
* @param modal
* @param budget
* @param mouv
*/
public MouvementEditor(JFrame frame, boolean modal, Budget budget,
Mouvement mouv) {
this(frame, modal, budget);
mouvToEdit = mouv;
this.edit = true;
libelle.setText(mouv.libelle);
montant.setText(Float.toString(mouv.montant));
GregorianCalendar dateGreg = mouv.date;
DateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
dateFormat.setCalendar(dateGreg);
date.setText(dateFormat.format(dateGreg.getTime()));
Categorie categorie = null;
for (Categorie cat : budget.categories) {
if (cat.id == mouv.idCategorie) {
categorie = cat;
}
}
CBcategorie.setSelectedItem(categorie);
SousCategorie sousCategorie = null;
for (SousCategorie sousCat : categorie.sousCategories) {
if (sousCat.id == mouv.idSousCategorie) {
sousCategorie = sousCat;
}
}
CBsousCategorie.setSelectedItem(sousCategorie);
CBtypeES.setSelectedIndex(mouv.ESType);
CBperiodicite.setSelectedIndex(mouv.periodicite - 1);
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btCancel) {
this.setVisible(false);
mouvement = null;
}
if (e.getSource() == btSubmit) {
if (libelle.getText().length() > 3
&& montant.getText().length() > 0
&& Float.valueOf(montant.getText()) > 0.00
&& montant.getText().matches("[0-9]*\\.?[0-9]+$")
&& date.getText().matches("[1-31]\\.[1-12]\\.[1-2999]") && edit) {
Categorie cat = (Categorie) CBcategorie.getSelectedItem();
SousCategorie sousCat = (SousCategorie) CBsousCategorie
.getSelectedItem();
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Date dateDate = null;
try {
dateDate = df.parse(date.getText());
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dateDate);
mouvement = Roc2DB.editMouvement(mouvToEdit.id,
libelle.getText(), Float.parseFloat(montant.getText()),
1, CBtypeES.getSelectedIndex(), cal,
CBperiodicite.getSelectedIndex() + 1, cat, sousCat,
budget.idBudget);
setVisible(false);
} else if (libelle.getText().length() > 3
&& montant.getText().length() > 0
&& Float.valueOf(montant.getText()) > 0.00
&& montant.getText().matches("[0-9]*\\.?[0-9]+$")
&& !date.getText().matches("[1-31]\\.[1-12]\\.[1-2999]")
&& CBsousCategorie.getSelectedItem() != null) {
Categorie cat = (Categorie) CBcategorie.getSelectedItem();
SousCategorie sousCat = (SousCategorie) CBsousCategorie
.getSelectedItem();
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Date dateDate = null;
try {
dateDate = df.parse(date.getText());
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dateDate);
mouvement = Roc2DB.addMouvement(libelle.getText(),
Float.parseFloat(montant.getText()), 1,
CBtypeES.getSelectedIndex(), cal,
CBperiodicite.getSelectedIndex() + 1, cat, sousCat,
budget.idBudget);
setVisible(false);
} else {
String message = "";
if(libelle.getText().length() < 4){
message = message + "- Le libellé est trop court (4 caractères minimum)\n";
}
if(montant.getText().length() == 0){
message = message + "- Veuillez entrer un montant\n";
}else{
if(Float.valueOf(montant.getText()) == 0.0){
message = message + "- Veuillez entrer un montant non nul\n";
}
if(!montant.getText().matches("[0-9]*\\.?[0-9]")){
message = message + "- Veuillez entrez le montant sous la forme ##.##\n";
}
}
if(!date.getText().matches("[1-31]\\.[1-12]\\.[1-2999]")){
message = message + "- Veuillez entrer une date\n";
}
if(CBsousCategorie.getSelectedItem() == null){
message = message + "- Veuillez d'abors créer une sous catégorie\n";
}
JOptionPane.showMessageDialog(this,
message);
}
}
}
/*
* (non-Javadoc)
*
* @see
* java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
*/
@Override
public void itemStateChanged(ItemEvent e) {
CBsousCategorie.removeAllItems();
Categorie cat = (Categorie) CBcategorie.getSelectedItem();
for (SousCategorie sousCat : cat.sousCategories)
CBsousCategorie.addItem(sousCat);
}
@Override
public void focusGained(FocusEvent e) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
*
* @see java.awt.event.FocusListener#focusLost(java.awt.event.FocusEvent)
*/
@Override
public void focusLost(FocusEvent e) {
if (e.getSource() == montant) {
if (!montant.getText().matches("[0-9]*\\.?[0-9]+$")) {
montant.setText("0.00");
}
}
}
}
| true | true | public MouvementEditor(JFrame frame, boolean modal, Budget budget) {
super(frame, modal);
this.budget = budget;
MaskFormatter df = null;
try {
df = new MaskFormatter("##.##.####");
} catch (java.text.ParseException e) {
System.err.println(e);
}
;
df.setPlaceholderCharacter('_');
lblLibelle = new JLabel("Libellé:");
lblMontant = new JLabel("Montant:");
lblDate = new JLabel("Date:");
lblCategorie = new JLabel("Catégorie:");
lblSousCategorie = new JLabel("Sous-catégorie:");
lblType = new JLabel("Type:");
lblTypeES = new JLabel("Entrée/Sortie:");
lblPeriodicite = new JLabel("Périodicité:");
libelle = new JTextField(25);
montant = new JTextField(10);
date = new JFormattedTextField(df);
CBtype = new JComboBox<String>();
CBtype.addItem("Ponctuel");
CBtype.addItem("Récurrent");
CBtypeES = new JComboBox<String>();
CBtypeES.addItem("Entrée");
CBtypeES.addItem("Sortie");
CBperiodicite = new JComboBox<Integer>();
for (int i = 1; i < 12; i++) {
CBperiodicite.addItem(i);
}
CBcategorie = new JComboBox<Categorie>();
for (Categorie cat : budget.categories) {
CBcategorie.addItem(cat);
}
CBcategorie.addItemListener(this);
CBsousCategorie = new JComboBox<SousCategorie>();
Categorie cat = (Categorie) CBcategorie.getSelectedItem();
for (SousCategorie sousCat : cat.sousCategories)
CBsousCategorie.addItem(sousCat);
btSubmit = new JButton("Valider");
btCancel = new JButton("Annuler");
btSubmit.addActionListener(this);
btCancel.addActionListener(this);
montant.addFocusListener(this);
KeyAdapter actionClavier = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER)
btSubmit.doClick();
else if (key == KeyEvent.VK_ESCAPE)
btCancel.doClick();
}
};
panel = new JPanel(new GridLayout(8, 1));
panel.add(lblLibelle);
panel.add(libelle);
panel.add(lblMontant);
panel.add(montant);
panel.add(lblDate);
panel.add(date);
panel.add(lblCategorie);
panel.add(CBcategorie);
panel.add(lblSousCategorie);
panel.add(CBsousCategorie);
// panel.add(lblType);
// panel.add(CBtype);
panel.add(lblTypeES);
panel.add(CBtypeES);
panel.add(lblPeriodicite);
panel.add(CBperiodicite);
panel.add(btCancel);
panel.add(btSubmit);
setTitle("ROC2");
add(panel, BorderLayout.CENTER);
for (Component c : panel.getComponents()) {
c.addKeyListener(actionClavier);
}
}
| public MouvementEditor(JFrame frame, boolean modal, Budget budget) {
super(frame, modal);
this.budget = budget;
MaskFormatter df = null;
try {
df = new MaskFormatter("##.##.####");
} catch (java.text.ParseException e) {
System.err.println(e);
}
;
df.setPlaceholderCharacter('_');
lblLibelle = new JLabel("Libellé:");
lblMontant = new JLabel("Montant:");
lblDate = new JLabel("Date:");
lblCategorie = new JLabel("Catégorie:");
lblSousCategorie = new JLabel("Sous-catégorie:");
lblType = new JLabel("Type:");
lblTypeES = new JLabel("Entrée/Sortie:");
lblPeriodicite = new JLabel("Périodicité:");
libelle = new JTextField(25);
montant = new JTextField(10);
date = new JFormattedTextField(df);
CBtype = new JComboBox<String>();
CBtype.addItem("Ponctuel");
CBtype.addItem("Récurrent");
CBtypeES = new JComboBox<String>();
CBtypeES.addItem("Entrée");
CBtypeES.addItem("Sortie");
CBperiodicite = new JComboBox<Integer>();
for (int i = 1; i <= 12; i++) {
CBperiodicite.addItem(i);
}
CBcategorie = new JComboBox<Categorie>();
for (Categorie cat : budget.categories) {
CBcategorie.addItem(cat);
}
CBcategorie.addItemListener(this);
CBsousCategorie = new JComboBox<SousCategorie>();
Categorie cat = (Categorie) CBcategorie.getSelectedItem();
for (SousCategorie sousCat : cat.sousCategories)
CBsousCategorie.addItem(sousCat);
btSubmit = new JButton("Valider");
btCancel = new JButton("Annuler");
btSubmit.addActionListener(this);
btCancel.addActionListener(this);
montant.addFocusListener(this);
KeyAdapter actionClavier = new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER)
btSubmit.doClick();
else if (key == KeyEvent.VK_ESCAPE)
btCancel.doClick();
}
};
panel = new JPanel(new GridLayout(8, 1));
panel.add(lblLibelle);
panel.add(libelle);
panel.add(lblMontant);
panel.add(montant);
panel.add(lblDate);
panel.add(date);
panel.add(lblCategorie);
panel.add(CBcategorie);
panel.add(lblSousCategorie);
panel.add(CBsousCategorie);
// panel.add(lblType);
// panel.add(CBtype);
panel.add(lblTypeES);
panel.add(CBtypeES);
panel.add(lblPeriodicite);
panel.add(CBperiodicite);
panel.add(btCancel);
panel.add(btSubmit);
setTitle("ROC2");
add(panel, BorderLayout.CENTER);
for (Component c : panel.getComponents()) {
c.addKeyListener(actionClavier);
}
}
|